qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
63,415,954
why the result of C++ and python bitwise shift operator are diffrernt? python ``` >>> 1<<20 1048576 ``` C++ ``` cout <<1<<20; 120 ```
2020/08/14
[ "https://Stackoverflow.com/questions/63415954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13966865/" ]
The result differes because of the operator associativity in C++. ``` std::cout << 1 << 20; ``` is the same as ``` (std::cout << 1) << 20; ``` because `operator <<` is left-associative. What you intend to do is ``` std::cout << (1 << 20); ```
cout overloads the '<<' operator to print the values. So when you are doing ``` cout <<1<<20; ``` It actually prints 1 and 20 and doesnt do any shifting ``` int shifted = 1 << 20; cout << shifted; ``` This should return the same output as python's simpler way is to do ``` cout << (1 <<20); ```
69,592,525
I refer to [Python : Using the map function](https://stackoverflow.com/questions/18087544/python-using-the-map-function) It says "map returns a specific type of generator in Python 3 that is not a list (but rather a 'map object', as you can see). " That is my understanding too. Generator object do not contain the values but is able to give you the values when you call it (next()). So my question is where are those values store ? I tried the following experiment. 1. create 2 tuple and check their size 2. create 2 map objects from the tuple 3. do a next() on the map objects to use up some of the values 4. delete one of the tuple 5. continue to do next() I would assume that when I delete the tuple, there would be no more values to do a next() but that's not the case. So my question is where are those values coming from ? Where are they stored after I delete the tuple ? Code: ``` t1 = tuple(range(1000)) t2 = tuple(range(10000)) print(f'{t1[:10]} len = {len(t1):5d} size = {getsizeof(t1):5d}') print(f'{t2[:10]} len = {len(t2):5d} size = {getsizeof(t2):5d}') ``` Output: ``` (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) len = 1000 size = 8040 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) len = 10000 size = 80040 ``` Code: ``` m1 = map(lambda y: print(y), t1) m2 = map(lambda y: print(y), t2) print(f'size of m1 = {getsizeof(m1)}') print(f'size of m2 = {getsizeof(m2)}') ``` Output: ``` size of m1 = 48 size of m2 = 48 ``` Do the following a number of times: ``` next(m1) next(m2) ``` Output: ``` 23 23 ``` Delete the tuple: ``` import gc del t1 gc.collect() t1 ``` Output: ``` 168 --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-336-df561a5cc277> in <module> 2 del t1 3 gc.collect() ----> 4 t1 NameError: name 't1' is not defined ``` Continue next() ``` next(m1) next(m2) ``` Output: ``` 31 31 ``` I'm still able to get values from map after deleting the tuple.
2021/10/16
[ "https://Stackoverflow.com/questions/69592525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15670527/" ]
`del` doesn't remove the tuple from memory, it just removes the variable. The `map` object has its own reference to the tuple -- it's a class instance variable variable. Garbage collection doesn't remove a the tuple from memory until all references to it are destroyed. This will happen when the generator reaches the end (it should delete its own reference to avoid a memory leak) or if you delete the reference to the generator.
With `del t1` you delete the *variable*, not the object it references. Before `del t1`: [![before](https://i.stack.imgur.com/7EsXt.png)](https://i.stack.imgur.com/7EsXt.png) After `del t1`: [![after](https://i.stack.imgur.com/0xwMq.png)](https://i.stack.imgur.com/0xwMq.png) So that's still all alive and well and functional. You just don't have the separate `t1` variable referencing the tuple anymore.
69,141,448
I have an error that I cannot resolve. here is the error I get when I authenticate with postman: **TypeError: Object of type ObjectId is not JSON serializable // Werkzeug Debugger** **File "C:\Users\Amoungui\AppData\Local\Programs\Python\Python39\Lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.**class**.**name**} ' TypeError: Object of type ObjectId is not JSON serializable** Here is my code, I followed the official documentation, but at this does not work I do not understand. here is the link of the documentation: <https://pythonhosted.org/Flask-JWT/> customer.py ``` from flask import jsonify, make_response from config.mongoose import db import bson class Customer(db.Document): _id = db.ObjectIdField(default=bson.ObjectId, primary_key=True) #bson.ObjectId tel = db.StringField() password = db.StringField() def to_json(self): return { "_id": self._id, "tel": self.tel, "password": self.password, } def findAll(self): users = [] for user in self.objects: users.append(user) return users ``` service.py ``` from Models.Customer import Customer from werkzeug.security import safe_str_cmp find_by_username = {u.tel:u for u in Customer.objects} find_by_id = {u._id: u for u in Customer.objects} def auth(username, password): user = find_by_username.get(username, None) if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user def identity(payload): _id = payload['identity'] return find_by_id.get(_id) ``` thank's for your help
2021/09/11
[ "https://Stackoverflow.com/questions/69141448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12665256/" ]
Try to use `timestamps` in your schema after defining you fields. ``` const itemSchema = mongoose.Schema({ person_name: String, person_position: String, person_level: String, },{timestamps:true}); var RecordItem = mongoose.model("recorditem", itemSchema); ```
There are several ways to safe createdAt 1. timestamp : true in options 2. `createdAt: { type: Date, default: Date.now },` 3. itemSchema.pre('save', function(next) { if (!this.createdAt) { this.createdAt = new Date(); } next(); });
68,168,293
I am trying to retrieve data from SQL Server database using python but the system crash and display the below error: > > ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'where'. (156) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)") > > > Code: ``` import pandas as pd import streamlit as st search_term=st.text_input("Enter Search Term") cursor.execute("select * from testDB.dbo.t1 where ID = ? OR where first =?",search_term,search_term) dd = cursor.fetchall() print(dd) ```
2021/06/28
[ "https://Stackoverflow.com/questions/68168293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5980666/" ]
You have not declared user variable. Either declare it as follows: ``` const user = firebase.auth().currentUser ``` Or directly pass it as param if you don't need user object anywhere else: ``` .doc(firebase.auth().currentUser.uid) ```
You should initialize the user before using it. ``` // Your web app's Firebase configuration var firebaseConfig = { apiKey: "####", authDomain: "###.firebaseapp.com", projectId: "#", storageBucket: "#.appspot.com", messagingSenderId: "#", appId: "1:####" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); const auth = firebase.auth() const db = firebase.firestore() db.settings({ timestampsInSnapshots: true }) </script> <script> function savetodb() { var user = firebase.auth().currentUser; db.collection('users').doc(user.uid).get().then(doc => { const saveditems1 = doc.data().saveditems const ob = { Name:'Test', Price:'Test', Link:'https://www.test.com' } saveditems1.push(ob) }); ```
33,050,100
I am dealing with a simple csv file that contains three columns and three rows containing numeric data. The csv data file looks like the following: ``` Col1,Col2,Col3 1,2,3 2,2,3 3,2,3 4,2,3 ``` I have hard time figuring out how to let my python program subtracts the average value of the first column "Col1" from each value in the same column. For illustration the output should give the following values for 'Col1': ``` 1 - 2.5 = -1.5 2 - 2.5 = -0.5 3 - 2.5 = 0.5 4 - 2.5 = 1.5 ``` Here is my attempt that gives me (TypeError: unsupported operand type(s) for -: 'str' and 'float' ) at the last print statement which containing the comprehension. ``` import csv # Opening the csv file file1 = csv.DictReader(open('columns.csv')) file2 = csv.DictReader(open('columns.csv')) # Do some calculations NumOfSamples = open('columns.csv').read().count('\n') SumData = sum(float(row['Col1']) for row in file1) Aver = SumData/(NumOfSamples - 1) # compute the average of the data in 'Col1' # Subtracting the average from each value in 'Col1' data = [] for row in file2: data.append(row['Col1']) # Print the results print Aver print [e-Aver for e in data] # trying to use comprehension to subtract the average from each value in the list 'data' ``` I do not know how to solve this problem! Any idea how to make the comprehension working to give what is supposed to do?
2015/10/10
[ "https://Stackoverflow.com/questions/33050100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974919/" ]
Please show your html page from where you are sending post data. I think you should have to make an array of $\_POST variables then you can get all the records at php side and you can insert all three records in table. Try this Please check the below link where you can find your solution [Inserting Multiple Rows with PHP & MySQL](https://stackoverflow.com/questions/8235250/inserting-multiple-rows-with-php-mysql)
Create Model that holds all table columns. ``` class OrderModel extends BaseModel{ public $id; // Fill here all columns public function __construct($data) { foreach ($data as $key => $value) { $this->$key = $value; } } public function get_table_name() { return "ordering"; } } ``` Create Base model class and put insert method in this class. ``` public function insert() { $dbh = DB::connect(); $object_keys = array_keys(get_object_vars($this)); $query = "INSERT INTO " . $this->get_table_name() . " (" . implode(',', $object_keys) . ") VALUES(:" . implode(',:', $object_keys) . ");"; $sth = $dbh->prepare($query); foreach ($object_keys as $key) { $sth->bindParam(':' . $key, $this->$key); } $sth->execute(); $this->id = $dbh->lastInsertId(); return TRUE; } $filtered_post = filter_input_array(INPUT_POST); $order = New OrderModel($filtered_post); $order->insert(); ``` * Use PDO instead mysql\_ functions * Use Filter functions to filter POST Array
41,841,828
I would like to know if there is an else statement, like in python, that when attached to a **try-catch** structure, makes the block of code within it only executable if no exceptions were thrown/caught. For instance: ``` try { //code here } catch(...) { //exception handling here } ELSE { //this should execute only if no exceptions occurred } ```
2017/01/25
[ "https://Stackoverflow.com/questions/41841828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7408143/" ]
The concept of an `else` for a `try` block doesn't exist in c++. It can be emulated with the use of a flag: ``` { bool exception_caught = true; try { // Try block, without the else code: do_stuff_that_might_throw_an_exception(); exception_caught = false; // This needs to be the last statement in the try block } catch (Exception& a) { // Handle the exception or rethrow, but do not touch exception_caught. } // Other catches elided. if (! exception_caught) { // The equivalent of the python else block goes here. do_stuff_only_if_try_block_succeeded(); } } ``` The `do_stuff_only_if_try_block_succeeded()` code is executed only if the try block executes without throwing an exception. Note that in the case that `do_stuff_only_if_try_block_succeeded()` does throw an exception, that exception will not be caught. These two concepts mimic the intent of the python `try ... catch ... else` concept.
Why not just put it at the end of the try block?
59,694,929
i am creating a project where react is not rendering anything on django localhost index.html ``` <!DOCTYPE html> <html lang="en"> <head></head> <body> <div id="App"> <!---all will be define in App.js--> <h1>Index.html </h1> </div> </body> {% load static%} <script src="{% static "frontend/main.js" %}"></script> </html> ``` app.js ``` import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Header from './layout/header'; class App extends Component { render() { return ( <h1>App.JS</h1> ) } } ReactDOM.render(<App />, document.getElementById('app')); ``` this is my project structure: [![Project structure](https://i.stack.imgur.com/3GRVF.png)](https://i.stack.imgur.com/3GRVF.png) After running npm run dev and python manage.py runserver this is the status everything is fine till here: [![the status](https://i.stack.imgur.com/W4LNL.png)](https://i.stack.imgur.com/W4LNL.png)
2020/01/11
[ "https://Stackoverflow.com/questions/59694929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11631248/" ]
Change this source code: ``` document.getElementById('app') ``` ... to this: ``` document.getElementById('App') ```
Its because your element has id of "App" but you are trying to hook react app on element 'app'. It's case sensitive.
59,694,929
i am creating a project where react is not rendering anything on django localhost index.html ``` <!DOCTYPE html> <html lang="en"> <head></head> <body> <div id="App"> <!---all will be define in App.js--> <h1>Index.html </h1> </div> </body> {% load static%} <script src="{% static "frontend/main.js" %}"></script> </html> ``` app.js ``` import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Header from './layout/header'; class App extends Component { render() { return ( <h1>App.JS</h1> ) } } ReactDOM.render(<App />, document.getElementById('app')); ``` this is my project structure: [![Project structure](https://i.stack.imgur.com/3GRVF.png)](https://i.stack.imgur.com/3GRVF.png) After running npm run dev and python manage.py runserver this is the status everything is fine till here: [![the status](https://i.stack.imgur.com/W4LNL.png)](https://i.stack.imgur.com/W4LNL.png)
2020/01/11
[ "https://Stackoverflow.com/questions/59694929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11631248/" ]
Change this source code: ``` document.getElementById('app') ``` ... to this: ``` document.getElementById('App') ```
document.getElementById is case sensitive
39,760,629
UnitTests has a feature to capture `KeyboardInterrupt`, finishes a test and then report the results. > > **-c, --catch** > > > *Control-C* during the test run waits for the current test to end and then reports all the results so far. A second *Control-C* > raises the normal KeyboardInterrupt exception. > > > See Signal Handling for the functions that provide this functionality. > > > c.f. <https://docs.python.org/2/library/unittest.html#command-line-options> > > > In PyTest, `Ctrl`+`C` will just stop the session. Is there a way to do the same as UniTests: * Capture `KeyboardInterrupt` * Finishes to execute the on-going test [optional] * Skip other tests * Display a result, and potentially print a report (e.g. usage of `pytest-html`) Thanks **[Edit 11 November 2016]** I tried to put the hook in my `conftest.py` file but it does not seem to work and capture. In particular, the following does not write anything in `toto.txt`. ``` def pytest_keyboard_interrupt(excinfo): with open('toto.txt', 'w') as f: f.write("Hello") pytestmark = pytest.mark.skip('Interrupted Test Session') ``` Does anybody has a new suggestion?
2016/09/29
[ "https://Stackoverflow.com/questions/39760629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1603480/" ]
Your issue may lie in the execution ordering of your hook, such that pytest exits prior to your hook being executed. This could happen if an unhandled exception occurs in preexisting handling of the keyboard interrupt. To ensure your hook executes sooner, use `tryfirst` or `hookwrapper` as described [here](https://docs.pytest.org/en/latest/writing_plugins.html#hook-function-ordering-call-example). The following shall be written in **conftest.py** file: ``` import pytest @pytest.hookimpl(tryfirst=True) def pytest_keyboard_interrupt(excinfo): with open('toto.txt', 'w') as f: f.write("Hello") pytestmark = pytest.mark.skip('Interrupted Test Session') ```
Take a look at pytest's [hookspec](http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html). They have a hook for keyword interrupt. ``` def pytest_keyboard_interrupt(excinfo): """ called for keyboard interrupt. """ ```
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
The reason this doesn’t work on Python 2 lies in its implementation of `literal_eval`. The original implementation only performed number evaluation for additions and subtractions when the righth operand was a complex number. This is syntactically necessary for complex numbers to be expressed as a literal. This [was changed](https://hg.python.org/cpython/rev/884c71cd8dc6/) in Python 3 so that it supports any kind of valid number expression to be on either side of the addition and subtraction. However, the use of `literal_eval` is still restricted to additions and subtractions. This is mostly because `literal_eval` is supposed to be a function that turns a single *constant* literal (expressed as a string) into a Python object. Kind of like a backwards `repr` for simple built-in types. Actual expression evaluation is not included, and the fact that this works with Python 3 is just a nice-to-have side effect from its implementation. In order to evaluate actual expressions, without having to use `eval` (which we don’t want to), we can write our own expression evaluation algorithm that operates on the AST. This is pretty simple, especially for simple arithmetic operations on numbers (for example to build your own calculator etc.). We simply parse the string into an AST and then evaluate the resulting tree by looking at the different node types and applying the correct operation. Something like this: ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.div, ast.Mod: operator.mod } def arithmeticEval (s): node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ``` As you can see, this implementation is pretty straightforward. Of course it does not support more complex stuff like exponentiation and some unary nodes yet, but it’s not too difficult to add that. And it works just fine: ``` >>> arithmeticEval('4+2') 6 >>> arithmeticEval('4*1+2*6/3') 8 ``` You could even introduce more complex things later (for example function calls for things like `sin()`).
Use the source, luke! [`http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40`](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40) [`http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39`](http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39) You will find your answer in there. Specifically, the 2.7 version has the weird restriction on [line 70](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l70) that the right node of the BinOp is complex. ``` >>> sys.version '2.7.3 (default, Sep 26 2013, 20:03:06) \n[GCC 4.6.3]' >>> ast.literal_eval('9 + 0j') (9 + 0j) >>> ast.literal_eval('0j + 9') ValueError: malformed string ``` I'm guessing that the intention of 2.7 was to allow `literal_eval` of complex literals for example numbers like `9 + 0j`, and it was never intended to do simple integer additions. Then in python 3 they beefed up the `literal_eval` to handle these cases.
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
The reason this doesn’t work on Python 2 lies in its implementation of `literal_eval`. The original implementation only performed number evaluation for additions and subtractions when the righth operand was a complex number. This is syntactically necessary for complex numbers to be expressed as a literal. This [was changed](https://hg.python.org/cpython/rev/884c71cd8dc6/) in Python 3 so that it supports any kind of valid number expression to be on either side of the addition and subtraction. However, the use of `literal_eval` is still restricted to additions and subtractions. This is mostly because `literal_eval` is supposed to be a function that turns a single *constant* literal (expressed as a string) into a Python object. Kind of like a backwards `repr` for simple built-in types. Actual expression evaluation is not included, and the fact that this works with Python 3 is just a nice-to-have side effect from its implementation. In order to evaluate actual expressions, without having to use `eval` (which we don’t want to), we can write our own expression evaluation algorithm that operates on the AST. This is pretty simple, especially for simple arithmetic operations on numbers (for example to build your own calculator etc.). We simply parse the string into an AST and then evaluate the resulting tree by looking at the different node types and applying the correct operation. Something like this: ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.div, ast.Mod: operator.mod } def arithmeticEval (s): node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ``` As you can see, this implementation is pretty straightforward. Of course it does not support more complex stuff like exponentiation and some unary nodes yet, but it’s not too difficult to add that. And it works just fine: ``` >>> arithmeticEval('4+2') 6 >>> arithmeticEval('4*1+2*6/3') 8 ``` You could even introduce more complex things later (for example function calls for things like `sin()`).
It's in order to support complex numbers (since [issue 4907](http://bugs.python.org/issue4907)). For example, `1 + 2j` is parsed by the parser as an expression consisting of an integer literal, an addition operation and an [imaginary literal](http://docs.python.org/2/reference/lexical_analysis.html#imaginary-literals); but since [complex numbers](http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex) are a built-in type, it is desirable for `ast.literal_eval` to support complex number syntax. The [change in behaviour](http://hg.python.org/cpython/rev/884c71cd8dc6/) between 2.x and 3.x is to support writing the complex number the "wrong way round" e.g. `1j + 2`; the fact that it allows arbitrary addition or subtraction expressions is a (mostly unintended) side effect. If you want to parse arbitrary arithmetic expressions, you should parse to a syntax tree (using [`ast.parse`](http://docs.python.org/2/library/ast.html#ast.parse)), [verify it with a whitelist](https://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe), and then evaluate.
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
The reason this doesn’t work on Python 2 lies in its implementation of `literal_eval`. The original implementation only performed number evaluation for additions and subtractions when the righth operand was a complex number. This is syntactically necessary for complex numbers to be expressed as a literal. This [was changed](https://hg.python.org/cpython/rev/884c71cd8dc6/) in Python 3 so that it supports any kind of valid number expression to be on either side of the addition and subtraction. However, the use of `literal_eval` is still restricted to additions and subtractions. This is mostly because `literal_eval` is supposed to be a function that turns a single *constant* literal (expressed as a string) into a Python object. Kind of like a backwards `repr` for simple built-in types. Actual expression evaluation is not included, and the fact that this works with Python 3 is just a nice-to-have side effect from its implementation. In order to evaluate actual expressions, without having to use `eval` (which we don’t want to), we can write our own expression evaluation algorithm that operates on the AST. This is pretty simple, especially for simple arithmetic operations on numbers (for example to build your own calculator etc.). We simply parse the string into an AST and then evaluate the resulting tree by looking at the different node types and applying the correct operation. Something like this: ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.div, ast.Mod: operator.mod } def arithmeticEval (s): node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ``` As you can see, this implementation is pretty straightforward. Of course it does not support more complex stuff like exponentiation and some unary nodes yet, but it’s not too difficult to add that. And it works just fine: ``` >>> arithmeticEval('4+2') 6 >>> arithmeticEval('4*1+2*6/3') 8 ``` You could even introduce more complex things later (for example function calls for things like `sin()`).
It is not too hard to use [pyparsing](http://pyparsing.wikispaces.com) to cobble together a simple expression evaluator. Suppose you want to eval expression, including parens, of the type of expressions of the following: ``` 2+3 4.0^2+5*(2+3+4) 1.23+4.56-7.890 (1+2+3+4)/5 1e6^2/1e7 ``` This simplification of the [SimpleCalc](http://pyparsing.wikispaces.com/file/view/SimpleCalc.py/30112812/SimpleCalc.py) example: ``` import pyparsing as pp import re ex='''\ 2+3 4.0^2+5*(2+3+4) 1.23+4.56-7.890 (1+2+3+4)/5 1e6^2/1e7''' e = pp.CaselessLiteral('E') dec, plus, minus, mult, div, expop=map(pp.Literal,'.+-*/^') addop = plus | minus multop = mult | div lpar, rpar=map(pp.Suppress,'()') p_m = plus | minus num = pp.Word(pp.nums) integer = pp.Combine( pp.Optional(p_m) + num ) floatnumber = pp.Combine( integer + pp.Optional( dec + pp.Optional(num) ) + pp.Optional( e + integer ) ) stack=[] def pushFirst(s, l, t): stack.append( t[0] ) expr=pp.Forward() atom = ((floatnumber | integer).setParseAction(pushFirst) | ( lpar + expr.suppress() + rpar ) ) factor = pp.Forward() factor << atom + pp.ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) ) term = factor + pp.ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) ) expr << term + pp.ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) ) pattern=expr+pp.StringEnd() opn = { "+" : ( lambda a,b: a + b ), "-" : ( lambda a,b: a - b ), "*" : ( lambda a,b: a * b ), "/" : ( lambda a,b: a / b ), "^" : ( lambda a,b: a ** b ) } def evaluateStack(stk): op = stk.pop() if op in "+-*/^": op2 = evaluateStack(stk) op1 = evaluateStack(stk) return opn[op](op1, op2) elif re.search('^[-+]?[0-9]+$',op): return int(op) else: return float(op) for line in ex.splitlines(): parse=pattern.parseString(line) s=stack[:] print('"{}"->{} = {}'.format(line,s,evaluateStack(stack))) ``` Prints: ``` "2+3"->['2', '3', '+'] = 5 "4.0^2+5*(2+3+4)"->['4.0', '2', '^', '5', '2', '3', '+', '4', '+', '*', '+'] = 61.0 "1.23+4.56-7.890"->['1.23', '4.56', '+', '7.890', '-'] = -2.1000000000000005 "(1+2+3+4)/5"->['1', '2', '+', '3', '+', '4', '+', '5', '/'] = 2.0 "1e6^2/1e7"->['1E6', '2', '^', '1E7', '/'] = 100000.0 ```
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
The reason this doesn’t work on Python 2 lies in its implementation of `literal_eval`. The original implementation only performed number evaluation for additions and subtractions when the righth operand was a complex number. This is syntactically necessary for complex numbers to be expressed as a literal. This [was changed](https://hg.python.org/cpython/rev/884c71cd8dc6/) in Python 3 so that it supports any kind of valid number expression to be on either side of the addition and subtraction. However, the use of `literal_eval` is still restricted to additions and subtractions. This is mostly because `literal_eval` is supposed to be a function that turns a single *constant* literal (expressed as a string) into a Python object. Kind of like a backwards `repr` for simple built-in types. Actual expression evaluation is not included, and the fact that this works with Python 3 is just a nice-to-have side effect from its implementation. In order to evaluate actual expressions, without having to use `eval` (which we don’t want to), we can write our own expression evaluation algorithm that operates on the AST. This is pretty simple, especially for simple arithmetic operations on numbers (for example to build your own calculator etc.). We simply parse the string into an AST and then evaluate the resulting tree by looking at the different node types and applying the correct operation. Something like this: ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.div, ast.Mod: operator.mod } def arithmeticEval (s): node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ``` As you can see, this implementation is pretty straightforward. Of course it does not support more complex stuff like exponentiation and some unary nodes yet, but it’s not too difficult to add that. And it works just fine: ``` >>> arithmeticEval('4+2') 6 >>> arithmeticEval('4*1+2*6/3') 8 ``` You could even introduce more complex things later (for example function calls for things like `sin()`).
An updated version of the answer from @poke that allows negative numbers in py3.x or other unary operators. So "-3" evaluates to -3 for example, rather than an error. ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def arithmetic_eval(s): binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) elif isinstance(node, ast.UnaryOp): return unOps[type(node.op)](_eval(node.operand)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ```
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
It's in order to support complex numbers (since [issue 4907](http://bugs.python.org/issue4907)). For example, `1 + 2j` is parsed by the parser as an expression consisting of an integer literal, an addition operation and an [imaginary literal](http://docs.python.org/2/reference/lexical_analysis.html#imaginary-literals); but since [complex numbers](http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex) are a built-in type, it is desirable for `ast.literal_eval` to support complex number syntax. The [change in behaviour](http://hg.python.org/cpython/rev/884c71cd8dc6/) between 2.x and 3.x is to support writing the complex number the "wrong way round" e.g. `1j + 2`; the fact that it allows arbitrary addition or subtraction expressions is a (mostly unintended) side effect. If you want to parse arbitrary arithmetic expressions, you should parse to a syntax tree (using [`ast.parse`](http://docs.python.org/2/library/ast.html#ast.parse)), [verify it with a whitelist](https://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe), and then evaluate.
Use the source, luke! [`http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40`](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40) [`http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39`](http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39) You will find your answer in there. Specifically, the 2.7 version has the weird restriction on [line 70](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l70) that the right node of the BinOp is complex. ``` >>> sys.version '2.7.3 (default, Sep 26 2013, 20:03:06) \n[GCC 4.6.3]' >>> ast.literal_eval('9 + 0j') (9 + 0j) >>> ast.literal_eval('0j + 9') ValueError: malformed string ``` I'm guessing that the intention of 2.7 was to allow `literal_eval` of complex literals for example numbers like `9 + 0j`, and it was never intended to do simple integer additions. Then in python 3 they beefed up the `literal_eval` to handle these cases.
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
Use the source, luke! [`http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40`](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40) [`http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39`](http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39) You will find your answer in there. Specifically, the 2.7 version has the weird restriction on [line 70](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l70) that the right node of the BinOp is complex. ``` >>> sys.version '2.7.3 (default, Sep 26 2013, 20:03:06) \n[GCC 4.6.3]' >>> ast.literal_eval('9 + 0j') (9 + 0j) >>> ast.literal_eval('0j + 9') ValueError: malformed string ``` I'm guessing that the intention of 2.7 was to allow `literal_eval` of complex literals for example numbers like `9 + 0j`, and it was never intended to do simple integer additions. Then in python 3 they beefed up the `literal_eval` to handle these cases.
An updated version of the answer from @poke that allows negative numbers in py3.x or other unary operators. So "-3" evaluates to -3 for example, rather than an error. ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def arithmetic_eval(s): binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) elif isinstance(node, ast.UnaryOp): return unOps[type(node.op)](_eval(node.operand)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ```
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
It's in order to support complex numbers (since [issue 4907](http://bugs.python.org/issue4907)). For example, `1 + 2j` is parsed by the parser as an expression consisting of an integer literal, an addition operation and an [imaginary literal](http://docs.python.org/2/reference/lexical_analysis.html#imaginary-literals); but since [complex numbers](http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex) are a built-in type, it is desirable for `ast.literal_eval` to support complex number syntax. The [change in behaviour](http://hg.python.org/cpython/rev/884c71cd8dc6/) between 2.x and 3.x is to support writing the complex number the "wrong way round" e.g. `1j + 2`; the fact that it allows arbitrary addition or subtraction expressions is a (mostly unintended) side effect. If you want to parse arbitrary arithmetic expressions, you should parse to a syntax tree (using [`ast.parse`](http://docs.python.org/2/library/ast.html#ast.parse)), [verify it with a whitelist](https://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe), and then evaluate.
It is not too hard to use [pyparsing](http://pyparsing.wikispaces.com) to cobble together a simple expression evaluator. Suppose you want to eval expression, including parens, of the type of expressions of the following: ``` 2+3 4.0^2+5*(2+3+4) 1.23+4.56-7.890 (1+2+3+4)/5 1e6^2/1e7 ``` This simplification of the [SimpleCalc](http://pyparsing.wikispaces.com/file/view/SimpleCalc.py/30112812/SimpleCalc.py) example: ``` import pyparsing as pp import re ex='''\ 2+3 4.0^2+5*(2+3+4) 1.23+4.56-7.890 (1+2+3+4)/5 1e6^2/1e7''' e = pp.CaselessLiteral('E') dec, plus, minus, mult, div, expop=map(pp.Literal,'.+-*/^') addop = plus | minus multop = mult | div lpar, rpar=map(pp.Suppress,'()') p_m = plus | minus num = pp.Word(pp.nums) integer = pp.Combine( pp.Optional(p_m) + num ) floatnumber = pp.Combine( integer + pp.Optional( dec + pp.Optional(num) ) + pp.Optional( e + integer ) ) stack=[] def pushFirst(s, l, t): stack.append( t[0] ) expr=pp.Forward() atom = ((floatnumber | integer).setParseAction(pushFirst) | ( lpar + expr.suppress() + rpar ) ) factor = pp.Forward() factor << atom + pp.ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) ) term = factor + pp.ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) ) expr << term + pp.ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) ) pattern=expr+pp.StringEnd() opn = { "+" : ( lambda a,b: a + b ), "-" : ( lambda a,b: a - b ), "*" : ( lambda a,b: a * b ), "/" : ( lambda a,b: a / b ), "^" : ( lambda a,b: a ** b ) } def evaluateStack(stk): op = stk.pop() if op in "+-*/^": op2 = evaluateStack(stk) op1 = evaluateStack(stk) return opn[op](op1, op2) elif re.search('^[-+]?[0-9]+$',op): return int(op) else: return float(op) for line in ex.splitlines(): parse=pattern.parseString(line) s=stack[:] print('"{}"->{} = {}'.format(line,s,evaluateStack(stack))) ``` Prints: ``` "2+3"->['2', '3', '+'] = 5 "4.0^2+5*(2+3+4)"->['4.0', '2', '^', '5', '2', '3', '+', '4', '+', '*', '+'] = 61.0 "1.23+4.56-7.890"->['1.23', '4.56', '+', '7.890', '-'] = -2.1000000000000005 "(1+2+3+4)/5"->['1', '2', '+', '3', '+', '4', '+', '5', '/'] = 2.0 "1e6^2/1e7"->['1E6', '2', '^', '1E7', '/'] = 100000.0 ```
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
It's in order to support complex numbers (since [issue 4907](http://bugs.python.org/issue4907)). For example, `1 + 2j` is parsed by the parser as an expression consisting of an integer literal, an addition operation and an [imaginary literal](http://docs.python.org/2/reference/lexical_analysis.html#imaginary-literals); but since [complex numbers](http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex) are a built-in type, it is desirable for `ast.literal_eval` to support complex number syntax. The [change in behaviour](http://hg.python.org/cpython/rev/884c71cd8dc6/) between 2.x and 3.x is to support writing the complex number the "wrong way round" e.g. `1j + 2`; the fact that it allows arbitrary addition or subtraction expressions is a (mostly unintended) side effect. If you want to parse arbitrary arithmetic expressions, you should parse to a syntax tree (using [`ast.parse`](http://docs.python.org/2/library/ast.html#ast.parse)), [verify it with a whitelist](https://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe), and then evaluate.
An updated version of the answer from @poke that allows negative numbers in py3.x or other unary operators. So "-3" evaluates to -3 for example, rather than an error. ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def arithmetic_eval(s): binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) elif isinstance(node, ast.UnaryOp): return unOps[type(node.op)](_eval(node.operand)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ```
20,748,202
It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted However In python 2.7 it returns `ValueError: malformed string` when running this example: ``` >>> ast.literal_eval("4 + 9") ``` Whereas in python 3.3 this example works as expected: ``` >>> ast.literal_eval('4+9') 13 ``` Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky `eval()` function?
2013/12/23
[ "https://Stackoverflow.com/questions/20748202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425215/" ]
It is not too hard to use [pyparsing](http://pyparsing.wikispaces.com) to cobble together a simple expression evaluator. Suppose you want to eval expression, including parens, of the type of expressions of the following: ``` 2+3 4.0^2+5*(2+3+4) 1.23+4.56-7.890 (1+2+3+4)/5 1e6^2/1e7 ``` This simplification of the [SimpleCalc](http://pyparsing.wikispaces.com/file/view/SimpleCalc.py/30112812/SimpleCalc.py) example: ``` import pyparsing as pp import re ex='''\ 2+3 4.0^2+5*(2+3+4) 1.23+4.56-7.890 (1+2+3+4)/5 1e6^2/1e7''' e = pp.CaselessLiteral('E') dec, plus, minus, mult, div, expop=map(pp.Literal,'.+-*/^') addop = plus | minus multop = mult | div lpar, rpar=map(pp.Suppress,'()') p_m = plus | minus num = pp.Word(pp.nums) integer = pp.Combine( pp.Optional(p_m) + num ) floatnumber = pp.Combine( integer + pp.Optional( dec + pp.Optional(num) ) + pp.Optional( e + integer ) ) stack=[] def pushFirst(s, l, t): stack.append( t[0] ) expr=pp.Forward() atom = ((floatnumber | integer).setParseAction(pushFirst) | ( lpar + expr.suppress() + rpar ) ) factor = pp.Forward() factor << atom + pp.ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) ) term = factor + pp.ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) ) expr << term + pp.ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) ) pattern=expr+pp.StringEnd() opn = { "+" : ( lambda a,b: a + b ), "-" : ( lambda a,b: a - b ), "*" : ( lambda a,b: a * b ), "/" : ( lambda a,b: a / b ), "^" : ( lambda a,b: a ** b ) } def evaluateStack(stk): op = stk.pop() if op in "+-*/^": op2 = evaluateStack(stk) op1 = evaluateStack(stk) return opn[op](op1, op2) elif re.search('^[-+]?[0-9]+$',op): return int(op) else: return float(op) for line in ex.splitlines(): parse=pattern.parseString(line) s=stack[:] print('"{}"->{} = {}'.format(line,s,evaluateStack(stack))) ``` Prints: ``` "2+3"->['2', '3', '+'] = 5 "4.0^2+5*(2+3+4)"->['4.0', '2', '^', '5', '2', '3', '+', '4', '+', '*', '+'] = 61.0 "1.23+4.56-7.890"->['1.23', '4.56', '+', '7.890', '-'] = -2.1000000000000005 "(1+2+3+4)/5"->['1', '2', '+', '3', '+', '4', '+', '5', '/'] = 2.0 "1e6^2/1e7"->['1E6', '2', '^', '1E7', '/'] = 100000.0 ```
An updated version of the answer from @poke that allows negative numbers in py3.x or other unary operators. So "-3" evaluates to -3 for example, rather than an error. ``` import ast, operator binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def arithmetic_eval(s): binOps = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod } unOps = { ast.USub: operator.neg } node = ast.parse(s, mode='eval') def _eval(node): if isinstance(node, ast.Expression): return _eval(node.body) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return binOps[type(node.op)](_eval(node.left), _eval(node.right)) elif isinstance(node, ast.UnaryOp): return unOps[type(node.op)](_eval(node.operand)) else: raise Exception('Unsupported type {}'.format(node)) return _eval(node.body) ```
61,385,841
I have specific question. I have lego EV3 and i installed Micropython. But i want import turtle, tkinter and other modules and they aren't in micropython. But time module working.Do someone know what modules are in ev3 micropython? Thanks for answer.
2020/04/23
[ "https://Stackoverflow.com/questions/61385841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13045504/" ]
To add bearer token in retrofit, you have to create a class that implements `Interceptor` ``` public class TokenInterceptor implements Interceptor{ @Override public Response intercept(Chain chain) throws IOException { //rewrite the request to add bearer token Request newRequest=chain.request().newBuilder() .header("Authorization","Bearer "+ yourtokenvalue) .build(); return chain.proceed(newRequest); } } ``` Now add your Interceptor class in OKHttpClient object and add that obejct in Retrofit object: ``` TokenInterceptor interceptor=new TokenInterceptor(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor). .build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl("add your url here") .addConverterFactory(JacksonConverterFactory.create()) .build(); ```
these three class will be your final setup for all types of call > > for first call(Login) you do not need to pass token and after login pass jwt as bearer token to authenticate after authentication do not need to pass > > > ``` public class ApiUtils { private static final String BASE_URL="https://abcd.abcd.com/"; public ApiUtils() { } public static API getApiService(String token){ return RetrofitClient.getClient(BASE_URL,token).create(API.class); }} ``` 2.Using ApiUtils.getapiService you can get the client ,pass jwt or bearer token ``` public class RetrofitClient { public static Retrofit retrofit=null; public static Retrofit getClient(String baseUrl, String token){ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .readTimeout(60,TimeUnit.SECONDS) .connectTimeout(60,TimeUnit.SECONDS) .addInterceptor(interceptor) .addInterceptor(new Interceptor() { @NotNull @Override public Response intercept(@NotNull Chain chain) throws IOException { Request request=chain.request().newBuilder() .addHeader("Authorization", "Bearer " + token) .build(); return chain.proceed(request); } }).build(); if(retrofit==null||token!=null){ retrofit= new Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; }} ``` 3 In this Interface you can create methods for get or post requests ``` public interface API { @POST("/Api/Authentication/Login") Call<JsonObject> login(@Body Model userdata); @POST("/api/Authentication/ValidateSession") Call<JsonObject> validateSession(@Body MyToken myToken); @POST("/api/master/abcd") Call<JsonObject> phoneDir(@Body JsonObject jsonObject); @Multipart @POST("/api/dash/UploadProfilePic") Call<JsonObject> uploadProfile(@Part MultipartBody.Part part); @FormUrlEncoded @POST("/api/dashboard/RulesAndPolicies") Call<JsonObject> rulesAndProcess(@Field("ct") int city); @FormUrlEncoded @POST("/api/dashboard/RulesAndPolicies") Call<JsonObject> rulesAndProcess( @Field("city") int city, @Field("department") String department, @Field("ctype") String ctype ); ```
38,775,586
The following python code: ``` # user profile information args = { 'access_token':access_token, 'fields':'id,name', } print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me', urllib.urlencode(args)).read() ``` Prints the following: *ACCESSED {"success":true}* The token is valid, no error, the fields are valid. Why is it not returning the fields I asked for?
2016/08/04
[ "https://Stackoverflow.com/questions/38775586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1507649/" ]
Turns out urllib.urlopen will send the data as a POST when the data parameter is provided. Facebook Graph API works using GET not POST. Change the call to trick the function into calling just a URL ( no data ): ``` print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me/?' + urllib.urlencode(args)).read() ``` And everything works! Sigh, I can see why urllib is being altered in python 3.0...
You have to add a `/` to the URL to get `https://graph.facebook.com/me/` instead of `https://graph.facebook.com/me`. ``` # user profile information args = { 'access_token':access_token, 'fields':'id,name' } print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me/', urllib.urlencode(args)).read() ``` PS : Try using the `requests` which is much more efficient than `urllib`, here is the doc : <http://docs.python-requests.org/en/master/>
73,009,209
I have a pandas datafrme with a text column and was wondering how can I count the number of line breaks.This is how it's done in excel and would like to now how I can achieve this in python: [How To Count Number Of Lines (Line Breaks) In A Cell In Excel?](https://www.extendoffice.com/documents/excel/4785-excel-count-newlines.html#:%7E:text=This%20formula%20%3DLEN(A2)%2D,0%20for%20a%20blank%20cell.)
2022/07/17
[ "https://Stackoverflow.com/questions/73009209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7297511/" ]
Your approach is slow because you loop over the rows and use intermediate copies. You should be able to use boolean indexing for direct swapping: ``` mask = final['HomeAway'].eq(0) final.loc[mask, 4:124], final.loc[mask, 124:] = final.loc[mask, 124:], final.loc[mask, 4:124] ```
The Data on which you are working is unknown and I have tried to replicate your problem with duplicate data. Change the variables and the indexing values while using it in your project **CODE** ``` import pandas as pd import numpy as np data = pd.DataFrame({"HomeAway": [1, 1, 0, 0, 1], "Value1": [14, 16, 29, 22, 21], "Value2": [8, 14, 24, 14, 19], "Value3": [6, 2, 5, 8, 2], "Value4": [3, 3, 2, 2, 0]}) print("BEFORE") print(data) left = np.asanyarray(data[data["HomeAway"] == 0].iloc[:, 1:3]) right = np.asanyarray(data[data["HomeAway"] == 0].iloc[:, 3:5]) data.iloc[data["HomeAway"] == 0, 1:3] = right data.iloc[data["HomeAway"] == 0, 3:5] = left print("AFTER") print(data) ``` **OUTPUT** ``` BEFORE HomeAway Value1 Value2 Value3 Value4 0 1 14 8 6 3 1 1 16 14 2 3 2 0 29 24 5 2 3 0 22 14 8 2 4 1 21 19 2 0 AFTER HomeAway Value1 Value2 Value3 Value4 0 1 14 8 6 3 1 1 16 14 2 3 2 0 5 2 29 24 3 0 8 2 22 14 4 1 21 19 2 0 ```
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
``` from django.contrib import admin,include admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` maybe you missed "include" in the first line
``` Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ``` This error message should list all possible URLs, including the 'expanded' urls from your pnasser app. Since you're only getting the URLs from your main urls.py, it suggests you haven't properly enabled the `pnasser` app in settings.py's `INSTALLED_APPS`.
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
The problem seemed to be in the django.wsgi file - and the differences in how the standard django.wsgi file loads a python site vs how the development server loads the site. I guess it's a well known issue, that I was unaware of. Thanks everyone for the suggestions. Alternative django.wsgi file found here: <http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html>
The following works for me: > > If your urls are not working correctly, you may need to add this line > to location /: > > > > ``` > fastcgi_split_path_info ^()(.*)$; > > ``` > > From: <https://code.djangoproject.com/wiki/DjangoAndNginx>
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
``` from django.contrib import admin,include admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` maybe you missed "include" in the first line
Within your URL's file you can write something like the following below. += obviously allows us to add additional 'patterns' to our 'urlpatterns' variable, this also means we can wrap these in an 'if' statement. ``` urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('', (r'^api/', include('api.urls')), ) if settings.SHOP_TOGGLE: urlpatterns += patterns('', (r'^shop/', include('shop.urls')),) ) ```
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
The problem seemed to be in the django.wsgi file - and the differences in how the standard django.wsgi file loads a python site vs how the development server loads the site. I guess it's a well known issue, that I was unaware of. Thanks everyone for the suggestions. Alternative django.wsgi file found here: <http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html>
``` Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ``` This error message should list all possible URLs, including the 'expanded' urls from your pnasser app. Since you're only getting the URLs from your main urls.py, it suggests you haven't properly enabled the `pnasser` app in settings.py's `INSTALLED_APPS`.
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
``` from django.contrib import admin,include admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` maybe you missed "include" in the first line
The following works for me: > > If your urls are not working correctly, you may need to add this line > to location /: > > > > ``` > fastcgi_split_path_info ^()(.*)$; > > ``` > > From: <https://code.djangoproject.com/wiki/DjangoAndNginx>
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
The problem seemed to be in the django.wsgi file - and the differences in how the standard django.wsgi file loads a python site vs how the development server loads the site. I guess it's a well known issue, that I was unaware of. Thanks everyone for the suggestions. Alternative django.wsgi file found here: <http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html>
``` from django.contrib import admin,include admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` maybe you missed "include" in the first line
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
Within your URL's file you can write something like the following below. += obviously allows us to add additional 'patterns' to our 'urlpatterns' variable, this also means we can wrap these in an 'if' statement. ``` urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('', (r'^api/', include('api.urls')), ) if settings.SHOP_TOGGLE: urlpatterns += patterns('', (r'^shop/', include('shop.urls')),) ) ```
The following works for me: > > If your urls are not working correctly, you may need to add this line > to location /: > > > > ``` > fastcgi_split_path_info ^()(.*)$; > > ``` > > From: <https://code.djangoproject.com/wiki/DjangoAndNginx>
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
The problem is that you are using an empty regex (`"^"` will match anything, including an empty url) to handle an include directive. If you do that, it will always append a first slash at your request path. Considering that on your pnasser.urls does not contain a regex for "/", there is no match for a request on mysite.com. If you want mysite.com or mysite.com/ to take you to pnasser "index" view, you need to have something like: ``` from django.contrib import admin from pnasser.views import index admin.autodiscover() urlpatterns = patterns('', (r'^/?$', index), (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), ) ``` So, you have: * mysite.com => pnasser.views.index * mysite.com/ => pnasser.views.index * mysite.com/admin => admin page * mysite.com/pnasser/ => pnasser.views.index * mysite.com/pnasser/home => pnasser.views.home If this doesn't work, make sure that you have [Django's CommonMiddleware](https://docs.djangoproject.com/en/dev/ref/middleware/#module-django.middleware.common) installed, and make you have `APPEND_SLASH = True` (it is the default, so you shouldn't need to mess with this if you don't find it in your settings.py file).
``` Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ``` This error message should list all possible URLs, including the 'expanded' urls from your pnasser app. Since you're only getting the URLs from your main urls.py, it suggests you haven't properly enabled the `pnasser` app in settings.py's `INSTALLED_APPS`.
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
The problem seemed to be in the django.wsgi file - and the differences in how the standard django.wsgi file loads a python site vs how the development server loads the site. I guess it's a well known issue, that I was unaware of. Thanks everyone for the suggestions. Alternative django.wsgi file found here: <http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html>
Within your URL's file you can write something like the following below. += obviously allows us to add additional 'patterns' to our 'urlpatterns' variable, this also means we can wrap these in an 'if' statement. ``` urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('', (r'^api/', include('api.urls')), ) if settings.SHOP_TOGGLE: urlpatterns += patterns('', (r'^shop/', include('shop.urls')),) ) ```
7,733,200
I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine ``` from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) ``` I then have a folder pnasser, with the file urls.py with the following: ``` from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) ``` I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > > Using the URLconf defined in mysite.urls, Django tried these URL > patterns, in this order: > 1. ^pnasser/ > 2. ^admin/ > > > The current URL, , didn't match any of these. > > > **edit** settings.py installed apps: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) ``` **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod\_wsgi is the problem. However, I'm not sure where the problem would be
2011/10/11
[ "https://Stackoverflow.com/questions/7733200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225600/" ]
The problem is that you are using an empty regex (`"^"` will match anything, including an empty url) to handle an include directive. If you do that, it will always append a first slash at your request path. Considering that on your pnasser.urls does not contain a regex for "/", there is no match for a request on mysite.com. If you want mysite.com or mysite.com/ to take you to pnasser "index" view, you need to have something like: ``` from django.contrib import admin from pnasser.views import index admin.autodiscover() urlpatterns = patterns('', (r'^/?$', index), (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), ) ``` So, you have: * mysite.com => pnasser.views.index * mysite.com/ => pnasser.views.index * mysite.com/admin => admin page * mysite.com/pnasser/ => pnasser.views.index * mysite.com/pnasser/home => pnasser.views.home If this doesn't work, make sure that you have [Django's CommonMiddleware](https://docs.djangoproject.com/en/dev/ref/middleware/#module-django.middleware.common) installed, and make you have `APPEND_SLASH = True` (it is the default, so you shouldn't need to mess with this if you don't find it in your settings.py file).
The following works for me: > > If your urls are not working correctly, you may need to add this line > to location /: > > > > ``` > fastcgi_split_path_info ^()(.*)$; > > ``` > > From: <https://code.djangoproject.com/wiki/DjangoAndNginx>
56,093,339
I'm currently trying to write a script that does a specific action on a certain day. So for example, if today is the 6/30/2019 and in my dataframe there is a 6/30/2019 entry, xyz proceeds to happen. However, I am having troubles comparing the date from a dataframe to a DateTime date. Here's how I created the dataframe ``` now = datetime.datetime.now() Test1 = pd.read_excel(r"some path") ``` Heres what the output looks like when I print the dataframe. ``` symbol ... phase 0 MDCO ... Phase 2 1 FTSV ... Phase 1/2 2 NVO ... Phase 2 3 PFE ... PDUFA priority review 4 ATRA ... Phase 1 ``` Heres' how the 'event\_date' column prints out ``` 0 05/18/2019 1 06/30/2019 2 06/30/2019 3 06/11/2019 4 06/29/2019 ``` So I've tried a few things I've seen in other threads. I've tried: ``` if (Test1['event_date'] == now): print('True') ``` That returns ``` ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). ``` I've tried reformatting my the data with: ``` column_A = datetime.strptime(Test1['event_date'], '%m %d %y').date() ``` which returns this ``` TypeError: strptime() argument 1 must be str, not Series ``` I've tried this ``` if any(Test1.loc(Test1['event_date'])) == now: ``` and that returned this ``` TypeError: 'Series' objects are mutable, thus they cannot be hashed ``` I don't know why python is telling me the str is a dataframe, I'm assuming it has something to do with how python exports data from an excel sheet. I'm not sure how to fix this. I simply want python to check if any of the rows have the same `"event_date"` value as the current date and return the index or return a boolean to be used in a loop.
2019/05/11
[ "https://Stackoverflow.com/questions/56093339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11486279/" ]
``` import datetime import pandas as pd da = str(datetime.datetime.now().date()) # converting the column to datetime, you can check the dtype of the column by doing # df['event_date'].dtypes df['event_date'] = pd.to_datetime(df['event_date']) # generate a df with rows where there is a match df_co = df.loc[df['event_date'] == da] ``` I would suggest doing xy or what is required in a column based on the match in the same column. i.e. `df.loc[df['event_date'] == da,'column name'] = df['x'] + df['y']` Easier than looping.
``` import pandas as pd import time # keep only y,m,d, and throw out the rest: now = (time.strftime("%Y/%m/%d")) # the column in the dataframe needs to be converted to datetime first. df['event_date'] = pd.to_datetime(df['event_date']) # to return indices df[df['event_date']==now].index.values # if you want to loop, you can do: for ix, row in df.iterrows(): if row['event_date'] == now: print(ix) ```
44,089,727
i have a weekly report that i need to do, i chooseed to create it with openpyxl python module, and send it via mail, when i open the received mail (outlook), the cells with formulas appears as empty, but when downloading the file and open it, the data appears, OS fedora 20. parts of the code : ``` # imported modules from openpyxl ... wb = Workbook() ws = wb.active counter = 3 ws.append(row) for day in data : row = ['']*(len(hosts)*2 +5) row[0] = day.dayDate row[1] ='=SUM(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+\ ')/(COUNT(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+'))' row[2] = '=SUM('+get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')/COUNT('+\ get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')' row[3] = '=MAX('+get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')' row[4] = '=_xlfn.STDEV.P('+get_column_letter(len(hosts)+6)+str(counter)\ +':'+get_column_letter(len(hosts)*2+5)+str(counter)+')' counter += 1 ``` then, i create from the date some charts, etc.. and save, then send via mail : ``` wb.save(pathToFile+fileName+'.xlsx') os.system('echo -e "'+msg+'" | mail -s "'+fileName+'" -a '+\ pathToFile+fileName+'.xlsx -r '+myUsr+' '+ppl2send2) ``` those are parts of the actual code, any one have an idea why the email don't show the results of the formulas in the cells ? Thanks in advance :) [![enter image description here](https://i.stack.imgur.com/iZ7IQ.png)](https://i.stack.imgur.com/iZ7IQ.png)
2017/05/20
[ "https://Stackoverflow.com/questions/44089727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6424190/" ]
Unfortunately not. There is no language support for what you want. Let me be specific about what you want just so that you understand what I answered. Your question is basically this: Given that I have *two* instances of an object, and I have properties in this object that have a private setter, is there any language support for ensuring that instance #1 cannot change this private information of instance #2? And the answer is no. This will compile and "work": ``` public class Test { public void TestIt(Test t) { t.Value = 42; } public int Value { get; private set; } } ... var t1 = new Test(); var t2 = new Test(); t1.TestIt(t2); // will "happily" change t2.Value ``` Basically, the onus is on *you* to make sure this doesn't happen if you don't want it to happen. There is no language or runtime support to prevent this. The access modifiers you can use are: * `public`: Anyone can access this * `private`: Only the type can access this * `protected`: Only the type, or a descendant of the type, can access this * `internal`: Any type *in the same assembly* can access this * `internal protected`: Any type *in the same assembly* **or** a descendant, can access this Other than this, you have no other options. So "only the same **instance** can access this" does not exist as an access modifier.
That won't work. If `Pos` is a property with a private setter (as it is) the only way they could change it would be by calling a public method from within `otherPlayer`. Something like `otherPlayer.SetPos(new Vector2(34,151))`, where `SetPos()` is: ``` public void SetPos(Vector2 NewPos) { Pos = NewPos; } ```
44,089,727
i have a weekly report that i need to do, i chooseed to create it with openpyxl python module, and send it via mail, when i open the received mail (outlook), the cells with formulas appears as empty, but when downloading the file and open it, the data appears, OS fedora 20. parts of the code : ``` # imported modules from openpyxl ... wb = Workbook() ws = wb.active counter = 3 ws.append(row) for day in data : row = ['']*(len(hosts)*2 +5) row[0] = day.dayDate row[1] ='=SUM(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+\ ')/(COUNT(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+'))' row[2] = '=SUM('+get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')/COUNT('+\ get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')' row[3] = '=MAX('+get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')' row[4] = '=_xlfn.STDEV.P('+get_column_letter(len(hosts)+6)+str(counter)\ +':'+get_column_letter(len(hosts)*2+5)+str(counter)+')' counter += 1 ``` then, i create from the date some charts, etc.. and save, then send via mail : ``` wb.save(pathToFile+fileName+'.xlsx') os.system('echo -e "'+msg+'" | mail -s "'+fileName+'" -a '+\ pathToFile+fileName+'.xlsx -r '+myUsr+' '+ppl2send2) ``` those are parts of the actual code, any one have an idea why the email don't show the results of the formulas in the cells ? Thanks in advance :) [![enter image description here](https://i.stack.imgur.com/iZ7IQ.png)](https://i.stack.imgur.com/iZ7IQ.png)
2017/05/20
[ "https://Stackoverflow.com/questions/44089727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6424190/" ]
Unfortunately not. There is no language support for what you want. Let me be specific about what you want just so that you understand what I answered. Your question is basically this: Given that I have *two* instances of an object, and I have properties in this object that have a private setter, is there any language support for ensuring that instance #1 cannot change this private information of instance #2? And the answer is no. This will compile and "work": ``` public class Test { public void TestIt(Test t) { t.Value = 42; } public int Value { get; private set; } } ... var t1 = new Test(); var t2 = new Test(); t1.TestIt(t2); // will "happily" change t2.Value ``` Basically, the onus is on *you* to make sure this doesn't happen if you don't want it to happen. There is no language or runtime support to prevent this. The access modifiers you can use are: * `public`: Anyone can access this * `private`: Only the type can access this * `protected`: Only the type, or a descendant of the type, can access this * `internal`: Any type *in the same assembly* can access this * `internal protected`: Any type *in the same assembly* **or** a descendant, can access this Other than this, you have no other options. So "only the same **instance** can access this" does not exist as an access modifier.
If this is the property and you are worried about being set from elsewhere: ``` public Vector2 Pos { get { return pos; } private set { this.pos = value; } } private Vector2 pos; ``` This will NOT work. So you do not need to worry: ``` Player otherPlayer = GetNearestEnemy(); otherPlayer.Pos = new Vector2(34,151); // <--- no this will not work ``` That property can only be set from within the class.
44,089,727
i have a weekly report that i need to do, i chooseed to create it with openpyxl python module, and send it via mail, when i open the received mail (outlook), the cells with formulas appears as empty, but when downloading the file and open it, the data appears, OS fedora 20. parts of the code : ``` # imported modules from openpyxl ... wb = Workbook() ws = wb.active counter = 3 ws.append(row) for day in data : row = ['']*(len(hosts)*2 +5) row[0] = day.dayDate row[1] ='=SUM(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+\ ')/(COUNT(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+'))' row[2] = '=SUM('+get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')/COUNT('+\ get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')' row[3] = '=MAX('+get_column_letter(len(hosts)+6)+str(counter)+':'+\ get_column_letter(len(hosts)*2+5)+str(counter)+')' row[4] = '=_xlfn.STDEV.P('+get_column_letter(len(hosts)+6)+str(counter)\ +':'+get_column_letter(len(hosts)*2+5)+str(counter)+')' counter += 1 ``` then, i create from the date some charts, etc.. and save, then send via mail : ``` wb.save(pathToFile+fileName+'.xlsx') os.system('echo -e "'+msg+'" | mail -s "'+fileName+'" -a '+\ pathToFile+fileName+'.xlsx -r '+myUsr+' '+ppl2send2) ``` those are parts of the actual code, any one have an idea why the email don't show the results of the formulas in the cells ? Thanks in advance :) [![enter image description here](https://i.stack.imgur.com/iZ7IQ.png)](https://i.stack.imgur.com/iZ7IQ.png)
2017/05/20
[ "https://Stackoverflow.com/questions/44089727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6424190/" ]
Unfortunately not. There is no language support for what you want. Let me be specific about what you want just so that you understand what I answered. Your question is basically this: Given that I have *two* instances of an object, and I have properties in this object that have a private setter, is there any language support for ensuring that instance #1 cannot change this private information of instance #2? And the answer is no. This will compile and "work": ``` public class Test { public void TestIt(Test t) { t.Value = 42; } public int Value { get; private set; } } ... var t1 = new Test(); var t2 = new Test(); t1.TestIt(t2); // will "happily" change t2.Value ``` Basically, the onus is on *you* to make sure this doesn't happen if you don't want it to happen. There is no language or runtime support to prevent this. The access modifiers you can use are: * `public`: Anyone can access this * `private`: Only the type can access this * `protected`: Only the type, or a descendant of the type, can access this * `internal`: Any type *in the same assembly* can access this * `internal protected`: Any type *in the same assembly* **or** a descendant, can access this Other than this, you have no other options. So "only the same **instance** can access this" does not exist as an access modifier.
The original scenario posted can be handled using an interface e.g. IPeerPlayer that only exposes what other players should see and hides other properties (i.e. the other properties would not be in the IPeerPlayer interface.)
32,496,664
**What is the pythonic way to set a maximum length paramter?** Let's say I want to restrict a list of strings to a certain maximum size: ``` >>> x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] >>> maxlen = 3 >>> [i for i in x if len(i) <= maxlen] ['foo', 'bar', 'a'] ``` And I want to functionalize it and allow different maxlen but if no maxlen is given, it should return the full list: ``` def func1(alist, maxlen): return [i for i in x if len(i) <= maxlen] ``` And I want to set the maxlen to the max length of element in alist, so I tried but I am torn between using `None`, `0` or `-1`. If I use `None`, it would be hard to cast the type later on: ``` def func1(alist, maxlen=None): if maxlen == None: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` And I might get this as the function builds on: ``` >>> maxlen = None >>> int(None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: int() argument must be a string or a number, not 'NoneType' >>> type(maxlen) <type 'NoneType'> ``` If I use -1, it sort of resolve the `int(maxlen)` issues but it's also sort of weird since length should never be negative. ``` def func1(alist, maxlen=-1): if maxlen < 0: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` If I use 0, I face the problem when I really need to return an empty list and set `maxlen=0` but then again, if I really need an empty list then I don't even need a function to create one. ``` def func1(alist, maxlen=0): if maxlen == 0: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` (Note: the ultimate task is NOT to filter a list, i.e. `(filter(lambda k: len(k) <= maxlen, lst))` but it's an example to ask about the pythonic way to set an integer variable that sets a maximum)
2015/09/10
[ "https://Stackoverflow.com/questions/32496664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
> > Let's say I want to restrict a list of strings to a certain maximum > size: > > > And I want to functionalize it and allow different maxlen but if no > maxlen is given, it should return the full list: > > > And I want to set the maxlen to the max length of element in alist > > > To address all these requests, the best answer I can think of is something like this... ``` def func(lst, ln=None): if not ln: return lst ln = max(ln, len(lst)) return [i for i in lst if len(i) <= ln] ``` --- **edit:** If it is important to handle negative maximum length (who knows why) or 0 length, then a function like this can be used. (Though I am against duck-typing) ``` def func(lst, ln=None): if ln is None: return lst elif ln < 1: # handles 0, and negative values. return [] else: ln = max(ln, len(lst)) return [i for i in lst if len(i) <= ln] ```
How about the following approach, this avoids the need to use `max`: ``` def filter_length(a_list, max_length=None): if max_length == 0: return [] elif max_length: return [i for i in x if len(i) <= max_length] else: return a_list x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] print filter_length(x, 3) print filter_length(x) print filter_length(x, 0) ``` Giving you the output: ``` ['foo', 'bar', 'a'] ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] [] ```
32,496,664
**What is the pythonic way to set a maximum length paramter?** Let's say I want to restrict a list of strings to a certain maximum size: ``` >>> x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] >>> maxlen = 3 >>> [i for i in x if len(i) <= maxlen] ['foo', 'bar', 'a'] ``` And I want to functionalize it and allow different maxlen but if no maxlen is given, it should return the full list: ``` def func1(alist, maxlen): return [i for i in x if len(i) <= maxlen] ``` And I want to set the maxlen to the max length of element in alist, so I tried but I am torn between using `None`, `0` or `-1`. If I use `None`, it would be hard to cast the type later on: ``` def func1(alist, maxlen=None): if maxlen == None: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` And I might get this as the function builds on: ``` >>> maxlen = None >>> int(None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: int() argument must be a string or a number, not 'NoneType' >>> type(maxlen) <type 'NoneType'> ``` If I use -1, it sort of resolve the `int(maxlen)` issues but it's also sort of weird since length should never be negative. ``` def func1(alist, maxlen=-1): if maxlen < 0: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` If I use 0, I face the problem when I really need to return an empty list and set `maxlen=0` but then again, if I really need an empty list then I don't even need a function to create one. ``` def func1(alist, maxlen=0): if maxlen == 0: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` (Note: the ultimate task is NOT to filter a list, i.e. `(filter(lambda k: len(k) <= maxlen, lst))` but it's an example to ask about the pythonic way to set an integer variable that sets a maximum)
2015/09/10
[ "https://Stackoverflow.com/questions/32496664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
> > Let's say I want to restrict a list of strings to a certain maximum > size: > > > And I want to functionalize it and allow different maxlen but if no > maxlen is given, it should return the full list: > > > And I want to set the maxlen to the max length of element in alist > > > To address all these requests, the best answer I can think of is something like this... ``` def func(lst, ln=None): if not ln: return lst ln = max(ln, len(lst)) return [i for i in lst if len(i) <= ln] ``` --- **edit:** If it is important to handle negative maximum length (who knows why) or 0 length, then a function like this can be used. (Though I am against duck-typing) ``` def func(lst, ln=None): if ln is None: return lst elif ln < 1: # handles 0, and negative values. return [] else: ln = max(ln, len(lst)) return [i for i in lst if len(i) <= ln] ```
What about some tricks?.. Operator `or` returns first value, if both values are `True`. And, if first value is `False` and second is `True`, `or` returns second value. ``` >>> m = 3 >>> [i for i in x if len(i) <= m] or x ['foo', 'bar', 'a'] >>> m = 0 >>> [i for i in x if len(i) <= m] [] >>> [i for i in x if len(i) <= m] or x ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] ``` I think it's just what you need. :-) Ough... I forget about `-1` and `None`. Result will be the same: ``` >>> m = None >>> [i for i in x if len(i) <= m] or x ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] >>> m = -1 >>> [i for i in x if len(i) <= m] or x ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] ```
32,496,664
**What is the pythonic way to set a maximum length paramter?** Let's say I want to restrict a list of strings to a certain maximum size: ``` >>> x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] >>> maxlen = 3 >>> [i for i in x if len(i) <= maxlen] ['foo', 'bar', 'a'] ``` And I want to functionalize it and allow different maxlen but if no maxlen is given, it should return the full list: ``` def func1(alist, maxlen): return [i for i in x if len(i) <= maxlen] ``` And I want to set the maxlen to the max length of element in alist, so I tried but I am torn between using `None`, `0` or `-1`. If I use `None`, it would be hard to cast the type later on: ``` def func1(alist, maxlen=None): if maxlen == None: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` And I might get this as the function builds on: ``` >>> maxlen = None >>> int(None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: int() argument must be a string or a number, not 'NoneType' >>> type(maxlen) <type 'NoneType'> ``` If I use -1, it sort of resolve the `int(maxlen)` issues but it's also sort of weird since length should never be negative. ``` def func1(alist, maxlen=-1): if maxlen < 0: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` If I use 0, I face the problem when I really need to return an empty list and set `maxlen=0` but then again, if I really need an empty list then I don't even need a function to create one. ``` def func1(alist, maxlen=0): if maxlen == 0: maxlen = max(alist, key=len) return [i for i in x if len(i) <= maxlen] ``` (Note: the ultimate task is NOT to filter a list, i.e. `(filter(lambda k: len(k) <= maxlen, lst))` but it's an example to ask about the pythonic way to set an integer variable that sets a maximum)
2015/09/10
[ "https://Stackoverflow.com/questions/32496664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
> > Let's say I want to restrict a list of strings to a certain maximum > size: > > > And I want to functionalize it and allow different maxlen but if no > maxlen is given, it should return the full list: > > > And I want to set the maxlen to the max length of element in alist > > > To address all these requests, the best answer I can think of is something like this... ``` def func(lst, ln=None): if not ln: return lst ln = max(ln, len(lst)) return [i for i in lst if len(i) <= ln] ``` --- **edit:** If it is important to handle negative maximum length (who knows why) or 0 length, then a function like this can be used. (Though I am against duck-typing) ``` def func(lst, ln=None): if ln is None: return lst elif ln < 1: # handles 0, and negative values. return [] else: ln = max(ln, len(lst)) return [i for i in lst if len(i) <= ln] ```
As you said: "*I want to allow different `maxlen`s but if no `maxlen` is given, it should return the full list*". An approach would be a definition of a `maxFilter()` function which uses Pythons **[*default argument values*](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values)**: ``` >>> def maxFilter(alist, maxlen = None): if maxlen is None: #no maxlen is given -> return full list return alist else: #in all other cases apply algorithm return [i for i in x if len(i) <= maxlen] ``` Examples, using `x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo']`: ``` >>> maxFilter(x, None) #same as maxFilter(x) ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo'] >>> maxFilter(x, 3) ['foo', 'bar', 'a'] >>> maxFilter(x, 0) [] ``` **Note:** In my opinion it would be better to ask about a way *to set an **optional** length parameter to list elments* .
28,894,756
I have installed python 2.7, numpy 1.9.0, scipy 0.15.1 and scikit-learn 0.15.2. Now when I do the following in python: ``` train_set = ("The sky is blue.", "The sun is bright.") test_set = ("The sun in the sky is bright.", "We can see the shining sun, the bright sun.") from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() print vectorizer CountVectorizer(analyzer=u'word', binary=False, charset=None, charset_error=None, decode_error=u'strict', dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content', lowercase=True, max_df=1.0, max_features=None, min_df=1, ngram_range=(1, 1), preprocessor=None, stop_words=None, strip_accents=None, token_pattern=u'(?u)\\b\\w\\w+\\b', tokenizer=None, vocabulary=None) vectorizer.fit_transform(train_set) print vectorizer.vocabulary None. ``` Actually it should have printed the following: ``` CountVectorizer(analyzer__min_n=1, analyzer__stop_words=set(['all', 'six', 'less', 'being', 'indeed', 'over', 'move', 'anyway', 'four', 'not', 'own', 'through', 'yourselves', (...) ---> For count vectorizer {'blue': 0, 'sun': 1, 'bright': 2, 'sky': 3} ---> for vocabulary ``` The above code are from the blog: <http://blog.christianperone.com/?p=1589> Could you please help me as to why I get such an error. Since the vocabulary is not indexed properly I am not able to move ahead in understanding the concept of TF-IDF. I am a newbie for python so any help would be appreciated. Arc.
2015/03/06
[ "https://Stackoverflow.com/questions/28894756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4193051/" ]
You are missing an underscore, try this way: ``` from sklearn.feature_extraction.text import CountVectorizer train_set = ("The sky is blue.", "The sun is bright.") test_set = ("The sun in the sky is bright.", "We can see the shining sun, the bright sun.") vectorizer = CountVectorizer(stop_words='english') document_term_matrix = vectorizer.fit_transform(train_set) print vectorizer.vocabulary_ # {u'blue': 0, u'sun': 3, u'bright': 1, u'sky': 2} ``` If you use the ipython shell, you can use tab completion, and you can find easier the methods and attributes of objects.
Try using the `vectorizer.get_feature_names()` method. It gives the column names in the order it appears in the `document_term_matrix`. ``` from sklearn.feature_extraction.text import CountVectorizer train_set = ("The sky is blue.", "The sun is bright.") test_set = ("The sun in the sky is bright.", "We can see the shining sun, the bright sun.") vectorizer = CountVectorizer(stop_words='english') document_term_matrix = vectorizer.fit_transform(train_set) vectorizer.get_feature_names() #> ['blue', 'bright', 'sky', 'sun'] ```
48,671,331
Am implementing a sign up using python & mysql. Am getting the error no module named flask.ext.mysql and research implies that i should install flask first. They say it's very simple, you simply type pip install flask-mysql but where do i type this? In mysql command line for my database or in the python app?
2018/02/07
[ "https://Stackoverflow.com/questions/48671331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8857901/" ]
Pip is used from the command line. If you are on a Linux/Mac machine, type it from the Terminal. Make sure you actually have Pip. If you don't, use this command (on the Terminal) on linux: ``` sudo apt-get install pip ``` If you are on a Mac, use (in the Terminal): ``` /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ``` then: ``` brew install pip ``` After doing that on Mac/Linux, you can go ahead and execute the command: ``` pip install flask-mysql ``` If you are on a Windows machine, read this instead: [How do I install pip on Windows?](https://stackoverflow.com/questions/4750806/how-do-i-install-pip-on-windows) Hope this helped!
You should be able to type it in the command line for your operating system (ie. CMD/bash/terminal) as long as you have pip installed and the executable location is in your PATH.
41,708,881
I used pip today for the first time in a while and I got the helpful message > > You are using pip version 8.1.1, however version 9.0.1 is available. > You should consider upgrading via the 'pip install --upgrade pip' command. > > > So, I went ahead and ``` pip install --upgrade pip ``` but things did not go according to plan... ``` Collecting pip Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB) 100% |████████████████████████████████| 1.3MB 510kB/s Installing collected packages: pip Found existing installation: pip 8.1.1 Uninstalling pip-8.1.1: Exception: Traceback (most recent call last): File "//anaconda/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "//anaconda/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "//anaconda/lib/python2.7/site-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True) File "//anaconda/lib/python2.7/site-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm) File "//anaconda/lib/python2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "//anaconda/lib/python2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "//anaconda/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/anaconda/lib/python2.7/site-packages/pip-8.1.1.dist-info/DESCRIPTION.rst' You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ``` And now it seems that pip is completely gone from my computer: ``` $ pip -bash: //anaconda/bin/pip: No such file or directory ``` Is pip really gone, that is, did it really uninstall and then fail to reinstall, or did something just get unlinked? How can I avoid this issue in the future? Because I can imagine I will need to upgrade pip again at some point...
2017/01/17
[ "https://Stackoverflow.com/questions/41708881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3704831/" ]
You can reinstall `pip` with `conda`: ``` conda install pip ``` Looks like you need to have root rights: ``` sudo conda install pip ```
You can use curl to reinstall pip via the Python Packaging Authority website: ``` curl https://bootstrap.pypa.io/get-pip.py | python ```
41,708,881
I used pip today for the first time in a while and I got the helpful message > > You are using pip version 8.1.1, however version 9.0.1 is available. > You should consider upgrading via the 'pip install --upgrade pip' command. > > > So, I went ahead and ``` pip install --upgrade pip ``` but things did not go according to plan... ``` Collecting pip Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB) 100% |████████████████████████████████| 1.3MB 510kB/s Installing collected packages: pip Found existing installation: pip 8.1.1 Uninstalling pip-8.1.1: Exception: Traceback (most recent call last): File "//anaconda/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "//anaconda/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "//anaconda/lib/python2.7/site-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True) File "//anaconda/lib/python2.7/site-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm) File "//anaconda/lib/python2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "//anaconda/lib/python2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "//anaconda/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/anaconda/lib/python2.7/site-packages/pip-8.1.1.dist-info/DESCRIPTION.rst' You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ``` And now it seems that pip is completely gone from my computer: ``` $ pip -bash: //anaconda/bin/pip: No such file or directory ``` Is pip really gone, that is, did it really uninstall and then fail to reinstall, or did something just get unlinked? How can I avoid this issue in the future? Because I can imagine I will need to upgrade pip again at some point...
2017/01/17
[ "https://Stackoverflow.com/questions/41708881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3704831/" ]
Python comes with a module for installing pip without needing to pull anything from the internet called `ensurepip`. It's pretty straightforward to use, just run the following in a terminal: ``` python -m ensurepip ``` From there you can upgrade pip to the latest the standard way. Additional documentation is available here <https://docs.python.org/3/library/ensurepip.html>.
You can reinstall `pip` with `conda`: ``` conda install pip ``` Looks like you need to have root rights: ``` sudo conda install pip ```
41,708,881
I used pip today for the first time in a while and I got the helpful message > > You are using pip version 8.1.1, however version 9.0.1 is available. > You should consider upgrading via the 'pip install --upgrade pip' command. > > > So, I went ahead and ``` pip install --upgrade pip ``` but things did not go according to plan... ``` Collecting pip Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB) 100% |████████████████████████████████| 1.3MB 510kB/s Installing collected packages: pip Found existing installation: pip 8.1.1 Uninstalling pip-8.1.1: Exception: Traceback (most recent call last): File "//anaconda/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "//anaconda/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "//anaconda/lib/python2.7/site-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True) File "//anaconda/lib/python2.7/site-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm) File "//anaconda/lib/python2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "//anaconda/lib/python2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "//anaconda/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/anaconda/lib/python2.7/site-packages/pip-8.1.1.dist-info/DESCRIPTION.rst' You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ``` And now it seems that pip is completely gone from my computer: ``` $ pip -bash: //anaconda/bin/pip: No such file or directory ``` Is pip really gone, that is, did it really uninstall and then fail to reinstall, or did something just get unlinked? How can I avoid this issue in the future? Because I can imagine I will need to upgrade pip again at some point...
2017/01/17
[ "https://Stackoverflow.com/questions/41708881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3704831/" ]
Python comes with a module for installing pip without needing to pull anything from the internet called `ensurepip`. It's pretty straightforward to use, just run the following in a terminal: ``` python -m ensurepip ``` From there you can upgrade pip to the latest the standard way. Additional documentation is available here <https://docs.python.org/3/library/ensurepip.html>.
You can use curl to reinstall pip via the Python Packaging Authority website: ``` curl https://bootstrap.pypa.io/get-pip.py | python ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
None of the above worked for me, but turns out the solution was quite simple... All I was doing wrong was not explicitly including "null" as the parameter in the useRef initialization (it expects null, not undefined). Also you CANNOT use "HTMLElement" as your ref type, you have to be more specific, so for me it was "HTMLDivElement" for example). So working code for me was something like this: ``` const ref = useRef<HTMLDivElement>(null); return <div ref={ref}> Some Content... </div> ```
The same stands for the `<svg>` elements: ``` const ref = useRef<SVGSVGElement>(null) ... <svg ref={ref} /> ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
Just import React: ```js import React, { useRef } from 'react'; function Test() { const node = useRef<HTMLDivElement>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={node}></div> } ``` I made an update. Use `HTMLDivElement` as generic parameter instead of `HTMLElement | null`. Also, `contains` expects an argument. **UPDATE** `useRef` expects generic argument of DOM element type. You don't need to use `| null` because `RefObject` already knows that `current` might be null. See next type: ```js interface RefObject<T> { readonly current: T | null } ``` TS & React are smart enough to figure out that your ref might be null
Key is to use HTMLElement and undefined for initialization ``` const node = useRef<HTMLElement>(); ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
Just import React: ```js import React, { useRef } from 'react'; function Test() { const node = useRef<HTMLDivElement>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={node}></div> } ``` I made an update. Use `HTMLDivElement` as generic parameter instead of `HTMLElement | null`. Also, `contains` expects an argument. **UPDATE** `useRef` expects generic argument of DOM element type. You don't need to use `| null` because `RefObject` already knows that `current` might be null. See next type: ```js interface RefObject<T> { readonly current: T | null } ``` TS & React are smart enough to figure out that your ref might be null
``` selfref = React.createRef<HTMLInputElement>() ``` I give the exacted TS Type, then the editor passed the check. it works nice now.
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
None of the above worked for me, but turns out the solution was quite simple... All I was doing wrong was not explicitly including "null" as the parameter in the useRef initialization (it expects null, not undefined). Also you CANNOT use "HTMLElement" as your ref type, you have to be more specific, so for me it was "HTMLDivElement" for example). So working code for me was something like this: ``` const ref = useRef<HTMLDivElement>(null); return <div ref={ref}> Some Content... </div> ```
Key is to use HTMLElement and undefined for initialization ``` const node = useRef<HTMLElement>(); ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
I came here looking for help with an iframe ref. Perhaps this solution will help someone else that's looking for the same thing. I replaced `HTMLDivElement` with `HTMLIFrameElement` so: ``` const node = useRef<HTMLIFrameElement>(null); ```
The same stands for the `<svg>` elements: ``` const ref = useRef<SVGSVGElement>(null) ... <svg ref={ref} /> ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
I came here looking for help with an iframe ref. Perhaps this solution will help someone else that's looking for the same thing. I replaced `HTMLDivElement` with `HTMLIFrameElement` so: ``` const node = useRef<HTMLIFrameElement>(null); ```
``` selfref = React.createRef<HTMLInputElement>() ``` I give the exacted TS Type, then the editor passed the check. it works nice now.
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
Just import React: ```js import React, { useRef } from 'react'; function Test() { const node = useRef<HTMLDivElement>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={node}></div> } ``` I made an update. Use `HTMLDivElement` as generic parameter instead of `HTMLElement | null`. Also, `contains` expects an argument. **UPDATE** `useRef` expects generic argument of DOM element type. You don't need to use `| null` because `RefObject` already knows that `current` might be null. See next type: ```js interface RefObject<T> { readonly current: T | null } ``` TS & React are smart enough to figure out that your ref might be null
The same stands for the `<svg>` elements: ``` const ref = useRef<SVGSVGElement>(null) ... <svg ref={ref} /> ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
Just import React: ```js import React, { useRef } from 'react'; function Test() { const node = useRef<HTMLDivElement>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={node}></div> } ``` I made an update. Use `HTMLDivElement` as generic parameter instead of `HTMLElement | null`. Also, `contains` expects an argument. **UPDATE** `useRef` expects generic argument of DOM element type. You don't need to use `| null` because `RefObject` already knows that `current` might be null. See next type: ```js interface RefObject<T> { readonly current: T | null } ``` TS & React are smart enough to figure out that your ref might be null
I came here looking for help with an iframe ref. Perhaps this solution will help someone else that's looking for the same thing. I replaced `HTMLDivElement` with `HTMLIFrameElement` so: ``` const node = useRef<HTMLIFrameElement>(null); ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
Key is to use HTMLElement and undefined for initialization ``` const node = useRef<HTMLElement>(); ```
The same stands for the `<svg>` elements: ``` const ref = useRef<SVGSVGElement>(null) ... <svg ref={ref} /> ```
66,963,342
How can I change the output of the `models.ForeignKey` field in my below custom field? Custom field: ```py class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) ``` And used in the below model: ```py class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) ``` I want to change the output of the below `print(a.job_title)` statement: ```py >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer ```
2021/04/06
[ "https://Stackoverflow.com/questions/66963342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7431943/" ]
I came here looking for help with an iframe ref. Perhaps this solution will help someone else that's looking for the same thing. I replaced `HTMLDivElement` with `HTMLIFrameElement` so: ``` const node = useRef<HTMLIFrameElement>(null); ```
Key is to use HTMLElement and undefined for initialization ``` const node = useRef<HTMLElement>(); ```
14,160,686
I'm writing a python (3.2+) plugin library and I want to create a function which will create some variables automatically handled from config files. The use case is as follows (class variable): ``` class X: option(y=0) def __init__(self): pass ``` (instance variable): ``` class Y: def __init__(self): option(y=0) ``` the option draft code is as follows: ``` def option(**kwargs): frame = inspect.stack()[1][0] locals_ = frame.f_locals if locals_ == frame.f_globals: raise SyntaxError('option() can only be used in a class definition') if '__module__' in locals_: # TODO else: for name, value in kwargs.items(): if not name in locals_["self"].__class__.__dict__: setattr(locals_["self"].__class__, name, VirtualOption('_'+name, static=False)) setattr(locals_["self"], '_'+name,value) ``` I have problem the first case, when option is declared as class variable. Is it possible to somehow get reference to the class in which this function was used (in example to class X)?
2013/01/04
[ "https://Stackoverflow.com/questions/14160686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889902/" ]
You cannot get a reference to the class, because the class has yet to be created. Your parent frame points a temporary function, whose `locals()` when it completes will be used as the class body. As such, all you need to do is add your variables to the parent frame locals, and these will be added to the class when class construction is finished. Short demo: ``` >>> def foo(): ... import sys ... flocals = sys._getframe(1).f_locals ... flocals['ham'] = 'eggs' ... >>> class Bar: ... foo() ... >>> dir(Bar) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__locals__', '__lt__', '__module__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'ham'] >>> Bar.ham 'eggs' ```
It seems to me that a metaclass would be suitable here: **python2.x syntax** ``` def class_maker(name,bases,dict_): dict_['y']=0 return type(name,bases,dict_) class X(object): __metaclass__ = class_maker def __init__(self): pass print X.y foo = X() print foo.y ``` **python3.x syntax** It seems that python3 uses a `metaclass` keyword in the class definition: ``` def class_maker(name,bases,dict_): dict_['y']=0 return type(name,bases,dict_) class X(metaclass=class_maker): def __init__(self): pass print( X.y ) foo = X() print( foo.y ) print( type(foo) ) ``` Or, more along the lines of what you have in your question: ``` def class_maker(name,bases,dict_,**kwargs): dict_.update(kwargs) return type(name,bases,dict_) class X(metaclass=lambda *args: class_maker(*args,y=0)): def __init__(self): pass print( X.y ) foo = X() print( foo.y ) print( type(foo) ) ```
8,301,962
I am trying to rewrite the code described [here](http://opencv.itseez.com/doc/tutorials/features2d/feature_homography/feature_homography.html#feature-homography). using the python API for Opencv. The step 3 of the code has this lines: ``` FlannBasedMatcher matcher; std::vector< DMatch > matches; matcher.match( descriptors_object, descriptors_scene, matches ); ``` I have looked over and over in [the OpenCV reference](http://opencv.itseez.com/index.html) but found nothing related to a FlannBasedMatcher in python or some other object which can do the work. Any ideas? NOTE: I am usign OpenCV 2.3.1 and Python 2.6
2011/11/28
[ "https://Stackoverflow.com/questions/8301962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053925/" ]
Looking in the examples provided by OpenCV 2.3.1 under the python2 folder, I found an implementation of a flann based match function which doesn't rely on the FlanBasedMatcher object. Here is the code: ``` FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 4) def match_flann(desc1, desc2, r_threshold = 0.6): flann = cv2.flann_Index(desc2, flann_params) idx2, dist = flann.knnSearch(desc1, 2, params = {}) # bug: need to provide empty dict mask = dist[:,0] / dist[:,1] < r_threshold idx1 = np.arange(len(desc1)) pairs = np.int32( zip(idx1, idx2[:,0]) ) return pairs[mask] ```
Pythonic FlannBasedMatcher is already available in OpenCV trunk, but if I remember correctly, it was added after 2.3.1 release. Here is OpenCV sample using FlannBasedMatcher: <http://code.opencv.org/projects/opencv/repository/revisions/master/entry/samples/python2/feature_homography.py>
8,301,962
I am trying to rewrite the code described [here](http://opencv.itseez.com/doc/tutorials/features2d/feature_homography/feature_homography.html#feature-homography). using the python API for Opencv. The step 3 of the code has this lines: ``` FlannBasedMatcher matcher; std::vector< DMatch > matches; matcher.match( descriptors_object, descriptors_scene, matches ); ``` I have looked over and over in [the OpenCV reference](http://opencv.itseez.com/index.html) but found nothing related to a FlannBasedMatcher in python or some other object which can do the work. Any ideas? NOTE: I am usign OpenCV 2.3.1 and Python 2.6
2011/11/28
[ "https://Stackoverflow.com/questions/8301962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053925/" ]
Pythonic FlannBasedMatcher is already available in OpenCV trunk, but if I remember correctly, it was added after 2.3.1 release. Here is OpenCV sample using FlannBasedMatcher: <http://code.opencv.org/projects/opencv/repository/revisions/master/entry/samples/python2/feature_homography.py>
I could not post the dead link on the post above because of lack of reputations. So, I am posting it here. [The dead link(feature\_homography.py)](https://github.com/opencv/opencv/blob/master/samples/python/feature_homography.py)
8,301,962
I am trying to rewrite the code described [here](http://opencv.itseez.com/doc/tutorials/features2d/feature_homography/feature_homography.html#feature-homography). using the python API for Opencv. The step 3 of the code has this lines: ``` FlannBasedMatcher matcher; std::vector< DMatch > matches; matcher.match( descriptors_object, descriptors_scene, matches ); ``` I have looked over and over in [the OpenCV reference](http://opencv.itseez.com/index.html) but found nothing related to a FlannBasedMatcher in python or some other object which can do the work. Any ideas? NOTE: I am usign OpenCV 2.3.1 and Python 2.6
2011/11/28
[ "https://Stackoverflow.com/questions/8301962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053925/" ]
Looking in the examples provided by OpenCV 2.3.1 under the python2 folder, I found an implementation of a flann based match function which doesn't rely on the FlanBasedMatcher object. Here is the code: ``` FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 4) def match_flann(desc1, desc2, r_threshold = 0.6): flann = cv2.flann_Index(desc2, flann_params) idx2, dist = flann.knnSearch(desc1, 2, params = {}) # bug: need to provide empty dict mask = dist[:,0] / dist[:,1] < r_threshold idx1 = np.arange(len(desc1)) pairs = np.int32( zip(idx1, idx2[:,0]) ) return pairs[mask] ```
I could not post the dead link on the post above because of lack of reputations. So, I am posting it here. [The dead link(feature\_homography.py)](https://github.com/opencv/opencv/blob/master/samples/python/feature_homography.py)
31,483,448
I have a python script which I want to start using a rc(8) script in FreeBSD. The python script uses the `#!/usr/bin/env python2` pattern for portability purposes. (Different \*nix's put interpreter binaries in different locations on the filesystem). The FreeBSD rc scripts will not work with this. Here is a script that sets up a test scenario that demonstrates this: ``` #!/bin/sh # Create dummy python script which uses env for shebang. cat << EOF > /usr/local/bin/foo #!/usr/bin/env python2.7 print("Hello foo") EOF # turn on executable bit chmod +x /usr/local/bin/foo # create FreeBSD rc script with command_interpreter specified. cat << EOF > /usr/local/etc/rc.d/foo #!/bin/sh # # PROVIDE: foo . /etc/rc.subr name="foo" rcvar=foo_enable command_interpreter="/usr/local/bin/python2.7" command="/usr/local/bin/foo" load_rc_config \$name run_rc_command \$1 EOF # turn on executable bit chmod +x /usr/local/etc/rc.d/foo # enable foo echo "foo_enable=\"YES\"" >> /etc/rc.conf ``` Here follows a console log demonstrating the behaviour when executing the rc script directly. Note this works, but emits a warning. ``` # /usr/local/etc/rc.d/foo start /usr/local/etc/rc.d/foo: WARNING: $command_interpreter /usr/local/bin/python2 != python2 Starting foo. Hello foo # ``` Here follows a console log demonstrating the behaviour when executing the rc script using the service(8) command. This fails completely. ``` # service foo start /usr/local/etc/rc.d/foo: WARNING: $command_interpreter /usr/local/bin/python2 != python2 Starting foo. env: python2: No such file or directory /usr/local/etc/rc.d/foo: WARNING: failed to start foo # ``` Why does the `service foo start` fail? Why does rc warn about the interpreter? Why does it not use the interpreter as specified in the `command_interpreter` variable?
2015/07/17
[ "https://Stackoverflow.com/questions/31483448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183499/" ]
*Self answered my question, but I'm hoping someone else will give a better answer for posterity* The reason why env(1) does not work is because it expects an environment in the first place, but rc scripts run before the environment is set up. Hence it fails. It seems that the popular env shebang pattern is actually an anti-pattern. I do not have a cogent answer for the `command_interpreter` warning.
The command interpreter warning is generated by the `_find_processes()` function in `/usr/src/etc/rc.subr`. The reason that it does that is because a service written in an interpreted language is found in `ps` output by the *name of the interpreter*.
6,648,394
I have a project and I want to use python but the server is only Windows Server 2000 can it run on this system?
2011/07/11
[ "https://Stackoverflow.com/questions/6648394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1347816/" ]
If you are using windows 2000 then it's possible that python 3.2 is not your best alternative. A couple of months ago there was an interesting thread in the python-dev mailing list[1] about dropping win2k support (there are some annoying bugs for this platform). [1] <http://mail.python.org/pipermail/python-dev/2010-March/098074.html>
You can use [Micro Python](https://micropython.org/) for DOS. It has Python 3.4 syntax.
5,189,483
If my question is unclear there is a great explainaion of what I'm attempting to do here under the section, "Method 2: The British Method": <http://www.gradeamathhelp.com/how-to-factor-polynomials.html> My current program simply inputted all 3 A,B, and C variables and then assigned A\*C to D I then took the negative value of the absolute value of D and assigned it to X and Y I then simply did if/then statements to test if X+Y=B and X\*Y=D and if not, to add .5 to X until it was equal to or greater than D at which point I put X back to it's orignial value and added .5 to Y. This resulted in a memory error. Disregarding the awful, AWFUL habit I made of using if/then statements, does anyone have a better idea of how I can solve this? (And cut me some slack, I only dabble around in java and python and sometimes TIBasic, and I'm only a sophomore in highschool!) Note: This code won't run because I'm recreating it, it's not the actual code, just a recreation. Syntax is all bugged up. (IE: -> is an arrow, not a negative equal sign) I just wrote this so i might have forgotten something. ``` :Prompt A :Prompt B :Prompt C :A*C→D :-abs(D)→X :-abs(D)→Y :Lbl A :If X+Y=B and X*Y=D :Then :Disp X,Y :Pause :Else :X+.5→X :Goto B :Lbl B :If X>D :-abs(D)→X :Y+.5→Y :Goto A ```
2011/03/04
[ "https://Stackoverflow.com/questions/5189483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your code isn't working because you need "END" commands every time you use a "THEN" command. END is also used to close off "REPEAT", "FOR", and "WHILE" loops. Why does it need "END" for an "IF,THEN" type command? Because "IF,THEN" equates to: ``` If X+Y=B and X*Y=D ( ``` In typical scripting The "END" is like an end parentheses, and is needed because the "THEN" is like an open parentheses. If you only have one command needing executed, do something like ``` If X+Y=B and X*Y=D do this ``` Which is like ``` If X+Y=B and X*Y=D do this ``` I'm not sure on this because I'm not sure exactly what you want to do, but I think the code is: ``` :Prompt A :Prompt B :Prompt C :A*C -> D :-abs(D) -> X :-abs(D) -> Y :lbl A :if X+Y=B and X*Y=D :then :disp X,Y :pause :else :X+.5 -> X :goto B :end :lbl B :if X>D :-abs(D) -> X :Y+.5->Y :goto A ``` Where if X+Y=B and X\*Y=D, it will display the correct answer, but if not it will add 0.5 to X, and proceed to lbl B.Within lbl B, it will check to check if X>D; if X is greater than D then the negative absolute value of D will be stored as X, Y will be increased by 0.5, and it will recheck the values again in lbl A. Also, a note on lbl B: ``` :if X>D :-abs(D) -> X :Y+.5->Y :goto A ``` Will make store the negative absolute value of D as X only if X>D. Y will be increased by 0.5 whether or not X is greater than or less than D. Not sure if that's what you intended, but just in case I figured I'd bring it to your attention.
Download available at: <http://www.ticalc.org/pub/83/basic/math/algebra/>
5,189,483
If my question is unclear there is a great explainaion of what I'm attempting to do here under the section, "Method 2: The British Method": <http://www.gradeamathhelp.com/how-to-factor-polynomials.html> My current program simply inputted all 3 A,B, and C variables and then assigned A\*C to D I then took the negative value of the absolute value of D and assigned it to X and Y I then simply did if/then statements to test if X+Y=B and X\*Y=D and if not, to add .5 to X until it was equal to or greater than D at which point I put X back to it's orignial value and added .5 to Y. This resulted in a memory error. Disregarding the awful, AWFUL habit I made of using if/then statements, does anyone have a better idea of how I can solve this? (And cut me some slack, I only dabble around in java and python and sometimes TIBasic, and I'm only a sophomore in highschool!) Note: This code won't run because I'm recreating it, it's not the actual code, just a recreation. Syntax is all bugged up. (IE: -> is an arrow, not a negative equal sign) I just wrote this so i might have forgotten something. ``` :Prompt A :Prompt B :Prompt C :A*C→D :-abs(D)→X :-abs(D)→Y :Lbl A :If X+Y=B and X*Y=D :Then :Disp X,Y :Pause :Else :X+.5→X :Goto B :Lbl B :If X>D :-abs(D)→X :Y+.5→Y :Goto A ```
2011/03/04
[ "https://Stackoverflow.com/questions/5189483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There's an easier way to do this. Setting `a+bi` makes sure that the program displays imaginary numbers as well instead of giving errors. `"` denotes comments. Finally, adding the last line gets rid of the "Done" message. ``` : "Clear and request input : ClrHome : a+bi : Disp "ax^2+bx+c=0" : Input "a. ",A : Input "b. ",B : Input "c. ",C : "Doing the maths : Disp (-B+√(B^2-4AC))/(2A) : Disp (-B-√(B^2-4AC))/(2A) : " ``` The code itself is pretty self explanatory, it asks for the variables `a`, `b`, and `c`, when it then substitutes into [the quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula "Quadratic Formula on Wikipedia") and prints.
Download available at: <http://www.ticalc.org/pub/83/basic/math/algebra/>
16,847,597
I am new to python and programming, so apologies in advance. I know of remove(), append(), len(), and rand.rang (or whatever it is), and I believe I would need those tools, but it's not clear to me *how* to code it. What I would like to do is, while looping or otherwise accessing List\_A, randomly select an index within List\_A, remove the selected\_index from List\_A, and then append() the selected\_index to List\_B. I would like to randomly remove only up to a *certain percentage* (or real number if this is impossible) of items from List A. Any ideas?? Is what I'm describing possible?
2013/05/30
[ "https://Stackoverflow.com/questions/16847597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2058922/" ]
If you don't care about the order of the input list, I'd shuffle it, then remove `n` items from that list, adding those to the other list: ``` from random import shuffle def remove_percentage(list_a, percentage): shuffle(list_a) count = int(len(list_a) * percentage) if not count: return [] # edge case, no elements removed list_a[-count:], list_b = [], list_a[-count:] return list_b ``` where `percentage` is a float value between `0.0` and `1.0`. Demo: ``` >>> list_a = range(100) >>> list_b = remove_percentage(list_a, 0.25) >>> len(list_a), len(list_b) (75, 25) >>> list_b [1, 94, 13, 81, 23, 84, 41, 92, 74, 82, 42, 28, 75, 33, 35, 62, 2, 58, 90, 52, 96, 68, 72, 73, 47] ```
If you can find a random index `i` of some element in `listA`, then you can easily move it from A to B using: ``` listB.append(listA.pop(i)) ```
16,847,597
I am new to python and programming, so apologies in advance. I know of remove(), append(), len(), and rand.rang (or whatever it is), and I believe I would need those tools, but it's not clear to me *how* to code it. What I would like to do is, while looping or otherwise accessing List\_A, randomly select an index within List\_A, remove the selected\_index from List\_A, and then append() the selected\_index to List\_B. I would like to randomly remove only up to a *certain percentage* (or real number if this is impossible) of items from List A. Any ideas?? Is what I'm describing possible?
2013/05/30
[ "https://Stackoverflow.com/questions/16847597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2058922/" ]
If you don't care about the order of the input list, I'd shuffle it, then remove `n` items from that list, adding those to the other list: ``` from random import shuffle def remove_percentage(list_a, percentage): shuffle(list_a) count = int(len(list_a) * percentage) if not count: return [] # edge case, no elements removed list_a[-count:], list_b = [], list_a[-count:] return list_b ``` where `percentage` is a float value between `0.0` and `1.0`. Demo: ``` >>> list_a = range(100) >>> list_b = remove_percentage(list_a, 0.25) >>> len(list_a), len(list_b) (75, 25) >>> list_b [1, 94, 13, 81, 23, 84, 41, 92, 74, 82, 42, 28, 75, 33, 35, 62, 2, 58, 90, 52, 96, 68, 72, 73, 47] ```
1) Calculate how many elements you want to remove, call it `k`. 2) `random.randrange(len(listA))` will return a random number between 0 and len(listA)-1 inclusive, e.g. a random index you can use in listA. 3) Grab the element at that index, remove it from listA, append it to listB. 4) Repeat until you have removed `k` elements.
16,847,597
I am new to python and programming, so apologies in advance. I know of remove(), append(), len(), and rand.rang (or whatever it is), and I believe I would need those tools, but it's not clear to me *how* to code it. What I would like to do is, while looping or otherwise accessing List\_A, randomly select an index within List\_A, remove the selected\_index from List\_A, and then append() the selected\_index to List\_B. I would like to randomly remove only up to a *certain percentage* (or real number if this is impossible) of items from List A. Any ideas?? Is what I'm describing possible?
2013/05/30
[ "https://Stackoverflow.com/questions/16847597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2058922/" ]
If you don't care about the order of the input list, I'd shuffle it, then remove `n` items from that list, adding those to the other list: ``` from random import shuffle def remove_percentage(list_a, percentage): shuffle(list_a) count = int(len(list_a) * percentage) if not count: return [] # edge case, no elements removed list_a[-count:], list_b = [], list_a[-count:] return list_b ``` where `percentage` is a float value between `0.0` and `1.0`. Demo: ``` >>> list_a = range(100) >>> list_b = remove_percentage(list_a, 0.25) >>> len(list_a), len(list_b) (75, 25) >>> list_b [1, 94, 13, 81, 23, 84, 41, 92, 74, 82, 42, 28, 75, 33, 35, 62, 2, 58, 90, 52, 96, 68, 72, 73, 47] ```
``` >>> lis = range(100) >>> per = .30 >>> no_of_items = int( len(lis) * per) #number of items in 30 percent >>> lis_b = [] >>> for _ in xrange(no_of_items): ind = random.randint(0,len(lis)-1) #selects a random index value lis_b.append(lis.pop(ind)) #pop the item at that index and append to lis_b ... >>> lis_b [73, 32, 82, 68, 90, 19, 3, 49, 21, 17, 30, 75, 1, 31, 80, 48, 38, 18, 99, 98, 4, 20, 33, 29, 66, 41, 64, 26, 77, 95] ```
62,999,056
This python 3 code does exactly what I want ```py from pathlib import Path def minify(src_dir:Path, dest_dir:Path, n: int): """Write first n lines of each file f in src_dir to dest_dir/f""" dest_dir.mkdir(exist_ok=True) for path in src_dir.iterdir(): new = [x.rstrip() for x in list(path.open().readlines())][:n] dest_path = dest_dir.joinpath(path.name) dest_path.open('w').write('\n'.join(new)) ``` Is there a way to do the same in bash, maybe with `xargs`? ``` ls src_dist/* | xargs head -10 ``` displays what I need, but I don't know how to route that output to the proper file.
2020/07/20
[ "https://Stackoverflow.com/questions/62999056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4381942/" ]
Looks like you are using Bootstrap. Currently, your left nav is initially set to `position: fixed`, I recommend using `position: relative` to your left nav initially so that positioning your `nav` elements can be **relative to the height of the background image**. Using Bootstrap, this solution wraps the left nav & the content in a flex container so that the content can be positioned relative to this container easily, since later on the navs are going to get `position: fixed`. Basically on the script, just detect if the top of the scroll bar's Y position is already past the `height` of the background image element. If it is, assign the `fixed` position to the nav elements and adjust the content's position as needed relative to the container wrapping the left nav & the content. Check the CSS properties involving `.navs-are-fixed` to see how the navs are assigned the `fixed` position. ```js $(window).scroll(function() { // innerHeight is used to include any padding var bgImgHeight = $('.some-bg-img').innerHeight(); // if the the scroll reaches the end of the background image, this is when you start to assign 'fixed' to your nav elements if ($(window).scrollTop() >= bgImgHeight) { $('body').addClass("navs-are-fixed"); } else { $('body').removeClass("navs-are-fixed"); } }); ``` ```css #menu_izq { height: 100%; width: 200px; position: relative; left: 0; top: 0; z-index: 3; background-color: #503522; overflow-x: hidden; padding-top: 20px; } #menu_arriba { background-color: #503522; width: 100%; z-index: 1; position: relative; top: 0; } body { background-color: #ffc75a !important; height: 300vh; /* sample arbitrary value to force body scrolling */ } .some-bg-img { background: url(https://via.placeholder.com/1920x200.png?text=Sample%20Background%20Image); height: 200px; background-repeat: no-repeat; background-size: cover; background-position: bottom; } .navs-are-fixed #menu_arriba { position: fixed; } .navs-are-fixed #menu_izq { position: fixed; top: 72px; /* the height of your top nav */ } .navs-are-fixed .some-sample-content { position: absolute; top: 72px; /* the height of your top nav */ left: 200px; /* the width of your left nav */ } ``` ```html <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <body> <div class="some-bg-img"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand"></div> <a href="user.php" class="navbar-brand"> <p>Inicio</p> </a> <a href="instrucciones.php" class="navbar-brand"> <p>Instrucciones</p> </a> <a href="contacto.php" class="navbar-brand"> <p>Contacto</p> </a> <a href="faq.php" class="navbar-brand"> <p>FaQ</p> </a> <a href="ajax/logout.php" class="navbar-brand"> <p><i class="fas fa-sign-out-alt"></i> Salir</p> </a> </nav> <div class="d-flex h-100 w-100 position-absolute"> <nav id="menu_izq" class="sidenav"> <div></div> <a href="nueva_cata.php"> <p>Nueva Cata</p> </a> <a href="nueva_cerveza.php"> <p>Nueva Cerveza</p> </a> <a href="cata.php"> <p>Mis catas</p> </a> <a href="mis_cervezas.php"> <p>Mis cervezas</p> </a> <a href="mis_amigos.php"> <p>Mis amigos</p> </a> </nav> <div class="some-sample-content"> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> </div> </div> </body> ``` If you really must keep your `fixed` positioning on your left nav, then you are going to have to compute it's `top` value based on on the `height` of both the banner & the top nav, such that if the `top` of scroll bar's Y position is past the `height` of the banner, the `top` value of the left nav will be equal to the height of the top nav - so you push it down so that they don't overlap. If the `top` of the scroll bar's Y position is not past the height of the banner, the top value of the left nav is going to be equal to the difference of the `height` of the banner & the top nav minus the top of the scroll bar's Y position. ```js $(window).scroll(function() { // innerHeight is used to include any padding var bgImgHeight = $('.some-bg-img').innerHeight(); var topNavHeight = $('#menu_arriba').innerHeight(); var leftNavInitialCssTop = bgImgHeight + topNavHeight; // if the the scroll reaches the end of the background image, this is when you start to assign 'fixed' to the top nav if ($(window).scrollTop() >= bgImgHeight) { $('body').addClass("navs-are-fixed"); $("#menu_izq").css("top", topNavHeight); } else { $('body').removeClass("navs-are-fixed"); $("#menu_izq").css("top", leftNavInitialCssTop - $(window).scrollTop()) } }); ``` ```css #menu_izq { height: 100%; width: 200px; position: fixed; left: 0; top: 252px; z-index: 3; background-color: #503522; overflow-x: hidden; padding-top: 20px; } #menu_arriba { background-color: #503522; width: 100%; z-index: 1; top: 0; } body { background-color: #ffc75a !important; height: 400vh; /* sample arbitrary value to force body scrolling */ } .some-bg-img { background: url(https://via.placeholder.com/1920x200.png?text=Sample%20Background%20Image); height: 179px; background-repeat: no-repeat; background-size: cover; background-position: bottom; } .navs-are-fixed #menu_arriba { position: fixed; } ``` ```html <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <div class="some-bg-img"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand"></div> <a href="user.php" class="navbar-brand"> <p>Inicio</p> </a> <a href="instrucciones.php" class="navbar-brand"> <p>Instrucciones</p> </a> <a href="contacto.php" class="navbar-brand"> <p>Contacto</p> </a> <a href="faq.php" class="navbar-brand"> <p>FaQ</p> </a> <a href="ajax/logout.php" class="navbar-brand"> <p><i class="fas fa-sign-out-alt"></i> Salir</p> </a> </nav> <nav id="menu_izq" class="sidenav"> <div></div> <a href="nueva_cata.php"> <p>Nueva Cata</p> </a> <a href="nueva_cerveza.php"> <p>Nueva Cerveza</p> </a> <a href="cata.php"> <p>Mis catas</p> </a> <a href="mis_cervezas.php"> <p>Mis cervezas</p> </a> <a href="mis_amigos.php"> <p>Mis amigos</p> </a> </nav> ```
You should be able to have that working with just CSS and no javascript using `position: sticky` attribute. Make both elements `position: sticky`, the top nav should have a `top: 0` property and the side nav should have a `top: x` property where `x` is the height of the top nav. That should be enough and you should be able to remove the js code. Read more about `sticky` position here <https://developer.mozilla.org/en-US/docs/Web/CSS/position>
62,999,056
This python 3 code does exactly what I want ```py from pathlib import Path def minify(src_dir:Path, dest_dir:Path, n: int): """Write first n lines of each file f in src_dir to dest_dir/f""" dest_dir.mkdir(exist_ok=True) for path in src_dir.iterdir(): new = [x.rstrip() for x in list(path.open().readlines())][:n] dest_path = dest_dir.joinpath(path.name) dest_path.open('w').write('\n'.join(new)) ``` Is there a way to do the same in bash, maybe with `xargs`? ``` ls src_dist/* | xargs head -10 ``` displays what I need, but I don't know how to route that output to the proper file.
2020/07/20
[ "https://Stackoverflow.com/questions/62999056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4381942/" ]
Looks like you are using Bootstrap. Currently, your left nav is initially set to `position: fixed`, I recommend using `position: relative` to your left nav initially so that positioning your `nav` elements can be **relative to the height of the background image**. Using Bootstrap, this solution wraps the left nav & the content in a flex container so that the content can be positioned relative to this container easily, since later on the navs are going to get `position: fixed`. Basically on the script, just detect if the top of the scroll bar's Y position is already past the `height` of the background image element. If it is, assign the `fixed` position to the nav elements and adjust the content's position as needed relative to the container wrapping the left nav & the content. Check the CSS properties involving `.navs-are-fixed` to see how the navs are assigned the `fixed` position. ```js $(window).scroll(function() { // innerHeight is used to include any padding var bgImgHeight = $('.some-bg-img').innerHeight(); // if the the scroll reaches the end of the background image, this is when you start to assign 'fixed' to your nav elements if ($(window).scrollTop() >= bgImgHeight) { $('body').addClass("navs-are-fixed"); } else { $('body').removeClass("navs-are-fixed"); } }); ``` ```css #menu_izq { height: 100%; width: 200px; position: relative; left: 0; top: 0; z-index: 3; background-color: #503522; overflow-x: hidden; padding-top: 20px; } #menu_arriba { background-color: #503522; width: 100%; z-index: 1; position: relative; top: 0; } body { background-color: #ffc75a !important; height: 300vh; /* sample arbitrary value to force body scrolling */ } .some-bg-img { background: url(https://via.placeholder.com/1920x200.png?text=Sample%20Background%20Image); height: 200px; background-repeat: no-repeat; background-size: cover; background-position: bottom; } .navs-are-fixed #menu_arriba { position: fixed; } .navs-are-fixed #menu_izq { position: fixed; top: 72px; /* the height of your top nav */ } .navs-are-fixed .some-sample-content { position: absolute; top: 72px; /* the height of your top nav */ left: 200px; /* the width of your left nav */ } ``` ```html <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <body> <div class="some-bg-img"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand"></div> <a href="user.php" class="navbar-brand"> <p>Inicio</p> </a> <a href="instrucciones.php" class="navbar-brand"> <p>Instrucciones</p> </a> <a href="contacto.php" class="navbar-brand"> <p>Contacto</p> </a> <a href="faq.php" class="navbar-brand"> <p>FaQ</p> </a> <a href="ajax/logout.php" class="navbar-brand"> <p><i class="fas fa-sign-out-alt"></i> Salir</p> </a> </nav> <div class="d-flex h-100 w-100 position-absolute"> <nav id="menu_izq" class="sidenav"> <div></div> <a href="nueva_cata.php"> <p>Nueva Cata</p> </a> <a href="nueva_cerveza.php"> <p>Nueva Cerveza</p> </a> <a href="cata.php"> <p>Mis catas</p> </a> <a href="mis_cervezas.php"> <p>Mis cervezas</p> </a> <a href="mis_amigos.php"> <p>Mis amigos</p> </a> </nav> <div class="some-sample-content"> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> </div> </div> </body> ``` If you really must keep your `fixed` positioning on your left nav, then you are going to have to compute it's `top` value based on on the `height` of both the banner & the top nav, such that if the `top` of scroll bar's Y position is past the `height` of the banner, the `top` value of the left nav will be equal to the height of the top nav - so you push it down so that they don't overlap. If the `top` of the scroll bar's Y position is not past the height of the banner, the top value of the left nav is going to be equal to the difference of the `height` of the banner & the top nav minus the top of the scroll bar's Y position. ```js $(window).scroll(function() { // innerHeight is used to include any padding var bgImgHeight = $('.some-bg-img').innerHeight(); var topNavHeight = $('#menu_arriba').innerHeight(); var leftNavInitialCssTop = bgImgHeight + topNavHeight; // if the the scroll reaches the end of the background image, this is when you start to assign 'fixed' to the top nav if ($(window).scrollTop() >= bgImgHeight) { $('body').addClass("navs-are-fixed"); $("#menu_izq").css("top", topNavHeight); } else { $('body').removeClass("navs-are-fixed"); $("#menu_izq").css("top", leftNavInitialCssTop - $(window).scrollTop()) } }); ``` ```css #menu_izq { height: 100%; width: 200px; position: fixed; left: 0; top: 252px; z-index: 3; background-color: #503522; overflow-x: hidden; padding-top: 20px; } #menu_arriba { background-color: #503522; width: 100%; z-index: 1; top: 0; } body { background-color: #ffc75a !important; height: 400vh; /* sample arbitrary value to force body scrolling */ } .some-bg-img { background: url(https://via.placeholder.com/1920x200.png?text=Sample%20Background%20Image); height: 179px; background-repeat: no-repeat; background-size: cover; background-position: bottom; } .navs-are-fixed #menu_arriba { position: fixed; } ``` ```html <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <div class="some-bg-img"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand"></div> <a href="user.php" class="navbar-brand"> <p>Inicio</p> </a> <a href="instrucciones.php" class="navbar-brand"> <p>Instrucciones</p> </a> <a href="contacto.php" class="navbar-brand"> <p>Contacto</p> </a> <a href="faq.php" class="navbar-brand"> <p>FaQ</p> </a> <a href="ajax/logout.php" class="navbar-brand"> <p><i class="fas fa-sign-out-alt"></i> Salir</p> </a> </nav> <nav id="menu_izq" class="sidenav"> <div></div> <a href="nueva_cata.php"> <p>Nueva Cata</p> </a> <a href="nueva_cerveza.php"> <p>Nueva Cerveza</p> </a> <a href="cata.php"> <p>Mis catas</p> </a> <a href="mis_cervezas.php"> <p>Mis cervezas</p> </a> <a href="mis_amigos.php"> <p>Mis amigos</p> </a> </nav> ```
why you want to do this? you can move the top menu and side menu and text container together in one container to be relative with each other, set the text box container fixed height in percent and set its `overflow-y` to `auto`. make the whole container animatable like the top menu. this will solve your problem.
62,999,056
This python 3 code does exactly what I want ```py from pathlib import Path def minify(src_dir:Path, dest_dir:Path, n: int): """Write first n lines of each file f in src_dir to dest_dir/f""" dest_dir.mkdir(exist_ok=True) for path in src_dir.iterdir(): new = [x.rstrip() for x in list(path.open().readlines())][:n] dest_path = dest_dir.joinpath(path.name) dest_path.open('w').write('\n'.join(new)) ``` Is there a way to do the same in bash, maybe with `xargs`? ``` ls src_dist/* | xargs head -10 ``` displays what I need, but I don't know how to route that output to the proper file.
2020/07/20
[ "https://Stackoverflow.com/questions/62999056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4381942/" ]
Looks like you are using Bootstrap. Currently, your left nav is initially set to `position: fixed`, I recommend using `position: relative` to your left nav initially so that positioning your `nav` elements can be **relative to the height of the background image**. Using Bootstrap, this solution wraps the left nav & the content in a flex container so that the content can be positioned relative to this container easily, since later on the navs are going to get `position: fixed`. Basically on the script, just detect if the top of the scroll bar's Y position is already past the `height` of the background image element. If it is, assign the `fixed` position to the nav elements and adjust the content's position as needed relative to the container wrapping the left nav & the content. Check the CSS properties involving `.navs-are-fixed` to see how the navs are assigned the `fixed` position. ```js $(window).scroll(function() { // innerHeight is used to include any padding var bgImgHeight = $('.some-bg-img').innerHeight(); // if the the scroll reaches the end of the background image, this is when you start to assign 'fixed' to your nav elements if ($(window).scrollTop() >= bgImgHeight) { $('body').addClass("navs-are-fixed"); } else { $('body').removeClass("navs-are-fixed"); } }); ``` ```css #menu_izq { height: 100%; width: 200px; position: relative; left: 0; top: 0; z-index: 3; background-color: #503522; overflow-x: hidden; padding-top: 20px; } #menu_arriba { background-color: #503522; width: 100%; z-index: 1; position: relative; top: 0; } body { background-color: #ffc75a !important; height: 300vh; /* sample arbitrary value to force body scrolling */ } .some-bg-img { background: url(https://via.placeholder.com/1920x200.png?text=Sample%20Background%20Image); height: 200px; background-repeat: no-repeat; background-size: cover; background-position: bottom; } .navs-are-fixed #menu_arriba { position: fixed; } .navs-are-fixed #menu_izq { position: fixed; top: 72px; /* the height of your top nav */ } .navs-are-fixed .some-sample-content { position: absolute; top: 72px; /* the height of your top nav */ left: 200px; /* the width of your left nav */ } ``` ```html <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <body> <div class="some-bg-img"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand"></div> <a href="user.php" class="navbar-brand"> <p>Inicio</p> </a> <a href="instrucciones.php" class="navbar-brand"> <p>Instrucciones</p> </a> <a href="contacto.php" class="navbar-brand"> <p>Contacto</p> </a> <a href="faq.php" class="navbar-brand"> <p>FaQ</p> </a> <a href="ajax/logout.php" class="navbar-brand"> <p><i class="fas fa-sign-out-alt"></i> Salir</p> </a> </nav> <div class="d-flex h-100 w-100 position-absolute"> <nav id="menu_izq" class="sidenav"> <div></div> <a href="nueva_cata.php"> <p>Nueva Cata</p> </a> <a href="nueva_cerveza.php"> <p>Nueva Cerveza</p> </a> <a href="cata.php"> <p>Mis catas</p> </a> <a href="mis_cervezas.php"> <p>Mis cervezas</p> </a> <a href="mis_amigos.php"> <p>Mis amigos</p> </a> </nav> <div class="some-sample-content"> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> <p>Lorem Ipsum</p> </div> </div> </body> ``` If you really must keep your `fixed` positioning on your left nav, then you are going to have to compute it's `top` value based on on the `height` of both the banner & the top nav, such that if the `top` of scroll bar's Y position is past the `height` of the banner, the `top` value of the left nav will be equal to the height of the top nav - so you push it down so that they don't overlap. If the `top` of the scroll bar's Y position is not past the height of the banner, the top value of the left nav is going to be equal to the difference of the `height` of the banner & the top nav minus the top of the scroll bar's Y position. ```js $(window).scroll(function() { // innerHeight is used to include any padding var bgImgHeight = $('.some-bg-img').innerHeight(); var topNavHeight = $('#menu_arriba').innerHeight(); var leftNavInitialCssTop = bgImgHeight + topNavHeight; // if the the scroll reaches the end of the background image, this is when you start to assign 'fixed' to the top nav if ($(window).scrollTop() >= bgImgHeight) { $('body').addClass("navs-are-fixed"); $("#menu_izq").css("top", topNavHeight); } else { $('body').removeClass("navs-are-fixed"); $("#menu_izq").css("top", leftNavInitialCssTop - $(window).scrollTop()) } }); ``` ```css #menu_izq { height: 100%; width: 200px; position: fixed; left: 0; top: 252px; z-index: 3; background-color: #503522; overflow-x: hidden; padding-top: 20px; } #menu_arriba { background-color: #503522; width: 100%; z-index: 1; top: 0; } body { background-color: #ffc75a !important; height: 400vh; /* sample arbitrary value to force body scrolling */ } .some-bg-img { background: url(https://via.placeholder.com/1920x200.png?text=Sample%20Background%20Image); height: 179px; background-repeat: no-repeat; background-size: cover; background-position: bottom; } .navs-are-fixed #menu_arriba { position: fixed; } ``` ```html <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <div class="some-bg-img"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand"></div> <a href="user.php" class="navbar-brand"> <p>Inicio</p> </a> <a href="instrucciones.php" class="navbar-brand"> <p>Instrucciones</p> </a> <a href="contacto.php" class="navbar-brand"> <p>Contacto</p> </a> <a href="faq.php" class="navbar-brand"> <p>FaQ</p> </a> <a href="ajax/logout.php" class="navbar-brand"> <p><i class="fas fa-sign-out-alt"></i> Salir</p> </a> </nav> <nav id="menu_izq" class="sidenav"> <div></div> <a href="nueva_cata.php"> <p>Nueva Cata</p> </a> <a href="nueva_cerveza.php"> <p>Nueva Cerveza</p> </a> <a href="cata.php"> <p>Mis catas</p> </a> <a href="mis_cervezas.php"> <p>Mis cervezas</p> </a> <a href="mis_amigos.php"> <p>Mis amigos</p> </a> </nav> ```
The side and top sliding `<nav>` elements cannot interact correctly with the page content. Especially the lateral `<nav>` with vertical sliding according to many changing rules - sit, follow, slide against, stick apart. It's too much at once. **Workaround 1 - smooth - top sliding, side fixed** *(anchors corrected)* I'm afraid this is not the solution to your dreams. Works smooth and easy as it avoids the crush point. ``` $(window).scroll(function(){ var elementPosition = $('#menu_arriba').offset(); if($(window).scrollTop() >= elementPosition.top){ $('#menu_arriba').css('position','fixed').css('top','0'); } else { $('#menu_arriba').css('position','relative'); /* fixed */ } if(elementPosition.top <= 200){ $('#menu_arriba').css('position','initial').css('top', '200'); }}); ``` --- ``` *{ box-sizing: border-box} body{ margin: 0; text-align: center; z-index: -1; } #pilar{ /* added fix */ background: #503522; width: 200px; position: fixed; top: 0; left: 0; bottom: 0; z-index: -1 } #menu_izq { background: 0; /* fixed */ width: 200px; /* padding-top: 200px; removed */ position: fixed; top: 200px; /* fixed */ left: 0; bottom: 0; z-index: 0; /* fixed */ } #menu_arriba{ background: #503522; width: 100%; position: relative; /* added fix */ z-index: 1; /* added fix */ } p{ margin: 100px 100px 100px 250px; z-index: -1 } a{ display: inline-block; width: 150px; border: 1px solid white; text- align: center; padding: 10px 0; margin: 20px} img{ border-bottom: 10px solid #503522; margin: 0 0 -3px; width: 100%; height: 200px; z-index: 1; z-index: 9;} ``` --- ``` <img src="img/blue.jpg" alt="blue"> <div id="pilar"></div> <!-- added fix --> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand" ></div> <!-- needed or redundancy? --> <a href="user.php" class="navbar-brand">Inicio</a> <a href="instrucciones.php" class="navbar-brand">Instrucciones</a> <a href="contacto.php" class="navbar-brand">Contacto</a> <a href="faq.php" class="navbar-brand">FaQ</a> <a href="ajax/logout.php" class="navbar-brand"><i class="fas fa-sign-out-alt"></i>Salir</a> </nav> <nav class="sidenav" id="menu_izq"> <a href="nueva_cata.php">Nueva Cata</a> <a href="nueva_cerveza.php">Nueva Cerveza</a> <a href="cata.php">Mis catas</a> <a href="mis_cervezas.php">Mis cervezas</a> <a href="mis_amigos.php">Mis amigos</a> </nav><p>... </p><p> ...</p> ``` **Workaround 1.1 - smooth with a nice view** only changes ``` #menu_arriba{ background: 0; width: 100%; position: relative; /* added fix */ z-index: 0 /* added fix */ } #hole{ background: #503522; height: 100%; margin-left: 200px; width: auto; } <div id="pilar"></div> <!-- added fix --> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div id="hole"> <div class="navbar-brand" ></div> <a href="user.php" class="navbar-brand">Inicio</a> <a href="instrucciones.php" class="navbar-brand">Instrucciones</a> <a href="contacto.php" class="navbar-brand">Contacto</a> <a href="faq.php" class="navbar-brand">FaQ</a> <a href="ajax/logout.php" class="navbar-brand"><i class="fas fa-sign-out-alt"></i> Salir</a> </div></nav> ``` **Workaround 2 - dirty - hide or cover up side effects** If you still insist - not so smooth, slightly bouncy menu. Your dreams are also not coming true, but there are no visible holes. Here you have it: ``` $(window).scroll(function(){ var elementPosition = $('#menu_arriba').offset(); if($(window).scrollTop() >= elementPosition.top){ $('#menu_arriba').css('position','fixed').css('top','0'); $('#menu_izq').css('position','fixed').css('top','0'); } else { $('#menu_arriba').css('position','initial'); $('#menu_izq').css('position','initial'); } if(elementPosition.top <= 200){ $('#menu_arriba').css('position','initial').css('top', '200'); $('#menu_izq').css('position','initial').css('top', '200'); }}); ``` --- ``` *{ box-sizing: border-box} body{ margin: 0; text-align: center; } #menu_izq { background: 0; height: auto; width: 200px; padding-top: 100px; } #menu_arriba{ background: #503522; width: 100%; z-index: 1 } #pilar{ background: #503522; width: 200px; position: fixed; top: 0; left: 0; bottom: 0; z-index: -1 } p { margin: 100px 300px; position: relative; bottom: 400px} a{ display: inline-block; width: 150px; border: 1px solid white; text-align: center; padding: 10px 0; margin: 20px} img{ border-bottom: 10px solid #503522; margin: 0 0 -3px; width: 100%; height: 200px;} ``` --- ``` <img src="img/blue.jpg" alt="blue"> <div id="pilar"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand" ></div> <!-- what for it is? needed? --> <a href="user.php" class="navbar-brand">Inicio</a> <a href="instrucciones.php" class="navbar-brand">Instrucciones</a> <a href="contacto.php" class="navbar-brand">Contacto</a> <a href="faq.php" class="navbar-brand">FaQ</a> <a href="ajax/logout.php" class="navbar-brand"><i class="fas fa-sign-out-alt"></i>Salir</a> </nav> <nav class="sidenav" id="menu_izq"> <a href="nueva_cata.php">Nueva Cata</a> <a href="nueva_cerveza.php">Nueva Cerveza</a> <a href="cata.php">Mis catas</a> <a href="mis_cervezas.php">Mis cervezas</a> <a href="mis_amigos.php">Mis amigos</a> </nav><p>... </p><p> ...</p> ``` There are other minor shortcomings in your code. `<a href=""><p> .... </p></a>` may not be a crime, but neither is it good. `<p>` has its own characteristics and is not a stiffener or pillar - I fixed it with css. Above you have whole code I used - as a hint and explanation. Resize elements to your needs and taste. Hope you like it cheers
62,999,056
This python 3 code does exactly what I want ```py from pathlib import Path def minify(src_dir:Path, dest_dir:Path, n: int): """Write first n lines of each file f in src_dir to dest_dir/f""" dest_dir.mkdir(exist_ok=True) for path in src_dir.iterdir(): new = [x.rstrip() for x in list(path.open().readlines())][:n] dest_path = dest_dir.joinpath(path.name) dest_path.open('w').write('\n'.join(new)) ``` Is there a way to do the same in bash, maybe with `xargs`? ``` ls src_dist/* | xargs head -10 ``` displays what I need, but I don't know how to route that output to the proper file.
2020/07/20
[ "https://Stackoverflow.com/questions/62999056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4381942/" ]
You should be able to have that working with just CSS and no javascript using `position: sticky` attribute. Make both elements `position: sticky`, the top nav should have a `top: 0` property and the side nav should have a `top: x` property where `x` is the height of the top nav. That should be enough and you should be able to remove the js code. Read more about `sticky` position here <https://developer.mozilla.org/en-US/docs/Web/CSS/position>
why you want to do this? you can move the top menu and side menu and text container together in one container to be relative with each other, set the text box container fixed height in percent and set its `overflow-y` to `auto`. make the whole container animatable like the top menu. this will solve your problem.
62,999,056
This python 3 code does exactly what I want ```py from pathlib import Path def minify(src_dir:Path, dest_dir:Path, n: int): """Write first n lines of each file f in src_dir to dest_dir/f""" dest_dir.mkdir(exist_ok=True) for path in src_dir.iterdir(): new = [x.rstrip() for x in list(path.open().readlines())][:n] dest_path = dest_dir.joinpath(path.name) dest_path.open('w').write('\n'.join(new)) ``` Is there a way to do the same in bash, maybe with `xargs`? ``` ls src_dist/* | xargs head -10 ``` displays what I need, but I don't know how to route that output to the proper file.
2020/07/20
[ "https://Stackoverflow.com/questions/62999056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4381942/" ]
You should be able to have that working with just CSS and no javascript using `position: sticky` attribute. Make both elements `position: sticky`, the top nav should have a `top: 0` property and the side nav should have a `top: x` property where `x` is the height of the top nav. That should be enough and you should be able to remove the js code. Read more about `sticky` position here <https://developer.mozilla.org/en-US/docs/Web/CSS/position>
The side and top sliding `<nav>` elements cannot interact correctly with the page content. Especially the lateral `<nav>` with vertical sliding according to many changing rules - sit, follow, slide against, stick apart. It's too much at once. **Workaround 1 - smooth - top sliding, side fixed** *(anchors corrected)* I'm afraid this is not the solution to your dreams. Works smooth and easy as it avoids the crush point. ``` $(window).scroll(function(){ var elementPosition = $('#menu_arriba').offset(); if($(window).scrollTop() >= elementPosition.top){ $('#menu_arriba').css('position','fixed').css('top','0'); } else { $('#menu_arriba').css('position','relative'); /* fixed */ } if(elementPosition.top <= 200){ $('#menu_arriba').css('position','initial').css('top', '200'); }}); ``` --- ``` *{ box-sizing: border-box} body{ margin: 0; text-align: center; z-index: -1; } #pilar{ /* added fix */ background: #503522; width: 200px; position: fixed; top: 0; left: 0; bottom: 0; z-index: -1 } #menu_izq { background: 0; /* fixed */ width: 200px; /* padding-top: 200px; removed */ position: fixed; top: 200px; /* fixed */ left: 0; bottom: 0; z-index: 0; /* fixed */ } #menu_arriba{ background: #503522; width: 100%; position: relative; /* added fix */ z-index: 1; /* added fix */ } p{ margin: 100px 100px 100px 250px; z-index: -1 } a{ display: inline-block; width: 150px; border: 1px solid white; text- align: center; padding: 10px 0; margin: 20px} img{ border-bottom: 10px solid #503522; margin: 0 0 -3px; width: 100%; height: 200px; z-index: 1; z-index: 9;} ``` --- ``` <img src="img/blue.jpg" alt="blue"> <div id="pilar"></div> <!-- added fix --> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand" ></div> <!-- needed or redundancy? --> <a href="user.php" class="navbar-brand">Inicio</a> <a href="instrucciones.php" class="navbar-brand">Instrucciones</a> <a href="contacto.php" class="navbar-brand">Contacto</a> <a href="faq.php" class="navbar-brand">FaQ</a> <a href="ajax/logout.php" class="navbar-brand"><i class="fas fa-sign-out-alt"></i>Salir</a> </nav> <nav class="sidenav" id="menu_izq"> <a href="nueva_cata.php">Nueva Cata</a> <a href="nueva_cerveza.php">Nueva Cerveza</a> <a href="cata.php">Mis catas</a> <a href="mis_cervezas.php">Mis cervezas</a> <a href="mis_amigos.php">Mis amigos</a> </nav><p>... </p><p> ...</p> ``` **Workaround 1.1 - smooth with a nice view** only changes ``` #menu_arriba{ background: 0; width: 100%; position: relative; /* added fix */ z-index: 0 /* added fix */ } #hole{ background: #503522; height: 100%; margin-left: 200px; width: auto; } <div id="pilar"></div> <!-- added fix --> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div id="hole"> <div class="navbar-brand" ></div> <a href="user.php" class="navbar-brand">Inicio</a> <a href="instrucciones.php" class="navbar-brand">Instrucciones</a> <a href="contacto.php" class="navbar-brand">Contacto</a> <a href="faq.php" class="navbar-brand">FaQ</a> <a href="ajax/logout.php" class="navbar-brand"><i class="fas fa-sign-out-alt"></i> Salir</a> </div></nav> ``` **Workaround 2 - dirty - hide or cover up side effects** If you still insist - not so smooth, slightly bouncy menu. Your dreams are also not coming true, but there are no visible holes. Here you have it: ``` $(window).scroll(function(){ var elementPosition = $('#menu_arriba').offset(); if($(window).scrollTop() >= elementPosition.top){ $('#menu_arriba').css('position','fixed').css('top','0'); $('#menu_izq').css('position','fixed').css('top','0'); } else { $('#menu_arriba').css('position','initial'); $('#menu_izq').css('position','initial'); } if(elementPosition.top <= 200){ $('#menu_arriba').css('position','initial').css('top', '200'); $('#menu_izq').css('position','initial').css('top', '200'); }}); ``` --- ``` *{ box-sizing: border-box} body{ margin: 0; text-align: center; } #menu_izq { background: 0; height: auto; width: 200px; padding-top: 100px; } #menu_arriba{ background: #503522; width: 100%; z-index: 1 } #pilar{ background: #503522; width: 200px; position: fixed; top: 0; left: 0; bottom: 0; z-index: -1 } p { margin: 100px 300px; position: relative; bottom: 400px} a{ display: inline-block; width: 150px; border: 1px solid white; text-align: center; padding: 10px 0; margin: 20px} img{ border-bottom: 10px solid #503522; margin: 0 0 -3px; width: 100%; height: 200px;} ``` --- ``` <img src="img/blue.jpg" alt="blue"> <div id="pilar"></div> <nav class="navbar navbar-expand-lg navbar-light bg-light" id="menu_arriba"> <div class="navbar-brand" ></div> <!-- what for it is? needed? --> <a href="user.php" class="navbar-brand">Inicio</a> <a href="instrucciones.php" class="navbar-brand">Instrucciones</a> <a href="contacto.php" class="navbar-brand">Contacto</a> <a href="faq.php" class="navbar-brand">FaQ</a> <a href="ajax/logout.php" class="navbar-brand"><i class="fas fa-sign-out-alt"></i>Salir</a> </nav> <nav class="sidenav" id="menu_izq"> <a href="nueva_cata.php">Nueva Cata</a> <a href="nueva_cerveza.php">Nueva Cerveza</a> <a href="cata.php">Mis catas</a> <a href="mis_cervezas.php">Mis cervezas</a> <a href="mis_amigos.php">Mis amigos</a> </nav><p>... </p><p> ...</p> ``` There are other minor shortcomings in your code. `<a href=""><p> .... </p></a>` may not be a crime, but neither is it good. `<p>` has its own characteristics and is not a stiffener or pillar - I fixed it with css. Above you have whole code I used - as a hint and explanation. Resize elements to your needs and taste. Hope you like it cheers
58,525,753
I'm trying to use Ansible with ssh for interact with Windows machines i have successfully install OpenSSH on a Windows machine that mean i can connect from linux to windows with: ``` ssh username@ipAdresse ``` i've tried using a lot of version of ansible (2.6, 2.7.12, 2.7.14, 2.8.5 and 2.8.6) and i always test if i can ping an other Linux machine with this line(it work): ``` ansible linux -m ping ``` There is my hosts file ``` [windows] 192.***.***.*** [linux] 192.***.***.*** [all:vars] ansible_connection=ssh ansible_user=root [windows:vars] ansible_ssh_pass=******* remote_tmp=C:\Users\root\AppData\Local\Temp\ become_method=runas ``` there is the error with verbose: ``` [root@oel76-template ~]# ansible windows -m win_ping -vvv ansible 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /usr/bin/ansible python version = 2.7.5 (default, Aug 7 2019, 08:19:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39.0.1)] Using /etc/ansible/ansible.cfg as config file host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Parsed /etc/ansible/hosts inventory source with ini plugin META: ran handlers <192.***.***.***> ESTABLISH SSH CONNECTION FOR USER: root <192.***.***.***> SSH: EXEC sshpass -d8 ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'User="root"' -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/91df1ca379 192.168.46.99 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo C:/Users/root/AppData/Local/Temp/ansible-tmp-1571839448.66-279092717123794 `" && echo ansible-tmp-1571839448.66-279092717123794="` echo C:/Users/root/AppData/Local/Temp/ansible-tmp-1571839448.66-279092717123794 `" ) && sleep 0'"'"'' <192.***.***.***> (1, '', 'The system cannot find the path specified.\r\n') <192.***.***.***> Failed to connect to the host via ssh: The system cannot find the path specified. 192.***.***.*** | UNREACHABLE! => { "changed": false, "msg": "Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the target directory. Consider changing the remote tmp path in ansible.cfg to a path rooted in \"/tmp\". Failed command was: ( umask 77 && mkdir -p \"` echo C:/Users/root/AppData/Local/Temp/ansible-tmp-1571839448.66-279092717123794 `\" && echo ansible-tmp-1571839448.66-279092717123794=\"` echo C:/Users/root/AppData/Local/Temp/ansible-tmp-1571839448.66-279092717123794 `\" ), exited with result 1", "unreachable": true } ``` I don't know what i'm doing wrong, i also try to change the remote\_tmp in ansible.cfg but nothing more. Actual value for remote\_tmp=C:/Users/root/AppData/Local/Temp Any idea ?
2019/10/23
[ "https://Stackoverflow.com/questions/58525753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11431519/" ]
Ok solved, the problem was ``` ansible_ssh_pass=***** ``` the correct syntax is ``` ansible_password=***** ```
To use SSH as the connection to a Windows host (starting from Ansible 2.8), set the following variables in the inventory: * ansible\_connection=ssh * **ansible\_shell\_type**=cmd/powershell (Set either cmd or powershell not both) Finally, the inventory file: ``` [windows] 192.***.***.*** [all:vars] ansible_connection=ssh ansible_user=root [windows:vars] ansible_password='*******' ansible_shell_type=cmd ``` Note for the variable **ansible\_password**. Use single quotation for password with special characters.
68,590,820
I want to use the face recognition module of python in a project but when I am trying to install it using the command "pip install face\_recognition" or "pip install face-recognition", it is showing an error and is not installing. This is the screenshot of the error:[![enter image description here](https://i.stack.imgur.com/DP5RK.png)](https://i.stack.imgur.com/DP5RK.png) How to fix this error and install the module? Thanks in advance!
2021/07/30
[ "https://Stackoverflow.com/questions/68590820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16017288/" ]
Your base template should provide defaults for most or all pages, but make it possible to override the default in cases where it's less than ideal. Here, put the base template message code into a named block. ``` {% block default_messages %} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert" id="message"> {{ message }} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} {% endif %} {% endblock default_messages %} ``` Now in any page where you find that the default is undesirable, you can override it. In `page_template.html`: ``` {% block default_messages %} <!-- delete the default, i.e. omit { { block.super } } --> {% endblock default_messages %} ``` and handle `messages` explicitly, elsewhere in `page_template.html`, perhaps with a `%include` if the block of message code is going to be useful in multiple pages.
``` {% block content %} {% endblock %} ``` put these inside div tag
61,969,924
my problem is that i am trying to use locust for the first time and i copied the basic code from their website <https://docs.locust.io/en/stable/quickstart.html> this is the code that they have given ``` from locust import HttpUser, task, between import random class WebsiteUser(HttpUser): wait_time = between(5, 9) @task(2) def index(self): self.client.get("/") self.client.get("/ajax-notifications/") @task(1) def view_post(self): post_id = random.randint(1, 10000) self.client.get("/post?id=%i" % post_id, name="/post?id=[post-id]") def on_start(self): """ on_start is called when a User starts before any task is scheduled """ self.login() def login(self): self.client.post("/login", {"username":"ellen_key", "password":"education"}) ``` This is the path to my locustfile.py E:\work\wipro\work\locust\_training\locustfile.py To run the locustfile.py i type locust in terminal ``` E:\work\wipro\work\locust_training>locust ``` The error that it throws is ``` [2020-05-23 14:44:25,916] DESKTOP-LQ261OQ/INFO/locust.main: Starting web monitor at http://:8089 Traceback (most recent call last): File "e:\setup\python\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "e:\setup\python\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "E:\setup\python\Scripts\locust.exe\__main__.py", line 9, in <module> File "e:\setup\python\lib\site-packages\locust\main.py", line 236, in main web_ui = environment.create_web_ui( File "e:\setup\python\lib\site-packages\locust\env.py", line 144, in create_web_ui self.web_ui = WebUI(self, host, port, auth_credentials=auth_credentials, tls_cert=tls_cert, tls_key=tls_key) File "e:\setup\python\lib\site-packages\locust\web.py", line 79, in __init__ app = Flask(__name__) File "e:\setup\python\lib\site-packages\flask\app.py", line 558, in __init__ self.add_url_rule( File "e:\setup\python\lib\site-packages\flask\app.py", line 66, in wrapper_func return f(self, *args, **kwargs) File "e:\setup\python\lib\site-packages\flask\app.py", line 1216, in add_url_rule self.url_map.add(rule) File "e:\setup\python\lib\site-packages\werkzeug\routing.py", line 1562, in add rule.bind(self) File "e:\setup\python\lib\site-packages\werkzeug\routing.py", line 711, in bind self.compile() File "e:\setup\python\lib\site-packages\werkzeug\routing.py", line 767, in compile self._build = self._compile_builder(False) File "e:\setup\python\lib\site-packages\werkzeug\routing.py", line 1128, in _compile_builder return self.BuilderCompiler(self).compile(append_unknown) File "e:\setup\python\lib\site-packages\werkzeug\routing.py", line 1119, in compile co = types.CodeType(*code_args) TypeError: code() takes at least 14 arguments (13 given) ``` I searched for the same but was not able to find any specific solution I even tried to copy any locust code i was able to find but that was also not helpful as in one way or other either this error came or some other Can anyone help with this What should I do next Any help will be appreciated And Thanks in Advance
2020/05/23
[ "https://Stackoverflow.com/questions/61969924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5825106/" ]
**If it crash on iOS :** Check if you have updated your Info.plist file. You must have the key «Privacy - Contacts Usage Description» with a sentence in value. Follow the documentation : <https://github.com/morenoh149/react-native-contacts#ios-2> **If it crash on Android :** Check if you have updated your AndroidManifest.xml file. You must request permission, like iOS. Follow the documentation : <https://github.com/morenoh149/react-native-contacts#permissions>
``` //Try it const addContact = () => { PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS, PermissionsAndroid.PERMISSIONS.READ_CONTACTS, ]) Contacts.getAll().then(contacts => { // console.log('hello',contacts); setMblContacts(contacts); }) } ```
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
I didn't like the idea of commenting/uncommenting code, so I tried a different approach: I migrated "manually" some apps, and then run `django-admin.py migrate` for the remaining ones. After deleting all the `*.pyc` files, my sequence of commands was: ``` $ django-admin.py migrate auth $ django-admin.py migrate contentypes $ django-admin.py migrate sites $ django-admin.py migrate MY_CUSTOM_USER_APP $ django-admin.py migrate ``` where `MY_CUSTOM_USER_APP` is the name of the application containing the model I set `AUTH_USER_MODEL` to in my `settings` file. Hope it can help. Btw, it seems strange that the best way to synchronize your db in Django 1.8 is so complicated. I wonder if I'm missing something (I'm not very familiar with Django 1.8, I used to work with older versions)
I had this issues with a `forms.ChoiceForm` queryset. I was able to switch to using [`forms.ModelChoiceForm`](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield) which are lazily evaluated and this fixed the problem for me.
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
Working on Django 1.10 I found out another solution: My application is named "web", and first I call: ``` python manage.py makemigrations web ``` then I call: ``` python manage.py makemigrations auth ``` then I call: ``` python manage.py migrate ``` Amazed: IT'S WORKING! :) It seems auth was searching for the AUTH\_USER\_MODEL "web.UserProfile" and a relation named web\_user\_profile, and it didn't find it, hence the error. On the other hand, calling makemigrations web first creates the required relation first, before auth is able to check and alert it's not there.
Always migrate db with `python manage.py makemigrations` and then `python manage.py migrate` in newer versions. For the error above if first time your are migrating your database then use `python manage.py migrate --fake-initial`. See docs <https://docs.djangoproject.com/en/1.9/ref/django-admin/#django-admin-migrate>
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
I didn't like the idea of commenting/uncommenting code, so I tried a different approach: I migrated "manually" some apps, and then run `django-admin.py migrate` for the remaining ones. After deleting all the `*.pyc` files, my sequence of commands was: ``` $ django-admin.py migrate auth $ django-admin.py migrate contentypes $ django-admin.py migrate sites $ django-admin.py migrate MY_CUSTOM_USER_APP $ django-admin.py migrate ``` where `MY_CUSTOM_USER_APP` is the name of the application containing the model I set `AUTH_USER_MODEL` to in my `settings` file. Hope it can help. Btw, it seems strange that the best way to synchronize your db in Django 1.8 is so complicated. I wonder if I'm missing something (I'm not very familiar with Django 1.8, I used to work with older versions)
I had the same issue, but my underlying cause was the `__init__.py` file in one of the migrations folders had been deleted from source code but not locally (causing 'Not on my machine' errors). Migrations folders still need `__init__.py` files, even with Python 3.
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
Working on Django 1.10 I found out another solution: My application is named "web", and first I call: ``` python manage.py makemigrations web ``` then I call: ``` python manage.py makemigrations auth ``` then I call: ``` python manage.py migrate ``` Amazed: IT'S WORKING! :) It seems auth was searching for the AUTH\_USER\_MODEL "web.UserProfile" and a relation named web\_user\_profile, and it didn't find it, hence the error. On the other hand, calling makemigrations web first creates the required relation first, before auth is able to check and alert it's not there.
I had the same problem, and I spent hours banging my head trying to find a solution, which was hidden in the comments. My problem was that CircleCI couldn't run tests because of this error. And I thought I would need to start fresh with a new and empty DB. But I got the same errors. Everything was seemingly related to 'auth', 'contenttypes' and 'sites'. I read [this](https://stackoverflow.com/questions/25609059/django-db-utils-programmingerror-relation-blogango-blog-does-not-exist), and [this](https://stackoverflow.com/questions/30356963/django-postgres-migration-failing-django-db-utils-programmingerror-relation-d), as well as [this](https://stackoverflow.com/questions/23925726/django-relation-django-site-does-not-exist) and also [this](https://stackoverflow.com/questions/31417470/django-db-utils-programmingerror-relation-app-user-does-not-exist-during-ma). None were solutions for me. So after having destroyed my DB and created a new one, the only solution I found to entirely avoid these `django.db.utils.ProgrammingError` was to: 1. Comment out all code related to the `User` model. 2. Delete all .pyc files in my project! `find . -name "*.pyc" -exec rm -- {} +` Thanks @max! 3. run `./manage.py migrate` (no fake, no fake-initial, no migration of 'auth' or 'contenttypes' before, juste plain migrate. 4. Uncomment the above code, and run migrate again! My INSTALLED\_APP is the following: ``` INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'mptt', 'djangobower', 'honeypot', 'django_hosts', 'leaflet', 'multiselectfield', 'corsheaders', 'rest_framework_swagger', 'allauth', 'allauth.account', # 'allauth.socialaccount', # 'allauth.socialaccount.providers.twitter', # 'allauth.socialaccount.providers.facebook', 'project.<app_name>', ) ```
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
I didn't like the idea of commenting/uncommenting code, so I tried a different approach: I migrated "manually" some apps, and then run `django-admin.py migrate` for the remaining ones. After deleting all the `*.pyc` files, my sequence of commands was: ``` $ django-admin.py migrate auth $ django-admin.py migrate contentypes $ django-admin.py migrate sites $ django-admin.py migrate MY_CUSTOM_USER_APP $ django-admin.py migrate ``` where `MY_CUSTOM_USER_APP` is the name of the application containing the model I set `AUTH_USER_MODEL` to in my `settings` file. Hope it can help. Btw, it seems strange that the best way to synchronize your db in Django 1.8 is so complicated. I wonder if I'm missing something (I'm not very familiar with Django 1.8, I used to work with older versions)
Deleting migration files, associated .pyc files, and just to be safe all .pyc files with the following commands did not solve my issue. ``` $ find . -path "*/migrations/*.py" -not -name "__init__.py" -delete $ find . -path "*/migrations/*.pyc" -delete $ find . -name "*.pyc" -exec rm -- {} + ``` What ended up solving my issue wasn't clearing caches, it was because I had a function that performed a query as a default function parameter. On init, which is what commands like `makemigrations` and `migrate` do before executing it seems like django (perhaps a python attribute?) initializes all default parameters. As my database was completely empty (I needed to perform `migrate --run-syncdb` to recreate the tables) when the below default parameter was initialized, it ran a query against the empty database that subsequently failed. change this: ``` def generate_new_addresses(number=1, index=None, wallet=get_active_wallet()): ... ... return ``` to: ``` def generate_new_addresses(number=1, index=None, wallet=None): if not wallet: wallet = get_active_wallet() ... ... return ```
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
I didn't like the idea of commenting/uncommenting code, so I tried a different approach: I migrated "manually" some apps, and then run `django-admin.py migrate` for the remaining ones. After deleting all the `*.pyc` files, my sequence of commands was: ``` $ django-admin.py migrate auth $ django-admin.py migrate contentypes $ django-admin.py migrate sites $ django-admin.py migrate MY_CUSTOM_USER_APP $ django-admin.py migrate ``` where `MY_CUSTOM_USER_APP` is the name of the application containing the model I set `AUTH_USER_MODEL` to in my `settings` file. Hope it can help. Btw, it seems strange that the best way to synchronize your db in Django 1.8 is so complicated. I wonder if I'm missing something (I'm not very familiar with Django 1.8, I used to work with older versions)
Error is basically because db (postgres or sqlite) have not found the relation, for which you are inserting or else performing CRUD. The solution is to make migrations `python manage.py makemigrations <app_name> python manage.py migrate`
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
Deleting migration files, associated .pyc files, and just to be safe all .pyc files with the following commands did not solve my issue. ``` $ find . -path "*/migrations/*.py" -not -name "__init__.py" -delete $ find . -path "*/migrations/*.pyc" -delete $ find . -name "*.pyc" -exec rm -- {} + ``` What ended up solving my issue wasn't clearing caches, it was because I had a function that performed a query as a default function parameter. On init, which is what commands like `makemigrations` and `migrate` do before executing it seems like django (perhaps a python attribute?) initializes all default parameters. As my database was completely empty (I needed to perform `migrate --run-syncdb` to recreate the tables) when the below default parameter was initialized, it ran a query against the empty database that subsequently failed. change this: ``` def generate_new_addresses(number=1, index=None, wallet=get_active_wallet()): ... ... return ``` to: ``` def generate_new_addresses(number=1, index=None, wallet=None): if not wallet: wallet = get_active_wallet() ... ... return ```
In my case, this error was appearing when the postgresql driver was able to connect to the database, but the provided user does not have access to the schema or the tables, etc. Instead of saying permission denied, the error being shown is saying that the database table being queried is not being found. Typically in such a situation, the migrate command will also fail with a similar error when it tries to create the `django_migrations` table. Check for access being granted on the user you're using in database connection in Django.
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
Deleting migration files, associated .pyc files, and just to be safe all .pyc files with the following commands did not solve my issue. ``` $ find . -path "*/migrations/*.py" -not -name "__init__.py" -delete $ find . -path "*/migrations/*.pyc" -delete $ find . -name "*.pyc" -exec rm -- {} + ``` What ended up solving my issue wasn't clearing caches, it was because I had a function that performed a query as a default function parameter. On init, which is what commands like `makemigrations` and `migrate` do before executing it seems like django (perhaps a python attribute?) initializes all default parameters. As my database was completely empty (I needed to perform `migrate --run-syncdb` to recreate the tables) when the below default parameter was initialized, it ran a query against the empty database that subsequently failed. change this: ``` def generate_new_addresses(number=1, index=None, wallet=get_active_wallet()): ... ... return ``` to: ``` def generate_new_addresses(number=1, index=None, wallet=None): if not wallet: wallet = get_active_wallet() ... ... return ```
Error is basically because db (postgres or sqlite) have not found the relation, for which you are inserting or else performing CRUD. The solution is to make migrations `python manage.py makemigrations <app_name> python manage.py migrate`
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
Working on Django 1.10 I found out another solution: My application is named "web", and first I call: ``` python manage.py makemigrations web ``` then I call: ``` python manage.py makemigrations auth ``` then I call: ``` python manage.py migrate ``` Amazed: IT'S WORKING! :) It seems auth was searching for the AUTH\_USER\_MODEL "web.UserProfile" and a relation named web\_user\_profile, and it didn't find it, hence the error. On the other hand, calling makemigrations web first creates the required relation first, before auth is able to check and alert it's not there.
In my case, this error was appearing when the postgresql driver was able to connect to the database, but the provided user does not have access to the schema or the tables, etc. Instead of saying permission denied, the error being shown is saying that the database table being queried is not being found. Typically in such a situation, the migrate command will also fail with a similar error when it tries to create the `django_migrations` table. Check for access being granted on the user you're using in database connection in Django.
30,897,442
I had a working project with django 1.7, and now I moved it to django 1.8. I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**: ``` Creating tables... Creating table x Creating table y Running deferred SQL... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "~/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "~/venv/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle created_models = self.sync_apps(connection, executor.loader.unmigrated_apps) File "~/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps cursor.execute(statement) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "~/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "~/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "auth_user" does not exist ``` I tried deleting the database and recreating it. Also, I tried: ``` python manage.py migrate auth ``` which also fails: ``` django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 ``` Please help get this fixed.
2015/06/17
[ "https://Stackoverflow.com/questions/30897442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896222/" ]
In my case, this error was appearing when the postgresql driver was able to connect to the database, but the provided user does not have access to the schema or the tables, etc. Instead of saying permission denied, the error being shown is saying that the database table being queried is not being found. Typically in such a situation, the migrate command will also fail with a similar error when it tries to create the `django_migrations` table. Check for access being granted on the user you're using in database connection in Django.
Error is basically because db (postgres or sqlite) have not found the relation, for which you are inserting or else performing CRUD. The solution is to make migrations `python manage.py makemigrations <app_name> python manage.py migrate`
2,066,049
I'm trying to write a POS-style application for a [Sheevaplug](http://en.wikipedia.org/wiki/SheevaPlug) that does the following: 1. Captures input from a card reader (as I understand, most mag card readers emulate keyboard input, so basically I'm looking to capture that) 2. Doesn't require X 3. Runs in the background (daemon) I've seen examples of code that will wait for STDIN, but that won't work because this is a background process with no login, not even a monitor actually. I also found this snippet [elsewhere](https://stackoverflow.com/questions/1859049/check-if-key-is-pressed-using-python-a-daemon-in-the-background) on this site: ``` from struct import unpack port = open("/dev/input/event1","rb") while 1: a,b,c,d = unpack("4B",port.read(4)) print a,b,c,d ``` Which, while being the closest thing to what I need so far, only generates a series of numbers, all of which are different with no way that I know of to translate them into useful values. Clearly, I'm missing something here, but I don't know what it is. Can someone please how to get the rest of the way?
2010/01/14
[ "https://Stackoverflow.com/questions/2066049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231670/" ]
Section 5 of the Linux kernel [input documentation](http://www.kernel.org/doc/Documentation/input/input.txt) describes what each of the values in the event interface means.
the format is explained in the [kernel documentation](http://www.mjmwired.net/kernel/Documentation/input/) in section *5. Event Interface*.
6,495,688
There are lots of [good](https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script) [reasons](https://stackoverflow.com/questions/1352922/why-is-usr-bin-env-python-supposedly-more-correct-than-just-usr-bin-pyth) to use #! /usr/bin/env. Bottom line: It makes your code more portable. Well, sorta. Check this out.... --- I have two nearly identical scripts, `bintest.py` ``` #! /usr/bin/python import time time.sleep(5*60) ``` and `envtest.py` ``` #! /usr/bin/env python import time time.sleep(5*60) ``` Note that they are only different in their [shebangs](http://en.wikipedia.org/wiki/Shebang_%28Unix%29). --- `bintest.py` runs as expected ``` br@carina:~$ ./bintest.py & ps && killall bintest.py [1] 15061 PID TTY TIME CMD 14625 pts/0 00:00:00 bash 15061 pts/0 00:00:00 bintest.py 15062 pts/0 00:00:00 ps br@carina:~$ [1]+ Terminated ./bintest.py ``` but `envtest.py` does something less-than-optimal ``` br@carina:~$ ./envtest.py & ps && killall envtest.py [1] 15066 PID TTY TIME CMD 14625 pts/0 00:00:00 bash 15066 pts/0 00:00:00 python 15067 pts/0 00:00:00 ps envtest.py: no process found br@carina:~$ killall python br@carina:~$ [1]+ Terminated ./envtest.py ``` --- What we've seen is that using `#! /usr/bin/env` caused the process to receive the name "python" rather than "envtest.py", thus rendering our `killall` ineffective. On some level it seems like we've traded one kind of portability for another: we can now swap out python interpreters easily, but we've lost "kill-ability" on the command line. What's up with that? If there's a best-practice here for achieving both, what is it?
2011/06/27
[ "https://Stackoverflow.com/questions/6495688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730070/" ]
*"kill-ability" on the command line* can by addressed portably and reliably using the PID of the backgrounded process obtained from shell `$!` variable. ``` $ ./bintest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid [1] 2993 bg_pid=2993 PID TTY TIME CMD 2410 pts/0 00:00:00 bash 2993 pts/0 00:00:00 bintest.py 2994 pts/0 00:00:00 ps $ [1]+ Terminated ./bintest.py $ ``` and envtest.py ``` $ ./envtest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid [1] 3016 bg_pid=3016 PID TTY TIME CMD 2410 pts/0 00:00:00 bash 3016 pts/0 00:00:00 python 3017 pts/0 00:00:00 ps $ [1]+ Terminated ./envtest.py $ ``` As @Adam Bryzak points out, neither script cause the process title to be set on Mac OS X. So, if that feature is a firm requirement, you may need to install and use python module [setproctitle](http://pypi.python.org/pypi/setproctitle) with your application. This Stackoverflow post discusses [setting process title in python](https://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python)
I don't think you can rely on the `killall` using the script name to work all the time. On Mac OS X I get the following output from `ps` after running both scripts: ``` 2108 ttys004 0:00.04 /usr/local/bin/python /Users/adam/bin/bintest.py 2133 ttys004 0:00.03 python /Users/adam/bin/envtest.py ``` and running `killall bintest.py` results in ``` No matching processes belonging to you were found ```
6,495,688
There are lots of [good](https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script) [reasons](https://stackoverflow.com/questions/1352922/why-is-usr-bin-env-python-supposedly-more-correct-than-just-usr-bin-pyth) to use #! /usr/bin/env. Bottom line: It makes your code more portable. Well, sorta. Check this out.... --- I have two nearly identical scripts, `bintest.py` ``` #! /usr/bin/python import time time.sleep(5*60) ``` and `envtest.py` ``` #! /usr/bin/env python import time time.sleep(5*60) ``` Note that they are only different in their [shebangs](http://en.wikipedia.org/wiki/Shebang_%28Unix%29). --- `bintest.py` runs as expected ``` br@carina:~$ ./bintest.py & ps && killall bintest.py [1] 15061 PID TTY TIME CMD 14625 pts/0 00:00:00 bash 15061 pts/0 00:00:00 bintest.py 15062 pts/0 00:00:00 ps br@carina:~$ [1]+ Terminated ./bintest.py ``` but `envtest.py` does something less-than-optimal ``` br@carina:~$ ./envtest.py & ps && killall envtest.py [1] 15066 PID TTY TIME CMD 14625 pts/0 00:00:00 bash 15066 pts/0 00:00:00 python 15067 pts/0 00:00:00 ps envtest.py: no process found br@carina:~$ killall python br@carina:~$ [1]+ Terminated ./envtest.py ``` --- What we've seen is that using `#! /usr/bin/env` caused the process to receive the name "python" rather than "envtest.py", thus rendering our `killall` ineffective. On some level it seems like we've traded one kind of portability for another: we can now swap out python interpreters easily, but we've lost "kill-ability" on the command line. What's up with that? If there's a best-practice here for achieving both, what is it?
2011/06/27
[ "https://Stackoverflow.com/questions/6495688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730070/" ]
*"kill-ability" on the command line* can by addressed portably and reliably using the PID of the backgrounded process obtained from shell `$!` variable. ``` $ ./bintest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid [1] 2993 bg_pid=2993 PID TTY TIME CMD 2410 pts/0 00:00:00 bash 2993 pts/0 00:00:00 bintest.py 2994 pts/0 00:00:00 ps $ [1]+ Terminated ./bintest.py $ ``` and envtest.py ``` $ ./envtest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid [1] 3016 bg_pid=3016 PID TTY TIME CMD 2410 pts/0 00:00:00 bash 3016 pts/0 00:00:00 python 3017 pts/0 00:00:00 ps $ [1]+ Terminated ./envtest.py $ ``` As @Adam Bryzak points out, neither script cause the process title to be set on Mac OS X. So, if that feature is a firm requirement, you may need to install and use python module [setproctitle](http://pypi.python.org/pypi/setproctitle) with your application. This Stackoverflow post discusses [setting process title in python](https://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python)
While I would still like a solution that makes scripting languages both cross-platform and easy-to-monitor from the command line, if you're just looking for an alternative to `killall <scriptname>` to stop custom services, here's how I solved it: ``` kill `ps -fC <interpreterName> | sed -n '/<scriptName>/s/^[^0-9]*\([0-9]*\).*$/\1/gp'` ``` For those not too familiar with ps and regexes, `ps`'s `-f` modifier has it list out a "full" set of information about a process, including its command-line arguments, and `-C` tells it to filter the list to only commands that match the next command-line argument. Replace `<interpreterName>` with `python` or `node` or whatever. `sed`'s `-n` argument tells it to not print anything by default, and the regex script has to explicitly indicate that you want to print something. In the regex, the first `/<scriptName>/` tells it to filter its results to only lines that contain the interior regex. You can replace `<scriptName>` with `envtest`, for example. The `s` indicates that a substitution regex will follow. `/^[^0-9]*\([0-9]*\).*$/` being the line matching portion and `/\1/` being the substitution portion. In the line matching portion, the `^` at the very beginning and the `$` at the very end mean that the match must start from the beginning of the line and end at the end of the line -- the entire line being checked is to be replaced. The `[^0-9]*` involves a few things: `[]` are used to define a set of allowable characters. Within this portion of the regex, the dash `-` means a range of characters, so it expands to `0123456789`. The `^` here mean "not" and immediately means "match any character that is NOT a number". The asterisk `*` afterwards means to keep on matching characters in this set until it encounters a non-matching character, in this case a number. The `\([0-9]*\)` has two portions, the `\(\)` and `[0-9]*`. The latter should be easy to follow from the previous explanation: it matches only numbers, and grabs as many as it can. The `\(\)` mean to save the contents of what is matched to a temporary variable. (In other RegEx versions, including Javascript and Perl, `()` is used, instead.) Finally, the `.*` means to match every remaining character, as `.` means any possible character. The `/\1/` portion says to replace the matched portion of the line (which is the whole line in this case) with `\1`, which is a reference to the saved temporary variable (if there had been two `\(\)` sections, the first one in the RegEx would be `\1` and the second `\2`). The `g` afterwards mean to be "greedy" and run this matching code on every line encountered, and the `p` means to print any line that has reached this point. Technically, this will blow up if you have multiple copies of your script running, and you'd really want the slightly heavier: ``` ps -fC <interpreterName> | sed -n '/<scriptName>/s/^[^0-9]*\([0-9]*\).$/kill \1/gp' | bash ``` If you want to truly replicate kill\*all\* functionality, but this spawns a separate bash shell for each script you'd like to kill.
6,495,688
There are lots of [good](https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script) [reasons](https://stackoverflow.com/questions/1352922/why-is-usr-bin-env-python-supposedly-more-correct-than-just-usr-bin-pyth) to use #! /usr/bin/env. Bottom line: It makes your code more portable. Well, sorta. Check this out.... --- I have two nearly identical scripts, `bintest.py` ``` #! /usr/bin/python import time time.sleep(5*60) ``` and `envtest.py` ``` #! /usr/bin/env python import time time.sleep(5*60) ``` Note that they are only different in their [shebangs](http://en.wikipedia.org/wiki/Shebang_%28Unix%29). --- `bintest.py` runs as expected ``` br@carina:~$ ./bintest.py & ps && killall bintest.py [1] 15061 PID TTY TIME CMD 14625 pts/0 00:00:00 bash 15061 pts/0 00:00:00 bintest.py 15062 pts/0 00:00:00 ps br@carina:~$ [1]+ Terminated ./bintest.py ``` but `envtest.py` does something less-than-optimal ``` br@carina:~$ ./envtest.py & ps && killall envtest.py [1] 15066 PID TTY TIME CMD 14625 pts/0 00:00:00 bash 15066 pts/0 00:00:00 python 15067 pts/0 00:00:00 ps envtest.py: no process found br@carina:~$ killall python br@carina:~$ [1]+ Terminated ./envtest.py ``` --- What we've seen is that using `#! /usr/bin/env` caused the process to receive the name "python" rather than "envtest.py", thus rendering our `killall` ineffective. On some level it seems like we've traded one kind of portability for another: we can now swap out python interpreters easily, but we've lost "kill-ability" on the command line. What's up with that? If there's a best-practice here for achieving both, what is it?
2011/06/27
[ "https://Stackoverflow.com/questions/6495688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730070/" ]
*"kill-ability" on the command line* can by addressed portably and reliably using the PID of the backgrounded process obtained from shell `$!` variable. ``` $ ./bintest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid [1] 2993 bg_pid=2993 PID TTY TIME CMD 2410 pts/0 00:00:00 bash 2993 pts/0 00:00:00 bintest.py 2994 pts/0 00:00:00 ps $ [1]+ Terminated ./bintest.py $ ``` and envtest.py ``` $ ./envtest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid [1] 3016 bg_pid=3016 PID TTY TIME CMD 2410 pts/0 00:00:00 bash 3016 pts/0 00:00:00 python 3017 pts/0 00:00:00 ps $ [1]+ Terminated ./envtest.py $ ``` As @Adam Bryzak points out, neither script cause the process title to be set on Mac OS X. So, if that feature is a firm requirement, you may need to install and use python module [setproctitle](http://pypi.python.org/pypi/setproctitle) with your application. This Stackoverflow post discusses [setting process title in python](https://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python)
In a comment, you say that the problem is that different systems (particularly MacOS and Linux) place executables in different directories. You can work around this by creating a directory with the same full path on both systems, and creating symbolic links to the executables. Experiment on Ubuntu, Solaris, and Cygwin indicates that the executable named in a shebang can be a symbolic link. (I don't have access to a MacOS system, so I'm not sure that it will work there.) For example, on my Ubuntu system: ``` $ cat hello.bash #!/tmp/bin/bash echo Yes, it works $ ./hello.bash -bash: ./hello.bash: /tmp/bin/bash: bad interpreter: Permission denied $ mkdir /tmp/bin $ ln -s /bin/bash /tmp/bin/. $ ./hello.bash Yes, it works $ ``` Setting up the common directory on all the relevant systems is admittedly inconvenient. (I used `/tmp` for this example; a different location might be better.) I'm not sure how this will interact with `killall`, but it's worth trying.
56,594,272
I found a code for text classification in tensorflow and when I try to run this code: <https://www.tensorflow.org/beta/tutorials/keras/feature_columns> I get an error. I used the dataset from here: <https://www.kaggle.com/kazanova/sentiment140> ``` Traceback (most recent call last): File "text_clas.py", line 35, in <module> train_ds = df_to_dataset(train, batch_size=batch_size) File "text_clas.py", line 27, in df_to_dataset labels = dataframe.pop('target') File "/home/yildiz/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 809, in pop result = self[item] File "/home/yildiz/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 2927, in __getitem__ indexer = self.columns.get_loc(key) File "/home/yildiz/.local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'target' ``` When I printed df.index.name I got NONE. So is the dataset not correct or am I doing something wrong? I changen the dataframe.head() to print(dataframe.head()) and got this output: ``` 0 ... @switchfoot http://twitpic.com/2y1zl - Awww, that's a bummer. You shoulda got David Carr of Third Day to do it. ;D 0 0 ... is upset that he can't update his Facebook by ... 1 0 ... @Kenichan I dived many times for the ball. Man... 2 0 ... my whole body feels itchy and like its on fire 3 0 ... @nationwideclass no, it's not behaving at all.... 4 0 ... @Kwesidei not the whole crew [5 rows x 6 columns] 1023999 train examples 256000 validation examples 320000 test examples ```
2019/06/14
[ "https://Stackoverflow.com/questions/56594272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You are saving or deleting a customer from the table, but the `dataSource` is using the data that you have already fetched from the database. It cannot get the updated data unless you manually do it. While saving a new customer, you'll have to make the `getUser()` request again ( or push the customer object in the `results` variable) and initialize the `dataSource` again. While deleting, again, either make the call again, or iterate through the result variable, find the customer that was deleted, remove it from the array, and reinitialize the `dataSource`.
Akash's approach is correct. In addition to his approach you should use [afterClosed()](https://material.angular.io/components/dialog/api#MatDialogRef) method to link MatDialog to current component and get notified when the dialog is closed. After the dialog is closed, just fetch users again. ```js ngOnInit() { this.fetchUsers(); } newCustomer(type) { this.service.initializeForm(); const dialogConfig = new MatDialogConfig(); //dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.width = "60%"; dialogConfig.id = type; this.dialog.open(CustomerComponent, dialogConfig).afterClosed().subscribe(() => this.fetchUsers()); } fetchUsers() { this.service.getUser().subscribe(results => { if (!results) { return; } console.log(results); this.dataSource = new MatTableDataSource(results); this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; }) } ``` Also if you share the code for deletion and `CustomerComponent` it would be easier to analyse any potential problems.
33,546,935
I have a list of lists, with integer values in each list, that represent dates over an 8 year period. ``` dates = [[2014, 11, 14], [2014, 11, 13], ....., [2013, 12, 01].....] ``` I need to compare these dates so that I can find an average cost per month, with other data stored in the file. So i need to figure out how to iterate through the dates and stop when the month changes. Each date has corresponding cost and volume values that I will need to find the average. So I was trying to find a way to make the dates in x.year, x.month, x.day format and do it that way but I'm new to python and very confused. How do I iterate through all of the dates for the 8 year period, but stopping and calculating the average of the data for each particular month and store that average for each month?? Thanks in advance, hope this makes sense.
2015/11/05
[ "https://Stackoverflow.com/questions/33546935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5522009/" ]
You can use a dictionary to preserve the year and month as the key and the relative days in a list as value, then you can do any progress on your items which are categorized by the year and month. ``` >>> dates = [['2014', '11', '14'], ['2014', '10', '13'], ['2014', '10', '01'], ['2014', '12', '01'], ['2013', '12', '01'], ['2013', '12', '09'], ['2013', '10', '01'], ['2013', '10', '05'], ['2013', '04', '01']] >>> my_dict = {} >>> >>> for y,m,d in dates: ... my_dict.setdefault((y,m),[]).append(d) ... >>> my_dict {('2013', '10'): ['01', '05'], ('2013', '12'): ['01', '09'], ('2014', '11'): ['14'], ('2014', '10'): ['13', '01'], ('2014', '12'): ['01'], ('2013', '04'): ['01']} >>> ``` You can use a nested list comprehension to convert the result to a nested list of relative month of datetime objects : ``` >>> [[datetime(int(y),int(m),int(d)) for d in days] for (y,m),days in my_dict.items()] [[datetime.datetime(2013, 10, 1, 0, 0), datetime.datetime(2013, 10, 5, 0, 0)], [datetime.datetime(2013, 12, 1, 0, 0), datetime.datetime(2013, 12, 9, 0, 0)], [datetime.datetime(2014, 11, 14, 0, 0)], [datetime.datetime(2014, 10, 13, 0, 0), datetime.datetime(2014, 10, 1, 0, 0)], [datetime.datetime(2014, 12, 1, 0, 0)], [datetime.datetime(2013, 4, 1, 0, 0)]] ```
If you want to iterate thought you dates array, and do an action every time the month changes you could use this method: ``` dates = [[2014, 11, 14], [2014, 11, 13], [2013, 12, 1]] old_m = "" for year, month, day in dates: if old_m != month: # calculate average here old_m = month ```
51,941,175
I am trying to read a txt file(kept in another location) in python, but getting error. -------------------------------------------------------------------------------------- > > FileNotFoundError > > in () > ----> 1 employeeFile=open("C:‪/Users/xxxxxxxx/Desktop/python/files/employee.txt","r") > 2 print(employeeFile.read()) > 3 employeeFile.close() > > > FileNotFoundError: [Errno 2] No such file or > directory:'C:\u202a/Users/xxxxxxxx/Desktop/python/files/employee.txt' > > > Code used: ``` employeeFile=open("C:‪/Users/xxxxxxxx/Desktop/python/files/employee.txt","r") print(employeeFile.read()) employeeFile.close() ``` I tried using frontslash(/) and backslash(). But getting the same error.Please let me know what is missing in code.
2018/08/21
[ "https://Stackoverflow.com/questions/51941175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6487702/" ]
I'm guessing you copy and pasted from a Windows property pane, switching backslashes to forward slashes manually. Problem is, the properties dialog shoves a Unicode LEFT-TO-RIGHT EMBEDDING character into the path so the display is consistent, even in locales with right-to-left languages (e.g. Arabic, Hebrew). You can read more about this on [Raymond Chen's blog, The Old New Thing](https://blogs.msdn.microsoft.com/oldnewthing/20150506-00/?p=44924/). The solution is to delete that invisible character from your path string. Selecting everything from the initial `"` to the first forward slash, deleting it, then retyping `"C:/`, should do the trick.
As your error message suggests, there's a weird character between the colon and the forward slash (`C:[some character]/`). Other than that the code is fine. ```py employeeFile = open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt", "r") ``` You can copy paste this code and use it.
19,623,386
Hi: I want to do a sound waves simulation that include wave propagation, absorbing and reflection in 3D space. I do some searches and I found [this question](https://stackoverflow.com/questions/4956331/wave-simulation-with-python) in stackoverflow but it talk about electromagnetic waves not sound waves. I know i can reimplement the **FDTD** method for sound waves but how about the sources and does it act like the electromagnetic waves ? Is there any resources to start with ? Thanks in advance.
2013/10/27
[ "https://Stackoverflow.com/questions/19623386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553460/" ]
Hope this can give you some inputs... As far as i know, in EM simulations obstacles (and thus terrain) are not considered at all. With sound you have to consider reflection, diffraction, etc there are different standards to calculate the noise originated from different sources (I'll list the europe ones, the one i know of): * traffic, NMPB (NMPB-Routes-96) is THE standard. All the noise calculations have to be done with that one (at least in my country). Results aren't very good. A "new" algorithm is SonRoad (i think it uses inverse ray-tracing)... from my tests it works great. * trains: Schall03 * industries, ISO 9613 * a list of all the used models in CadnaA (a professional software) so you can google them all: <http://www.datakustik.com/en/products/cadnaa/modeling-and-calculation/calculation-standards/> another pro software is SoundPlan, somewhere on the web there is a free "SoundPlan-ReferenceManual.pdf" 800-pages with the mathematical description of the implemented algorithms... i haven't had any luck with google today tough
An easy way to do this is use the SoundPlan software. Multiple sound propagation methods such as ISO9613-2, CONCAWE and Nord2000 are implemented. It has basic 3D visualization with sound pressure level contours.
46,309,161
I am having issues reading data from a bucket hosted by Google. I have a bucket containing ~1000 files I need to access, held at (for example) gs://my-bucket/data Using gsutil from the command line or other of Google's Python API clients I can access the data in the bucket, however importing these APIs is not supported by default on google-cloud-ml-engine. I need a way to access both the data and the names of the files, either with a default python library (i.e. os) or using tensorflow. I know tensorflow has this functionality built in somewhere, it has been hard for me to find Ideally I am looking for replacements for one command such as os.listdir() and another for open() ``` train_data = [read_training_data(filename) for filename in os.listdir('gs://my-bucket/data/')] ``` Where read\_training\_data uses a tensorflow reader object Thanks for any help! ( Also p.s. my data is binary )
2017/09/19
[ "https://Stackoverflow.com/questions/46309161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598909/" ]
If you just want to read data into memory, then [this answer](https://stackoverflow.com/a/42799952/1399222) has the details you need, namely, to use the [file\_io](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/lib/io/file_io.py) module. That said, you might want to consider using built-in reading mechanisms for TensorFlow as they can be more performant. Information on reading can be found [here](https://www.tensorflow.org/api_guides/python/reading_data). The latest and greatest (but not yet part of official "core" TensorFlow) is the Dataset API (more info [here](https://www.tensorflow.org/programmers_guide/datasets)). Some things to keep in mind: * Are you using a format TensorFlow can read? Can it be converted to that format? * Is the overhead of "feeding" high enough to affect training performance? * Is the training set too big to fit in memory? If the answer is yes to one or more of the questions, especially the latter two, consider using readers.
For what its worth. I also had problems reading files, in particular binary files from google cloud storage inside a datalab notebook. The first way I managed to do it was by copying files using gs-utils to my local filesystem and using tensorflow to read the files normally. This is demonstrated here after the file copy was done. Here is my setup cell ``` import math import shutil import numpy as np import pandas as pd import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) pd.options.display.max_rows = 10 pd.options.display.float_format = '{:.1f}'.format ``` Here is a cell for reading the file locally as a sanity check. ``` # this works for reading local file audio_binary_local = tf.read_file("100852.mp3") waveform = tf.contrib.ffmpeg.decode_audio(audio_binary_local, file_format='mp3', samples_per_second=44100, channel_count=2) # this will show that it has two channels of data with tf.Session() as sess: result = sess.run(waveform) print (result) ``` Here is reading the file from gs: directly as a binary file. ``` # this works for remote files in gs: gsfilename = 'gs://proj-getting-started/UrbanSound/data/air_conditioner/100852.mp3' # python 2 #audio_binary_remote = tf.gfile.Open(gsfilename).read() # python 3 audio_binary_remote = tf.gfile.Open(gsfilename, 'rb').read() waveform = tf.contrib.ffmpeg.decode_audio(audio_binary_remote, file_format='mp3', samples_per_second=44100, channel_count=2) # this will show that it has two channels of data with tf.Session() as sess: result = sess.run(waveform) print (result) ```
56,567,013
We are fairly new to Django. We we have an app and a model. We'd like to add an 'Category' object to our model. We did that, and then ran 'python manage.py makemigrations'. We then deploy our code to a server running the older code, and run 'python manage.py migrate'. This throws 2 pages of exceptions, finishing with 'django.db.utils.ProgrammingError: (1146, "Table 'reporting.contact\_category' doesn't exist")' This seems to be looking at our models.py. If we comment out Category from our model, and all references to it, the migration succeeds. I thought that the point of migrations is to make the database match what the model expects, but this seems to require that the model match the database before the migration. We clearly are doing something wrong, but what?
2019/06/12
[ "https://Stackoverflow.com/questions/56567013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11638068/" ]
I believe you skipped some migration in the server, so now you are missing some tables (I have been in that situation. Ensure **migrations** directories are on your **.gitignore**. You CAN NOT check in migrations files, you have to run `makemigrations` on the server). This can be solved by tracing back up to the point the database and models files match, but it is a risky process if it is your production database, so you should make a full backup before proceeding, and try the process on a different computer before. This would be my advice: 1. Delete migration files from the server. 2. Comment the models that rise the error. 3. Set the server's migration history to the point the database is, using `python manage.py makemigrations` and `python manage.py migrate --fake-initial` (this will update the migration files without actually attempting to modify the database). 4. Uncomment the models that raise the error. 5. Run `python manage.py makemigrations` and `python manage.py migrate`. If, after you comment the models that raise the exception, you get a different exception, you have to keep on commenting and attempting again. Once a migrations succeeds, you can uncomment all commented models and make an actual migration.
Remember to run `python manage.py makemigrations` if you made changes to the `models.py` then run `python manage.py makemigrations` Both commands **must** be run on the same server with the same database
10,654,707
I download python2.6.6 source form <http://www.python.org/getit/releases/2.6.6/> After that I run these commands ./configure make I tried to import zlib but it says no module named zlib. How can install zlib module for it After I tried installing python2.6.8 I got same error no zlib. While installing it I got below error Failed to find the necessary bits to build these modules: ``` _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop linuxaudiodev ossaudiodev readline sunaudiodev zlib ``` To find the necessary bits, look in setup.py in detect\_modules() for the module's name. Failed to build these modules: ``` crypt nis ```
2012/05/18
[ "https://Stackoverflow.com/questions/10654707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813102/" ]
I tried following which helped me with some of these modules. You have to edit setup.py. Find the following lines in setup.py: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', ] ``` **For 64 bit** Add `/usr/lib/x86_64-linux-gnu`: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu', ] ``` **For 32 bit** Add `/usr/lib/i386-linux-gnu`: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/i386-linux-gnu', ] ``` Note `x86_64-linux-gnu` & `i386-linux-gnu` might be located somewhere else in your system so path accordingly. Ater this you will be left with only following modules: ``` _bsddb bsddb185 dbm gdbm sunaudiodev ```
I wrote a note for myself addressing your problem, might be helpful: [`python installation`](http://cheater.nemoden.com/python-installation/). Do you really need `bsddb` and `sunaudiodev` modules? You might not want to since both are deprecated since python 2.6
10,654,707
I download python2.6.6 source form <http://www.python.org/getit/releases/2.6.6/> After that I run these commands ./configure make I tried to import zlib but it says no module named zlib. How can install zlib module for it After I tried installing python2.6.8 I got same error no zlib. While installing it I got below error Failed to find the necessary bits to build these modules: ``` _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop linuxaudiodev ossaudiodev readline sunaudiodev zlib ``` To find the necessary bits, look in setup.py in detect\_modules() for the module's name. Failed to build these modules: ``` crypt nis ```
2012/05/18
[ "https://Stackoverflow.com/questions/10654707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813102/" ]
I tried following which helped me with some of these modules. You have to edit setup.py. Find the following lines in setup.py: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', ] ``` **For 64 bit** Add `/usr/lib/x86_64-linux-gnu`: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu', ] ``` **For 32 bit** Add `/usr/lib/i386-linux-gnu`: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/i386-linux-gnu', ] ``` Note `x86_64-linux-gnu` & `i386-linux-gnu` might be located somewhere else in your system so path accordingly. Ater this you will be left with only following modules: ``` _bsddb bsddb185 dbm gdbm sunaudiodev ```
I solved the problem adding `LDFLAGS=-L/usr/lib/x86_64-linux-gnu` as `configure` parameter.
10,654,707
I download python2.6.6 source form <http://www.python.org/getit/releases/2.6.6/> After that I run these commands ./configure make I tried to import zlib but it says no module named zlib. How can install zlib module for it After I tried installing python2.6.8 I got same error no zlib. While installing it I got below error Failed to find the necessary bits to build these modules: ``` _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop linuxaudiodev ossaudiodev readline sunaudiodev zlib ``` To find the necessary bits, look in setup.py in detect\_modules() for the module's name. Failed to build these modules: ``` crypt nis ```
2012/05/18
[ "https://Stackoverflow.com/questions/10654707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813102/" ]
I tried following which helped me with some of these modules. You have to edit setup.py. Find the following lines in setup.py: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', ] ``` **For 64 bit** Add `/usr/lib/x86_64-linux-gnu`: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu', ] ``` **For 32 bit** Add `/usr/lib/i386-linux-gnu`: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/i386-linux-gnu', ] ``` Note `x86_64-linux-gnu` & `i386-linux-gnu` might be located somewhere else in your system so path accordingly. Ater this you will be left with only following modules: ``` _bsddb bsddb185 dbm gdbm sunaudiodev ```
I had this exact problem (exact python distribution as well) Dmity's answer almost worked... but after many hours searching I think I have found the issue (assuming you are using ubuntu 11.10 - 12.10) Ok, so for me at least the problem stemmed from the fact that Ubuntu disabled SSLv2, so the workaround is fairly involved. Basically you have to delve into the source code and remove all references to SSLv2 before you build it, in addition to adding library paths to your setup file. I followed this tutorial and now I have a working virtualenv with python-2.6.8: <http://ubuntuforums.org/showthread.php?t=1976837> (The patches are fairly easy to implement without using `patch`) Hope this helps clear up the issues. *PHEW*
10,654,707
I download python2.6.6 source form <http://www.python.org/getit/releases/2.6.6/> After that I run these commands ./configure make I tried to import zlib but it says no module named zlib. How can install zlib module for it After I tried installing python2.6.8 I got same error no zlib. While installing it I got below error Failed to find the necessary bits to build these modules: ``` _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop linuxaudiodev ossaudiodev readline sunaudiodev zlib ``` To find the necessary bits, look in setup.py in detect\_modules() for the module's name. Failed to build these modules: ``` crypt nis ```
2012/05/18
[ "https://Stackoverflow.com/questions/10654707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813102/" ]
I wrote a note for myself addressing your problem, might be helpful: [`python installation`](http://cheater.nemoden.com/python-installation/). Do you really need `bsddb` and `sunaudiodev` modules? You might not want to since both are deprecated since python 2.6
I had this exact problem (exact python distribution as well) Dmity's answer almost worked... but after many hours searching I think I have found the issue (assuming you are using ubuntu 11.10 - 12.10) Ok, so for me at least the problem stemmed from the fact that Ubuntu disabled SSLv2, so the workaround is fairly involved. Basically you have to delve into the source code and remove all references to SSLv2 before you build it, in addition to adding library paths to your setup file. I followed this tutorial and now I have a working virtualenv with python-2.6.8: <http://ubuntuforums.org/showthread.php?t=1976837> (The patches are fairly easy to implement without using `patch`) Hope this helps clear up the issues. *PHEW*
10,654,707
I download python2.6.6 source form <http://www.python.org/getit/releases/2.6.6/> After that I run these commands ./configure make I tried to import zlib but it says no module named zlib. How can install zlib module for it After I tried installing python2.6.8 I got same error no zlib. While installing it I got below error Failed to find the necessary bits to build these modules: ``` _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop linuxaudiodev ossaudiodev readline sunaudiodev zlib ``` To find the necessary bits, look in setup.py in detect\_modules() for the module's name. Failed to build these modules: ``` crypt nis ```
2012/05/18
[ "https://Stackoverflow.com/questions/10654707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813102/" ]
I solved the problem adding `LDFLAGS=-L/usr/lib/x86_64-linux-gnu` as `configure` parameter.
I had this exact problem (exact python distribution as well) Dmity's answer almost worked... but after many hours searching I think I have found the issue (assuming you are using ubuntu 11.10 - 12.10) Ok, so for me at least the problem stemmed from the fact that Ubuntu disabled SSLv2, so the workaround is fairly involved. Basically you have to delve into the source code and remove all references to SSLv2 before you build it, in addition to adding library paths to your setup file. I followed this tutorial and now I have a working virtualenv with python-2.6.8: <http://ubuntuforums.org/showthread.php?t=1976837> (The patches are fairly easy to implement without using `patch`) Hope this helps clear up the issues. *PHEW*
41,971,623
Is it possible to have a python script pause when you hold a button down and then start when you release that button? (I have the button connected to GPIO pins on my Raspberry Pi)
2017/02/01
[ "https://Stackoverflow.com/questions/41971623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5070269/" ]
**Yes.** The AWS account that is currently controlling your domain name with Route 53 must be used, but it can be pointed to anything on the Internet. Steps: * In the AWS account with the "other" EC2 instance, create an **Elastic IP Address** and assign it to the EC2 instance. This will ensure that its IP address does not change when the instance is stopped and started. * In your existing Route 53 configuration (in the original account), **create a Record Set** for the sub-domain (eg `images.example.com`) of type `A` and enter the Elastic IP Address as the *value*.
Once you have set the nameserver for your domain to point to Route53, you no longer need to control the subdomains from bigrock services. Just add them to your Route53 dashboard, and they'll be reflected live.
50,628,893
I am doing a final project in a python course and I have done a program using phantomjs that run like a background process in windows. Therefore, after creating my project, I used pyinstaller --noconsole --onefile to my file in order to hide his console but even tough I did it, I still get a console popup - phantomjs.exe [like this](https://i.stack.imgur.com/d9Zx8.png) Someone know how to remove the console without impairing the proper functioning of the program. Thanks alot, Omer **Note:** in my spec file in the exe option there is debug = False!
2018/05/31
[ "https://Stackoverflow.com/questions/50628893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9581412/" ]
No need to rename the .dat to .csv. Instead you can use a regex that matches two or more spaces as a column separator. Try use `sep` parameter: ``` pd.read_csv('http://users.stat.ufl.edu/~winner/data/clinton1.dat', header=None, sep='\s\s+', engine='python') ``` Output: ``` 0 1 2 3 4 5 6 7 8 9 10 0 Autauga, AL 30.92 31.7 57623 15768 15.2 10.74 51.41 60.4 2.36 457 1 Baldwin, AL 26.24 35.5 84935 16954 13.6 9.73 51.34 66.5 5.40 282 2 Barbour, AL 46.36 32.8 83656 15532 25.0 8.82 53.03 28.8 7.02 47 3 Blount, AL 32.92 34.5 61249 14820 15.0 9.67 51.15 62.4 2.36 185 4 Bullock, AL 67.67 31.7 75725 11120 33.0 7.08 50.76 17.6 2.91 141 ``` If you want your state as a seperate column you can use this sep='\s\s+|,' which means seperate columns on two spaces or more OR a comma. ``` pd.read_csv('http://users.stat.ufl.edu/~winner/data/clinton1.dat', header=None, sep='\s\s+|,', engine='python') ``` Output: ``` 0 1 2 3 4 5 6 7 8 9 10 11 0 Autauga AL 30.92 31.7 57623 15768.0 15.2 10.74 51.41 60.4 2.36 457.0 1 Baldwin AL 26.24 35.5 84935 16954.0 13.6 9.73 51.34 66.5 5.40 282.0 2 Barbour AL 46.36 32.8 83656 15532.0 25.0 8.82 53.03 28.8 7.02 47.0 3 Blount AL 32.92 34.5 61249 14820.0 15.0 9.67 51.15 62.4 2.36 185.0 4 Bullock AL 67.67 31.7 75725 11120.0 33.0 7.08 50.76 17.6 2.91 141.0 ```
You can use a regular expression as a separator. In your specific case, all the delimiters are more than one space whereas the spaces in the names are just single spaces. ``` import pandas as pd clinton = pd.read_csv("clinton1.csv", sep='\s{2,}', header=None, engine='python') ```
20,269,507
I'm a novice in python and also in py.test. I'm searching a way to run multiple tests on multiple items and cannot find it. I'm sure it's quite simple when you know how to do it. I have simplified what I'm trying to do to make it simple to understand. If I have a Test class who defines a serie of tests like this one : ``` class SeriesOfTests: def test_greater_than_30(self, itemNo): assert (itemNo > 30), "not greather than 30" def test_lesser_than_30(self, itemNo): assert (itemNo < 30), "not lesser thant 30" def test_modulo_2(self, itemNo): assert (itemNo % 2) == 0, "not divisible by 2" ``` I want to execute this SeriesOfTest on each item obtained from a function like : ``` def getItemNo(): return [0,11,33] ``` The result i'm trying to obtain is something like : ``` RESULT : Test "itemNo = 0" - test_greater_than_30 = failed - test_lesser_than_30 = success - test_modulo_2 = success Test "itemNo = 11" - test_greater_than_30 = failed - test_lesser_than_30 = success - test_modulo_2 = failed Test "itemNo = 33" - test_greater_than_30 = success - test_lesser_than_30 = failed - test_modulo_2 = failed ``` How can I do this with py.test? Than you guys (and girls also) André
2013/11/28
[ "https://Stackoverflow.com/questions/20269507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269921/" ]
Add the sorting clause to the most outer query
For paging with a "window", you can do something like this: ``` select e.* from ( select e.* , row_number() over (order by uur_id) ive$idx$ from bubs_uren_v e where ( uur_id = :w1 ) ) e where ive$idx$ between (:start_index + 1) and (:start_index + :max_row_count) ``` We use this code in our project management suite which handles very large volumes of data. Don't ask me how Oracle did it, but it consistently fast. Remember to only include the columns you need, saves processing, memory and maybe even PL/SQL function calls.