Key combinations with Python from focused window only?

Is there a clean and easy way to capture key combinations with Python only when the script being run is in focus (e.g. the Python intepreter/terminal or IDE window, no global capture)?

I’ve been trying the keyboard, pynput, and pygame.key for over two months, but none of these packages worked for me and some were an incredible mess to code with IMHO due to either a lack of documentation and bugs (keyboard) or too much overhead and unwieldy, convoluted classes/methods (pygame). Assume that you need to bind 50 different hotkeys – you don’t want to define a function with 10-20 lines of code for each key binding if e.g. a simple dictionary does the job. You also don’t want to be challenged to invent some god-level regex pattern for find & replace in order to write those 50 different functions if e.g. a simple dictionary does the job. You get the point.

It’s stunning that there doesn’t seem to exist a single Python package that offers a simple, concise solution for such a banal task that virtually any program that you are using right now is getting done. Try it: Alt+F4 will close your browser, but not some other applications that you might be running in the background.

I’m thinking about something along the lines of

import keyboard_package as kb   hotkeys = {'ctrl+c':some_callback, 'ctrl+v':another_callback}    # BAM!  kb.bind_hotkeys(hotkeys)    # BAM! kb.listener_start(focus=True)    # BAM!  do_something()    # Your game main loop  kb.listener_stop()    # BAM! kb.unbind_hotkeys()    # Done! You may now go home to wife and kids. 

If it’s not possible to limit the capture on one window, I’m also fine with having the callback pause the listener, e.g. while a certain very long loop is running and you need to write an e-mail in the meantime without accidentally triggering a core meltdown by doing Ctrl+C and Ctrl+V in Outlook.

Wish list:

  • Capture hotkeys only in focused window
  • Simple, pythonic – I’m not your beta tester
  • Straight/"no BS" package that gets the job done without forcing the user do a degree on ancient Egyptian philosophy

Python Opengl Procedural Terrain Rendering

I am rendering procedural terrain in Python using OpenGL. Once generated, data for each terrain tile is stored in lists. However currently I am only getting around 25fps despite rendering only around 4000 polygons (2 per terrain tile). The model x and z coordinates are stored in the position matrix contained in the terrain_quad_location list where as the heights are stored in the vertices of each terrain tile quad in the terrain_VAO list.

It seems like this low fps is due to inefficiency when render large numbers of models not polygons as when I render models with high polygon counts in addition to this my fps is minimally affected. For reference I am using VAOs, VBOs and EBOs and built upon these tutorials.

Is there a way I can make the code more efficient?

Before Runtime:

count=0 for i in range(terrain_quad_number):      terrain_VAO[count] = glGenVertexArrays(1)     glBindVertexArray(terrain_VAO[count])      terrain_VBO[count] = glGenBuffers(1)     glBindBuffer(GL_ARRAY_BUFFER, terrain_VBO[count])     glBufferData(GL_ARRAY_BUFFER, terrain_quad_vertices[count].nbytes, terrain_quad_vertices[count], GL_STATIC_DRAW)       terrain_EBO[count] = glGenBuffers(1)     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, terrain_EBO[count])     glBufferData(GL_ELEMENT_ARRAY_BUFFER, terrain_quad_vertices[count].nbytes, quad_indices, GL_STATIC_DRAW)      glEnableVertexAttribArray(0)     glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, terrain_quad_vertices[count].itemsize * 5, ctypes.c_void_p(0))      glEnableVertexAttribArray(1)     glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, terrain_quad_vertices[count].itemsize * 5, ctypes.c_void_p(12)) 


moo=0     for i in range (len(rendered_terrain_number)):         model = terrain_quad_location[rendered_terrain_number[moo]]          glBindVertexArray(terrain_VAO[rendered_terrain_number[moo]])         glBindTexture(GL_TEXTURE_2D, ground_textures[int(terrain_quad_sub_biome[int(rendered_terrain_number[moo])][0][0])-1])         glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)         glDrawElements(GL_TRIANGLES, len(quad_indices), GL_UNSIGNED_INT, None)         moo=moo+1 

I understand that I may need to lower the number of draw calls which may be done my merging terrain tile models, but how do I do this given I want each tile to have its own texture?

Apparently Minecraft does this by merging every block in a chunk into one VBO but how is this done given every block has a different texture? Instancing would not work either.

Here is a video of the program.

Simplifying equations in python using wolframclient

I’ve this mathematical expression and want it to Simplify it in python using wolframclient wrapper.

1/700*((-1316*w + b - 0.0)^2 + (-1116*w + b - 1.0)^2) 

I’ve tried this method:

In[1]: mathematica_session.evaluate(wlexpr('1/700*((-1316*w+b-0.0)^2+(-1116*w+b-1.0)^2)')) Out[1]: Times[Rational[1, 700], Plus[Power[Plus[0.0, Global`b, Times[-1316, Global`w]], 2], Power[Plus[-1.0, Global`b, Times[-1116, Global`w]], 2]]] 

And then this method:

In[2]: mathematica_session.evaluate(wl.Simplify('1/700*((-1316*w+b-0.0)^2+(-1116*w+b-1.0)^2)')) Out[2]: '1/700*((-1316*w+b-0.0)^2+(-1116*w+b-1.0)^2)' 

And finally this is the result when I tried this on directly Mathematica:

In[1]: Simplify[1/700*((-1316*w + b - 0.0)^2 + (-1116*w + b - 1.0)^2)] Out[1]: 0.00285714 (0.5 + b^2 + b (-1. - 2432. w) + 1116. w + 1.48866*10^6 w^2) 

And this is the result I want in python. So what I’m missing or doing wrong in python?

Exporting packages containing “Python Code” cells

I created a notebook with Python code cells (evaluated using External Evaluate) as can be created by typing > at the beginning of a cell. (And choosing Python for the external evaluator). I then marked these cells as initialization cells. However, I find that I can’t reliably create packages (I create packages autoamtically using the answer in The python cells do become python cells in the package but they get corrupted. It wrongly breaks cells up at any double new line (this can at least be avoided) but also randomly misses text. A cell with

import scipy.optimize import numpy as np def stuff(): ... 

just becomes import scipy.optimize import numpy as def stuff(): … and thus gives a syntax error since np is missing. The original notebook file works perfectly and has no such errors.

Is there any reliable way to export? Does everyone have these issues?

Version: "12.1.1 for Linux x86 (64-bit) (June 19, 2020)"

It gets even weirder. There seems to be some randomness to it. Now I managed to (without making changes) export it correctly to a package that does not produce any errors when run from within MMA (i.e. when opening it and running all the cells.) However, when calling it from another notebook using Get I still get a syntax error. I checked and see no syntax error in the cell where it should supposedly be.

It might be related to having set up a custom virtual environment using this answer. However, everything is working perfectly in the notebook. The issues only arise when converting to a package.

Performance of select from a 3d list – Mathematica slower than Python

I am creating a random 3d data set in Matematica 12.1. Then I am selecting all points that are in a certain range of one axis.

The same I am doing in Python (same computer, Python 3.8.5, numpy 1.19.2)

RESULT: It seems that Python is able to select much faster (1.7 sec) than Mathematica (5.2 sec). What is the reason for that? For selection in Mathematica I used the fastest solution, which is by Carl Woll (see here at bottom).

SeedRandom[1]; coordinates = RandomReal[10, {100000000, 3}];  selectedCoordinates =     Pick[coordinates,      Unitize@Clip[coordinates[[All, 1]], {6, 7}, {0, 0}],      1]; // AbsoluteTiming  {5.16326, Null}  Dimensions[coordinates]  {100000000, 3}  Dimensions[selectedCoordinates]  {10003201, 3} 


import time import numpy as np   np.random.seed(1) coordinates = np.random.random_sample((100000000,3))*10  start = time.time() selectedCoordinates = coordinates[(coordinates[:,0] > 6) & (coordinates[:,0] < 7)] end = time.time()  print(end-start)  print(coordinates.shape)  print(selectedCoordinates.shape)  1.6979997158050537  (100000000, 3)  (9997954, 3) 

Why is PHP still mostly used to make browser games rather than Python or Java? [closed]

I am a Computer Science student and I have been playing to Travian for years.Travian is a browser based MMOG where you have to build your village and compete for resources. There is no animation, there is 3 main views which is the map, your village and your fields.

I was looking at some Travian clones on GitHub and I found 3 clones, all of them using PHP. Travian has itself build using PHP.

I am wondering if PHP is better in some way than Python for example for building this kind of games? And if so, why would be the reason?

How does switching from WordPress to custom-made Python site affect SEO?

I want to switch from WordPress to a site I want to build with Python and the JustPy web framework(Python wrapper built around Quasar).

I plan to use things like Steppers and other tabbed features that do not immediately show the content when the page loads.

My question (fear) does that tabbed content affect SEO in some way?

Also, I know Python well, but I have no knowledge of how to optimize HTML for SEO. Are there other negative outcomes of switching from WordPress to a custom-made Python site SEO-wise?

Problem Lotka Volterra Model – Modelling & Plotting in Python

I urgently need your help. Currently I’m conducting a research in regards of the revenue calculation and the dynamics within revenue calculation for my masters. I thought of revenue/profit margin as of a dynamical system – Lotka Volterra differential equations. I thought of a contribution margin calculation as within this simple formula:

In consequence my idea was the following, but I receive an error:
enter image description here

enter image description here

enter image description here

  • Can anyone help me?
  • Do you think it’s a bad idea to use Lotka Volterra equations for this nonlinear purpose of Sales/Cost/Margin Simulation?
  • How would you model it and why? Am I missing equations or does the simple system already fit the requirements?
  • How do I generate a valid plot out of these results (Phase Portrait etc.)?

Run Python Functions in frontend [closed]

I know front-end developement with React.js. I want to make a basic web-app where I use some python functions (for example on onClick of buttons etc). These functions would mainly revolve around machine learning (but wont be too complex).

Is there any way to run python functions from React.js apart from ajax queries?

If not, which Python framework should I use to do web development in Python such that I can directly run Python functions as well? I have come across names like Django, Tinkter and Flask but couldn’t figure out what exactly would suit my requirement.

How do I approach towards an abstract production rule interpreter with this situation of converting XML to python or java class?

If I am asking in the wrong place, please forgive and direct me to a more suitable one

So I have a XML like this

<range>    unconstrained    <span>       <rttype>          String </range>  <range>    x type    <span>       <rttype>          int       <assert>          $   > 0 </range>  <range>    Simple class reference    <span>       <rttype>          SimpleClass </range>  <range>    Simple class set    <span>       <rttype>          ArrayList<SimpleClass> </range>  <class>   Simple class     <attribute>      x         <range>            x type   </attribute>    <attribute>      state   </attribute>    <action>      initializer      <guarantees>         x has been set to zero      </guarantees>      <pimaction>         .@a x @ = 0      </pimaction>   </action>    <action>      update x      <parameter>         new x         x type      <guarantees>         x has been set to new x      </guarantees>      <pimaction>         .@a x @ = @i new x @      </pimaction>   </action>    <state>      Exists   </state>    <state>      Doesn't exist   </state>    <event>      <<new>>   </event>    <event>      <<destroy>>   </event>    <event>      update   </event>    <transition>      Doesn't exist      <<new>>      Exists      <transitionaction>         initializer   </transition>    <transition>      Exists      <<destroy>>      Doesn't exist   </transition>    <transition>      Exists      update      Exists      <transitionaction>         update x   </transition> 

I have a Java compiler (let’s call this ToJavaCompiler) that will compile this into a Java class

And another Java compiler (let’s call this ToPythonCompiler) that will also compile this into a Python class.

class SimpleClass:      # State Enum Declaration     # see MMClass.ruleStateEnumDeclaration for implementation      SimpleClass_states = Enum("SimpleClass_states", "EXISTS DOESNTEXIST")      # Attribute instance variables     # see MMClass.ruleAttributeInstVarList for implementation      _x: int     _state: SimpleClass_states      # Class level attribute     # All class members accessor      SimpleClassSet: ClassVar[List[SimpleClass]] = []       # Constructor     # See MMClass.ruleConstructorOperation      # See constructEvent.ruleConstructorOperation     def __init__(self):         # requires         #    none         # guarantees         #    --> x has been set to zero and state == Exists         self._initializer()         self._state = SimpleClass.SimpleClass_states.EXISTS         SimpleClass.SimpleClassSet.append(self)      # Attribute getters      @property     def x(self) -> int:         # requires         #   none         # guarantees         #   returns the x         return self._x      @property     def state(self) -> SimpleClass_states:         # requires         #   none         # guarantees         #   returns the state         return self._state       # Pushed events      def destroy(self) -> None:         # requires         #    none         # guarantees         #   state was Exists --> state == Doesn't exist         if self._state == SimpleClass.SimpleClass_states.EXISTS:             self._state = SimpleClass.SimpleClass_states.DOESNTEXIST             SimpleClass.SimpleClassSet.remove(self)      def update(self, new_x: int) -> None:         # requires         #    none         # guarantees         #   state was Exists --> x has been set to new x         if self._state == SimpleClass.SimpleClass_states.EXISTS:             self._update_x(new_x)      # Private transition actions      def _initializer(self):         # requires         #   none         # guarantees         #   x has been set to zero         self._x = 0      def _update_x(self, new_x: int):         # requires         #   none         # guarantees         #   x has been set to new x         self._x = new_x 

THe thing is my production rule need access to instance variable data from the model object they are compiling.

For example to generate the instance variables declarations i need a production rule that’s written in Java code like this which require access to the underlying model itself at Context.model()

public void ruleAttributeInstVarList() {     // description     // this rule emits the set of (private) instance variable declarations, if any     //     // Class.#ATTRIBUTE_INST_VAR_LIST -->     // foreach anAttribute in class     // anAttribute.#DEFINE_INST_VAR     //     // requires     // none     // guarantees     // all attributes of this class have been declared as instance variable of the     // PIM Overlay run-time type     if (Context.model().isVerbose()) {         Context.codeOutput().indent();         Context.codeOutput().println("# Attribute instance variables");         Context.codeOutput().println("# see MMClass.ruleAttributeInstVarList for implementation");                  Context.codeOutput().println("");         if (!attributeSet.isEmpty()) {             for (Attribute anAttribute : attributeSet) {                 anAttribute.ruleDefineInstVarAsPrivate();             }         } else {             if (Context.model().isVerbose()) {                 Context.codeOutput().indent();                 Context.codeOutput().println("# none");             }         }         Context.codeOutput().indentLess();     } else {         for (Attribute anAttribute : attributeSet) {             anAttribute.ruleDefineInstVarAsPrivate();         }     }     Context.codeOutput().println("");     Context.codeOutput().println(""); } 

I wonder if there’s an easier way to add target languages or frameworks without creating separate codebases per target language.

For e.g. I now have a ToJavaCompiler and a ToPythonCompiler two separate codebases

So I am here asking if there’s a way I can create an abstract production rule interpreter that suits my needs. My aim is to ultimately produce model classes in the target language or framework (such as Django or Rails) with a single codebase that allows extensions for different target languages/frameworks

I am okay to move away from Java if there’s a better language that suits what I am trying to do.