julia import package stored as variable - julia

is there a way to programmatically import modules, something like?
deps = [ "HypothesisTests", "Plots", "MLDataUtils", "ArgParse",
"GraphViz", "Cairo", "CSV", "JLD", "FreqTables",
"MLBase", "Compat"]
for dep in deps
Pkg.add(dep)
try
import dep # <-- how?
catch
try
Pkg.build(dep)
catch
nothing
end
end
end
Pkg.update()
I'd appreciate any better approaches to what I am trying to do, i.e. deal with failed import/using.

This is one way that I found to address this:
s = Symbol("CSV")
#eval(import $s)

Related

SQLAlchemy and SQLite3: Error if database file does not exist

I would like SQLAlchemy to return an error if the underlying SQLite3 database file does not exist.
I've looked around, and tried:
#!/usr/bin/env python3
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.orm import Session, declarative_base
Base = declarative_base()
class SomeTable(Base):
id = Column(Integer)
DB_SPECIFIER = 'sqlite+pysqlite:////tmp/non-exist.db?mode=rw'
engine = create_engine(DB_SPECIFIER, echo=False, future=True, connect_args={'uri': True})
session = Session(engine)
x = session.query(SomeTable)
I'd like the create_engine call to fail if /tmp/non-exist.db does not exist. I thought using this answer would work, but it did not.
Looks like it's in the docs, though fairly hidden:
https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#uri-connections
So you'd do:
DB_SPECIFIER = 'sqlite:///file:/tmp/non-exist.db?mode=ro&uri=true'
engine = create_engine(DB_SPECIFIER, echo=False, future=True)
It picks this apart and sends arguments to the connection, the rest through to the URI. (You can also add some lock disabling and such there, if that helps, since it's read only).

How to verify record does not exist in database prior to import?

I have an importer function that works. The problem is if the record is already in the table it creates a duplicate. There is only one field in the table called mtype. So the CSV file looks like
mtype
HP360
Dell
The import that is working:
require 'csv'
class Modeltype < ApplicationRecord
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Modeltype.create! row.to_hash
end
end
end
I tried to search to see if the record was in the database with:
require 'csv'
class Modeltype < ApplicationRecord
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
tag = row.to_hash
if Modeltype.find_by_mtype(tag) == nil
Modeltype.create! row.to_hash
end
end
end
end
When I run it like this it returns a "Can't cast hash error."
In the Controller I have:
def import
Modeltype.import(params[:file])
redirect_to modeltypes_url, notice: "Model Types imported."
end
How can I search to see if the record already exists? Then create it if it does not exist and skip that row if it does exist? I also tried using the flag validates_presence_of, but that also did not work.
I seem to recall using a validates_uniquness_of on a different project before, is this something that might work?
In your modeltype.rb file add the line outside of your def but in the class Modeltype validates_uniqueness_of :mtype. This will allow the import to work if the item is not in the database. You will need to still build in a catch to skip if the record exists during import. Otherwise you will get an error. So your original def with that line added, like so:
require 'csv'
class Modeltype < ApplicationRecord
validates_uniqueness_of :mtype
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Modeltype.create! row.to_hash
end
end
end

Filtering tab completion in input task implementation

I'm currently implementing a SBT plugin for Gatling.
One of its features will be to open the last generated report in a new browser tab from SBT.
As each run can have a different "simulation ID" (basically a simple string), I'd like to offer tab completion on simulation ids.
An example :
Running the Gatling SBT plugin will produce several folders (named from simulationId + date of report generaation) in target/gatling, for example mysim-20140204234534, myothersim-20140203124534 and yetanothersim-20140204234534.
Let's call the task lastReport.
If someone start typing lastReport my, I'd like to filter out tab-completion to only suggest mysim and myothersim.
Getting the simulation ID is a breeze, but how can help the parser and filter out suggestions so that it only suggest an existing simulation ID ?
To sum up, I'd like to do what testOnly do, in a way : I only want to suggest things that make sense in my context.
Thanks in advance for your answers,
Pierre
Edit : As I got a bit stuck after my latest tries, here is the code of my inputTask, in it's current state :
package io.gatling.sbt
import sbt._
import sbt.complete.{ DefaultParsers, Parser }
import io.gatling.sbt.Utils._
object GatlingTasks {
val lastReport = inputKey[Unit]("Open last report in browser")
val allSimulationIds = taskKey[Set[String]]("List of simulation ids found in reports folder")
val allReports = taskKey[List[Report]]("List of all reports by simulation id and timestamp")
def findAllReports(reportsFolder: File): List[Report] = {
val allDirectories = (reportsFolder ** DirectoryFilter.&&(new PatternFilter(reportFolderRegex.pattern))).get
allDirectories.map(file => (file, reportFolderRegex.findFirstMatchIn(file.getPath).get)).map {
case (file, regexMatch) => Report(file, regexMatch.group(1), regexMatch.group(2))
}.toList
}
def findAllSimulationIds(allReports: Seq[Report]): Set[String] = allReports.map(_.simulationId).distinct.toSet
def openLastReport(allReports: List[Report], allSimulationIds: Set[String]): Unit = {
def simulationIdParser(allSimulationIds: Set[String]): Parser[Option[String]] =
DefaultParsers.ID.examples(allSimulationIds, check = true).?
def filterReportsIfSimulationIdSelected(allReports: List[Report], simulationId: Option[String]): List[Report] =
simulationId match {
case Some(id) => allReports.filter(_.simulationId == id)
case None => allReports
}
Def.inputTaskDyn {
val selectedSimulationId = simulationIdParser(allSimulationIds).parsed
val filteredReports = filterReportsIfSimulationIdSelected(allReports, selectedSimulationId)
val reportsSortedByDate = filteredReports.sorted.map(_.path)
Def.task(reportsSortedByDate.headOption.foreach(file => openInBrowser((file / "index.html").toURI)))
}
}
}
Of course, openReport is called using the results of allReports and allSimulationIds tasks.
I think I'm close to a functioning input task but I'm still missing something...
Def.inputTaskDyn returns a value of type InputTask[T] and doesn't perform any side effects. The result needs to be bound to an InputKey, like lastReport. The return type of openLastReport is Unit, which means that openLastReport will construct a value that will be discarded, effectively doing nothing useful. Instead, have:
def openLastReport(...): InputTask[...] = ...
lastReport := openLastReport(...).evaluated
(Or, the implementation of openLastReport can be inlined into the right hand side of :=)
You probably don't need inputTaskDyn, but just inputTask. You only need inputTaskDyn if you need to return a task. Otherwise, use inputTask and drop the Def.task.

Why does the "command" directly open and not when clicked on Button? Python 3

I pretty new in this whole Python thing and my question is how to make, that a button runs the command, when clicking it and not before.
I searched much in the Internet but i didnt find anything.
I dont understand the classes at all. Is there no other way to do this?
Here is my work, i did on the programm.
Thanks for your help
from tkinter import *
import os
t = ""
def ordner(x):
print ("def")
if os.path.exists(os.path.join("/Kunden/",x)) == True:
pass
else:
os.mkdir(os.path.join("/Kunden/",x))
def E1holen():
x = E1.get()
ordner(x)
#Hauptfenster
main=Tk(className='Kundendatenbank')
main.iconbitmap('icon.ico')
#Inhalt Hauptfenster
L1 = Label(main, text="Kundenname:")
L1.pack(side = LEFT)
E1 = Entry(main, bd =5, textvariable=t)
E1.pack(side = RIGHT)
a = Button (main, text=("erstellen/bearbeiten"), command=E1holen()).pack()
main.mainloop()
It runs immediately ecause you tell it to.
What is the syntax for calling a function in Python? It's foo(), right? So, when you do command=E1holen(), what should python do? It should call E1holen(), and then pass the result to the command attribute.
Put another way, the command attribute takes a reference to a function, but because of the () you were calling the function and giving the command attribute whatever that function returned. The solution? Remove the ():
a = Button(..., command=E1holen)

Grokless way for dynamic vocabularies?

I have a python-script, which returns returns a context-based, dynamically generated simple list:
def myVocabMethod(self):
mylist = ['a','list','apart']
# do sth dynamic
return mylist
I would like to pass the result to the selection-field with the vocabulary-attribute looking s.th. like this:
atapi.StringField('theField'
vocabulary=.myPythonScript.myVocabMethod(),
(...)
),
How to glue the script-results and and the vocab-value together?
The documentation I found, always requires Grok. Also it's just a simple list, no i18n or other more complex features needed.
Grokless way to register a named vocabulary:
http://developer.plone.org/forms/vocabularies.html#registering-a-named-vocabulary-provider-in-zcml
Basically you point it to a function which returns SimpleVocabulary instance.
The post, where I found what I was looking for is this one:
http://www.universalwebservices.net/web-programming-resources/zope-plone/dynamic-vocabularies-in-plone-archetypes/
And is referenced in the official docs here:
http://developer.plone.org/content/archetypes/fields.html#dynamic-vocabularies
For anyone who might be interested, this is the code:
from Acquisition import aq_parent
from Products.Archetypes import atapi
from Products.Archetypes.public import DisplayList
YourArchetypeSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((
atapi.StringField(
'somefieldname',
vocabulary = yourVocabulary,
),
))
class YourArchetype(base.ATCTContent):
def yourVocabulary(self):
dl = DisplayList()
# We can do something context-based here,
# f.e. get all Events in parent-folder:
eventlist = aq_parent(self).contentValues(filter={'portal_type' : 'Event'})
for event in eventlist:
dl.add(event['id'], event['title'])
return dl
atapi.registerType(YourArchetype, PROJECTNAME)

Resources