for the code below, execl destroy the script but not restart. If the method is out of the class is working. What I am doing wrong.?
import os
import sys
from tkinter import *
class parent():
def __init__(self,root):
self.root=root
def show_root(self):
self.root=Tk()
a=Button(self.root,text='restart',command=self.restart)
a.grid()
def restart(self):
sys.stdout.flush()
os.execl(sys.executable, 'python', __file__, *sys.argv[1:])
return
if __name__=='__main__':
gr=parent(None)
gr.show_root()
Related
I can't make the button work, it works as it should on the windows, why doesn't it work in ubuntu?
import tkinter as tk
from tkinter import ttk
import sys
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.attributes("-alpha", 1)
self.attributes("-topmost", True)
self.overrideredirect(True)
self.resizable(False, False)
self.title("CPU-RAM usage monitor bar")
self.set_ui()
def set_ui(self):
exit_but = tk.Button(self, text="Exit", command=lambda: self.app_exit)
exit_but.pack(fill=tk.X)
def app_exit(self):
self.destroy()
sys.exit()
root = Application()
root.mainloop()
'I want to build a module containing class AnimationCanvas inside (anim.py). And I want to call this module in a separate main.py file where the data (a variable) is changing (potentially with GUI). The instance animatedAxes would automatically update its plot by taking data from the variables in main.py file, while the main.py code is running (a sort of parallel processes).'
'Problem: the instance of class AnimationCanvas from the module does not see the variables of the class main in the main.py file.
I know how to do it if the class AnimationCanvas and the class main are in the same file. However I want to have an animation module (separate file), which can be used anywhere, just by importing it and writing a couple of lines.'
'I can call __init__ function of the class AnimationCanvas and pass the variables into it, but then it is a one-time effect, and if the variables change in class main, then animatedAxes instance will not see this change.'
'Single file which works (single.py):'
import matplotlib.pyplot as plt
from matplotlib.animation import TimedAnimation
from matplotlib.lines import Line2D
import numpy as np
class main():
def __init__(self):
self.size=800
main.data=np.random.rand(self.size)
# initialize animated graph routine
self.animatedAxes = AnimationCanvas()
# run random data array
for ii in range(20):
main.data=np.random.rand(self.size)
plt.pause(0.1)
class AnimationCanvas(TimedAnimation):
def __init__(self):
# initialize random data array
self.data = np.random.rand(5)
# Create animation axis and figure
self.fig = plt.figure(1, figsize=(5, 5))
self.ax = plt.axes([0.1, 0.1, 0.8, 0.8])
self.line1 = Line2D([], [], color='blue')
self.ax.add_line(self.line1)
# start animation with interval of 10 milliseconds
TimedAnimation.__init__(self, self.fig, interval=10, blit=True)
def new_frame_seq(self):
return iter(range(5*5))
def _step(self, *args):
try:
TimedAnimation._step(self, *args)
except Exception as e:
TimedAnimation._stop(self)
pass
def _draw_frame(self, framedata):
# update self.data
self.data=main.data
# update plot with self.data
self.line1.set_data(np.arange(len(self.data)),self.data)
if __name__ == '__main__':
main()
'Two files which do not work:'
'main.py:'
import matplotlib.pyplot as plt
import numpy as np
from anim import AnimationCanvas
class main():
def __init__(self):
self.size=800
self.data=np.random.rand(self.size)
# initialize animated graph routine
self.animatedAxes = AnimationCanvas()
# run random data array
for ii in range(20):
print(ii)
self.data=np.random.rand(self.size)
plt.pause(0.1)
if __name__ == '__main__':
main()
'anim.py:'
import matplotlib.pyplot as plt
from matplotlib.animation import TimedAnimation
from matplotlib.lines import Line2D
import numpy as np
class AnimationCanvas(TimedAnimation):
def __init__(self):
# initialize random data array
self.data = np.random.rand(5)
# Create animation axis and figure
self.fig = plt.figure(1, figsize=(5, 5))
self.ax = plt.axes([0.1, 0.1, 0.8, 0.8])
self.line1 = Line2D([], [], color='blue')
self.ax.add_line(self.line1)
# start animation with interval of 10 milliseconds
TimedAnimation.__init__(self, self.fig, interval=10, blit=True)
def new_frame_seq(self):
return iter(range(5*5))
def _step(self, *args):
try:
TimedAnimation._step(self, *args)
except Exception as e:
TimedAnimation._stop(self)
pass
def _draw_frame(self, framedata):
'update self.data:'
'????????????????'
'update plot with self.data'
self.line1.set_data(np.arange(len(self.data)),self.data)
'I tried to use super(AnimationCanvas,self).__init__() but it does not work.'
'In my understanding I need a direct connection between self of the class main and self of class AnimationCanvas. Any suggestions are appreciated. Thanks.'
I'm trying to write a custom Marshaller for a very simple object, but it seems the scala runtime is not able to find it.
Following the spray template, I've defined the route as follows:
package com.example
import akka.actor.Actor
import spray.routing._
import spray.http._
import MediaTypes._
import com.example.dto.RecipeEntry
import com.example.dto.RecipeEntryJson._
trait RecipeManager extends HttpService {
val myRoute =
path("recipe") {
post {
decompressRequest() {
entity(as[RecipeEntry]) { recipe =>
complete(s"picture is $recipe.image")
}
}
}
}
}
and I've tried to define the Marshaller[RecipeEntry] as such:
package com.example.dto
import spray.json.DefaultJsonProtocol
import spray.httpx.SprayJsonSupport._
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._
import spray.http._
case class RecipeEntry(originSite: String, image: String)
object RecipeEntryJson extends DefaultJsonProtocol {
implicit val jsonMarshaller: Marshaller[RecipeEntry] = jsonFormat2(RecipeEntry.apply)
}
but I keep getting the following error:
RecipeManager.scala:18: could not find implicit value for parameter um: spray.httpx.unmarshalling.FromRequestUnmarshaller[com.example.dto.RecipeEntry]
[error] entity(as[RecipeEntry]) { recipe =>
In fact, I'm running into the same problem as this link, however adding import com.example.dto.RecipeEntryJson._ did not help
I must be missing some small detail (probably quite a few, as I'm very new to scala and spray), but I've tried a number of things but to no avail. Any help is very much appreciated.
i am using cache headers like no-cache and no-store, i don´t know to do application level caching (maybe i could need some documentation here)
i print in console the data result when i call the method in mongodb, but it only works once after i run my app(that ocur in get service), the second time my app doesn´t print nothing, that is, it doesn't call the method.... that ocur when i try get a list of users the second time... for example, when i post something like insert new a user. i need to see the changes in the db in the frontend, my app seems get data from cache and it does´nt call the method to get the users again
the code I use in my spray scala service is
`package api
import spray.routing.Directives
import akka.actor.ActorRef
import spray.http.MediaTypes._
import core.UserRegister
import core.User
import scala.concurrent.ExecutionContext
import core.{User, LoginActor}
import akka.util.Timeout
import LoginActor._
import spray.http._
import scala.Some
import spray.json.JsonFormat
import spray.json.RootJsonFormat
import spray.json.JsArray
import spray.json.CollectionFormats
import spray.json._
import DefaultJsonProtocol._
import scala.util.parsing.json.JSONArray
import scala.util.parsing.json._
import data.UserDao
import core.UserListActor
import spray.routing.Route
import core.CoreActors
import spray.routing.HttpService
import core.Core
import akka.actor.{Props, ActorRefFactory, ActorSystem}
import akka.actor.ActorContext
import spray.routing.HttpServiceActor
import spray.http.HttpHeaders.RawHeader
import scala.concurrent.duration.Duration
import spray.routing.authentication.BasicAuth
import spray.routing.directives.CachingDirectives._
import spray.httpx.encoding._
import spray.caching._
import spray.caching.{LruCache, Cache}
import spray.caching.Cache
import web.StaticResources
import scala.concurrent.Future
class ListarUsuarioService(listaUsuario: ActorRef)(implicit executionContext: ExecutionContext)
extends Directives with DefaultJsonFormats with SprayCORSsupport with CORSSupport{
import akka.pattern.ask
import scala.concurrent.duration._
implicit val userFormat = jsonFormat2(User)
implicit val registerFormat = jsonFormat1(Register)
implicit val userRegisterFormat = jsonFormat5(UserRegister)
implicit val registeredFormat = jsonObjectFormat[Registered.type]
implicit val notRegisteredFormat = jsonObjectFormat[NotRegistered.type]
implicit val system = ActorSystem()
import system.dispatcher
lazy val simpleRouteCache = routeCache()
lazy val simpleCache = routeCache(maxCapacity = 5000, timeToIdle = 0.001 hour)
//lazy val cache = LruCache()
def routeCache(maxCapacity: Int = 2000, initialCapacity: Int = 100, timeToLive: Duration = 5 seconds,
timeToIdle: Duration = Duration.Inf): Cache[RouteResponse] =
LruCache(maxCapacity, initialCapacity, timeToLive, timeToIdle)
// and a Cache for its result type
val cache2: Cache[Double] = LruCache()
val listaUsuariosroute:Route =
cache(routeCache()){
cors{ addCORSDefaultSupport(){
path("usuario") {
get {
respondWithMediaType(`application/json`) {
_.complete {
//Elemento de la lista
//listaUsuarios(1)
UserListActor.listaUsuarios.toJson.convertTo[JsArray].prettyPrint }
}
}
}
}
}
}//cors
}
`
I am using Cors and cache headers like no-store, public and no-cache, but it doesn´t works, even i clear my cache browser but it neither works
package models
import play.api._
import play.api.mvc._
import anorm._
import anorm.SqlParser._
import play.api.db.DB
import play.api.Play.current
import scala.language.postfixOps
case class User(name:String)
object User {
def insert(name:String) : Boolean={
DB.withConnection { implicit connection =>
val result:Boolean= SQL("insert into user(name,username,password) VALUES('"+name+"','"+name+"','"+name+"')").execute()
return result
}
}
}
"In above program an exception is occured named "[Exception: DB plugin is not registered.]". how to fix it"
In my case the application.conf had invalid connect string to database (after deployment on a different environment). I have changed the db.default.url value in the application.conf.