function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def GetAction(self): return ModifyXmlAttributeAction( self.imageName, self.node, self.GetValue() )
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def UpdateItem(self, item): firstUpdate = item.xmlChangeCount == -1
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def ItemExpanding(self, item): if item.xmlChildrenChangeCount != item.xmlNode.childrenChangeCount: self.AddRemoveChildren(item) self.UpdateChildren(item)
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def UpdateLocalChanges(self, item): pass
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def GetNodeChildren(self, item): return item.xmlNode.GetChildren()
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def AddRemoveChildren(self, item): nodeChildren = list( self.GetNodeChildren(item) )
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def AppendItemForXmlNode(self, parentItem, xmlNode): item = self.propertiesPane.tree.AppendItem(parentItem, "") self.propertiesPane.InitItemForXmlNode(item, xmlNode, parentItem.level + 1) return item
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def InsertItemForXmlNodeBefore(self, parentItem, nextItem, xmlNode): previousItem = self.propertiesPane.tree.GetPrevSibling(nextItem) item = self.propertiesPane.tree.InsertItem(parentItem, previousItem, "") self.propertiesPane.InitItemForXmlNode(item, xmlNode, parentItem.level + 1) return item
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def UpdateChildren(self, item): for itemChild in self.propertiesPane.GetItemChildren(item): self.propertiesPane.UpdateItem(itemChild)
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def GetErrorMessage(self, node): message = super(ItemUpdaterWithChildren, self).GetErrorMessage(node) childrenErrorCount = node.childrenErrorCount if childrenErrorCount: childrenMessage = "- There are %d errors in children nodes" % node.childrenErrorCount if message: return '\n'.join( (message, childrenMessage) ) else: return childrenMessage else: return message
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def UpdateLocalChanges(self, item): if item is self.propertiesPane.root: self.SetItemWindow( item, self.propertiesPane.CreateRootWindow() ) else: if self.propertiesPane.tree.GetItemImage(item) < 0: self.SetItemImage(item, 'root') self.propertiesPane.tree.SetItemText(item, 'XML document')
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def UpdateLocalChanges(self, item): if self.propertiesPane.tree.GetItemImage(item) < 0: self.SetItemImage( item, self.GetItemImage() )
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def GetItemImage(self): return 'element'
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def GetItemText(self, node): return '<' + node.domNode.tagName + '>'
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def GetItemWindow(self, item): return None
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def GetModifyWindow(self, node): return None
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def __init__(self, parent, item, tree = None, value = wx.EmptyString, style = 0, *args, **kwargs): AutoFitTextCtrl.__init__(self, parent, value = value, style = style, *args, **kwargs) self.Bind(wx.EVT_SET_FOCUS, self.on_SetFocus)
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def on_SetFocus(self, event): event.Skip() tree = self.tree() if tree is None: return item = self.item() if item is None: return tree.SelectItem(item)
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def __init__(self, parent, errorMessage, *args, **kwargs): warningBitmap = wx.ArtProvider.GetBitmap(wx.ART_ERROR, size = (16, 16)) wx.StaticBitmap.__init__(self, parent, bitmap = warningBitmap, *args, **kwargs) self.SetToolTip( wx.ToolTip( errorMessage ) )
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def __init__(self, parent, errorMessage, itemWindow, modifyWindowFactory, node, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs)
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def on_EditButton(self, event): action = None modifyDialog = ModifyDialog(self, self.modifyWindowFactory, self.node) if modifyDialog.ShowModal() == wx.ID_OK: action = modifyDialog.modifyWindow.GetAction() wx.CallLater(1, action.Execute) modifyDialog.Destroy()
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def __init__(self, parent, modifyWindowFactory, node, *args, **kwargs): wx.Dialog.__init__(self, parent, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *args, **kwargs)
nsmoooose/csp
[ 8, 1, 8, 3, 1285610983 ]
def main(): link = "" title = ""
terzeron/FeedMakerApplications
[ 2, 1, 2, 1, 1440413798 ]
def __init__ (self, input): self.name = input[0] self.P = [float(i)/1000 for i in input[1:49]] # Convert loads from kW to MW
susantoj/powerfactory_python
[ 29, 16, 29, 1, 1424908821 ]
def __init__(self, username = None): if(username == None): self.username = getpass.getuser().lower() else: self.username = username.lower() self.access = None self.name = None self.db = self.__loadDB()
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def setAccess(self,access): self.access = access
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def getUsername(self): return self.username.lower()
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def getName(self): return self.name
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def checkAccessControlIsActive(self): if os.path.isfile(os.path.dirname(os.path.realpath(__file__)) + '\config.json'): with open(os.path.dirname(os.path.realpath(__file__)) + '\config.json') as config_file: config = json.load(config_file) accessControl = config['accessControl'] pass else: settings = QSettings("PostNAS", "PostNAS-Suche") accessControl = settings.value("accessControl") if(accessControl == 1): if (self.checkAccessTable() == False): accessControl = 0 else: if (self.checkAccessTable() == True): accessControl = 1 if os.path.isfile(os.path.dirname(os.path.realpath(__file__)) + '\config.json'): config['accessControl'] = accessControl with open(os.path.dirname(os.path.realpath(__file__)) + '\config.json', 'w') as config_file: json.dump(config, config_file) else: settings.setValue("accessControl", accessControl) if(accessControl == 1): return True else: return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def createAccessTable(self): file_path = os.path.dirname(os.path.realpath(__file__)) + "/create_accesstable/create_table.sql" sql = open(file_path).read() self.__openDB() query = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): sql = sql.replace("public.", self.dbSchema + ".") query.exec_(sql) if(query.lastError().number() == -1): return True else: return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def insertUser(self): if(self.getUsername() != None): self.__openDB() sql = "INSERT INTO public.postnas_search_access_control (username,name,access) VALUES (:username,:name,:access)" query = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): sql = sql.replace("public.", self.dbSchema + ".") query.prepare(sql) query.bindValue(":username",self.getUsername().lower()) query.bindValue(":name",self.name) query.bindValue(":access",self.access) query.exec_() if(query.lastError().number() == -1): return True else: return False else: return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def updateUser(self,username_old): if(self.getUsername() != None): self.__openDB() sql = "UPDATE public.postnas_search_access_control SET username = :username, name = :name, access = :access WHERE username = :username_old" query = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): sql = sql.replace("public.", self.dbSchema + ".") query.prepare(sql) query.bindValue(":username",self.getUsername().lower()) query.bindValue(":username_old",username_old) query.bindValue(":name",self.name) query.bindValue(":access",self.access) query.exec_() if(query.lastError().number() == -1): return True else: QgsMessageLog.logMessage("Datenbankfehler beim Update: " + query.lastError().text(),'PostNAS-Suche', Qgis.Critical) return False else: return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def checkUserHasEigentuemerAccess(self): if(self.getUsername() != None): self.__openDB() sql = "SELECT lower(username) as username FROM public.postnas_search_access_control WHERE access IN (0,1) AND lower(username) = :username" queryEigentuemerAccess = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): sql = sql.replace("public.", self.dbSchema + ".") queryEigentuemerAccess.prepare(sql) queryEigentuemerAccess.bindValue(":username",self.getUsername()) queryEigentuemerAccess.exec_() if(queryEigentuemerAccess.lastError().number() == -1): if(queryEigentuemerAccess.size() > 0): return True else: return False else: return False else: return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def deleteUser(self): sql = "DELETE FROM public.postnas_search_access_control WHERE lower(username) = :username" self.__openDB() queryDeleteUser = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): sql = sql.replace("public.", self.dbSchema + ".") queryDeleteUser.prepare(sql) queryDeleteUser.bindValue(":username",self.getUsername()) queryDeleteUser.exec_() if(queryDeleteUser.lastError().number() == -1): return True else: QgsMessageLog.logMessage("Datenbankfehler beim Löschen: " + queryDeleteUser.lastError().text(), 'PostNAS-Suche',Qgis.Critical) return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def checkUserExists(self): sql = "SELECT lower(username) as username FROM public.postnas_search_access_control WHERE lower(username) = :username" self.__openDB() queryCheckUserExists = QSqlQuery(self.db) if (self.dbSchema.lower() != "public"): sql = sql.replace("public.", self.dbSchema + ".") queryCheckUserExists.prepare(sql) queryCheckUserExists.bindValue(":username",self.getUsername()) queryCheckUserExists.exec_() if(queryCheckUserExists.lastError().number() == -1): if(queryCheckUserExists.size() > 0): return True else: return False else: return False
Kreis-Unna/PostNAS_Search
[ 2, 5, 2, 5, 1429788397 ]
def init(self, pad, callbacks): TextBox.init(self, pad, callbacks) self.quote_rgx = re.compile("[\\\"](.*?)[\\\"]") on_hook("curses_opt_change", self.on_opt_change, self) on_hook("curses_var_change", self.on_var_change, self) args = { "link-list" : ("", self.type_link_list), } cmds = { "goto" : (self.cmd_goto, ["link-list"], "Goto a specific link"), "destroy" : (self.cmd_destroy, [], "Destroy this window"), "show-links" : (self.cmd_show_links, [], "Toggle link list display"), "show-summary" : (self.cmd_show_desc, [], "Toggle summary display"), "show-enclosures" : (self.cmd_show_encs, [], "Toggle enclosure list display") } register_arg_types(self, args) register_commands(self, cmds, "Reader") self.plugin_class = ReaderPlugin self.update_plugin_lookups()
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def on_opt_change(self, change): if "reader" not in change: return for opt in ["show_description", "enumerate_links", "show_enclosures"]: if opt in change["reader"]: self.callbacks["set_var"]("needs_refresh", True) self.callbacks["release_gui"]() return
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def on_var_change(self, variables): # If we've been instantiated and unfocused, and selection changes, # we need to be redrawn. if "selected" in variables and variables["selected"]: self.callbacks["set_var"]("reader_item", variables["selected"]) self.callbacks["set_var"]("needs_refresh", True) self.callbacks["release_gui"]()
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def update_text(self): reader_conf = self.callbacks["get_opt"]("reader") s = "No selected story.\n" extra_content = "" sel = self.callbacks["get_var"]("reader_item") if sel: self.links = [("link",sel.content["link"],"mainlink")] s = "%B" + prep_for_display(sel.content["title"]) + "%b\n" # Make sure the story has the most recent info before we check it. sel.sync() # We use the description for most reader content, so if it hasn't # been fetched yet then grab that from the server now and setup # a hook to get notified when sel's attributes are changed. l = ["description", "content", "links", "media_content", "enclosures"] for attr in l: if attr not in sel.content: tag_updater.request_attributes(sel.id, l) s += "%BWaiting for content...%b\n" on_hook("curses_attributes", self.on_attributes, self) break else: # Grab text content over description, as it's likely got more # information. mainbody = sel.content["description"] if "content" in sel.content: for c in sel.content["content"]: if "type" in c and "text" in c["type"]: mainbody = c["value"] # Add enclosures before HTML parsing so that we can add a link # and have the remaining link logic pick it up as normal. if reader_conf['show_enclosures']: parsed_enclosures = [] if sel.content["links"]: for lnk in sel.content["links"]: if 'rel' in lnk and 'href' in lnk and lnk['rel'] == 'enclosure': if 'type' not in lnk: lnk['type'] = 'unknown' parsed_enclosures.append((lnk['href'], lnk['type'])) if sel.content["media_content"] and 'href' in sel.content["media_content"]: if 'type' not in sel.content["media_content"]: sel.content['media_content']['type'] = 'unknown' parsed_enclosures.append((sel.content["media_content"]['href'],\ sel.content["media_content"]['type'])) if sel.content["enclosures"] and 'href' in sel.content["enclosures"]: if 'type' not in sel.content["enclosures"]: sel.content['enclosures']['type'] = 'unknown' parsed_enclosures.append((sel.content['enclosures']['href'],\ sel.content['enclosures']['type'])) if not parsed_enclosures: mainbody += "<br />[ No enclosures. ]<br />" else: for lnk, typ in parsed_enclosures: mainbody += "<a href=\"" mainbody += lnk mainbody += "\">[" mainbody += typ mainbody += "]</a>\n" for attr in list(self.plugin_attrs.keys()): if not attr.startswith("edit_"): continue try: a = getattr(self, attr) (mainbody, extra_content) = a(mainbody, extra_content) except: log.error("Error running Reader edit plugin") log.error(traceback.format_exc()) # This needn't be prep_for_display'd because the HTML parser # handles that. content, links = htmlparser.convert(mainbody) # 0 always is the mainlink, append other links # to the list. self.links += links if reader_conf['show_description']: s += self.quote_rgx.sub(cc("reader_quote") + "\"\\1\"" + cc.end("reader_quote"), content) if reader_conf['enumerate_links']: s += "\n\n" for idx, (t, url, text) in enumerate(self.links): text = prep_for_display(text) url = prep_for_display(url) link_text = "[%B" + str(idx) + "%b][" +\ text + "]: " + url + "\n\n" if t == "link": link_text = cc("reader_link") + link_text + cc.end("reader_link") elif t == "image": link_text = cc("reader_image_link") + link_text + cc.end("reader_image_link") s += link_text # After we have generated the entirety of the content, # strip out any egregious spacing. self.text = s.rstrip(" \t\v\n") + extra_content
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def _toggle_cmd(self, opt): c = self.callbacks["get_conf"]() c["reader"][opt] = not c["reader"][opt] self.callbacks["set_conf"](c)
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def cmd_show_desc(self): self._toggle_cmd("show_description")
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def cmd_destroy(self): self.callbacks["set_var"]("reader_item", None) self.callbacks["die"](self)
themoken/canto-curses
[ 89, 8, 89, 1, 1314730178 ]
def setUp(self): test_functions.reset_test_list() super(TestBeforeAfter, self).setUp()
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def before_fn(*a): test_functions.test_list.append(1)
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def test_after(self): def after_fn(*a): test_functions.test_list.append(2) with after('before_after.tests.test_functions.sample_fn', after_fn): test_functions.sample_fn(1) self.assertEqual(test_functions.test_list, [1, 2])
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def before_fn(*a): test_functions.test_list.append(1)
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def test_before_once(self): def before_fn(*a): test_functions.test_list.append(1) with before( 'before_after.tests.test_functions.sample_fn', before_fn, once=True): test_functions.sample_fn(2) test_functions.sample_fn(3) self.assertEqual(test_functions.test_list, [1, 2, 3])
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def after_fn(*a): test_functions.test_list.append(2)
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def test_before_and_after_once(self): def before_fn(*a): test_functions.test_list.append(1) def after_fn(*a): test_functions.test_list.append(3) with before_after( 'before_after.tests.test_functions.sample_fn', before_fn=before_fn, after_fn=after_fn, once=True): test_functions.sample_fn(2) test_functions.sample_fn(4) self.assertEqual(test_functions.test_list, [1, 2, 3, 4])
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def before_fn(self, *a): sample_instance.instance_list.append(1)
c-oreills/before_after
[ 33, 9, 33, 7, 1422390294 ]
def usage(exit_code=0): print("""Usage: dak check-overrides
Debian/dak
[ 14, 13, 14, 4, 1399335066 ]
def process(osuite, affected_suites, originosuite, component, otype, session): global Logger, Options, sections, priorities o = get_suite(osuite, session) if o is None: utils.fubar("Suite '%s' not recognised." % (osuite)) osuite_id = o.suite_id originosuite_id = None if originosuite: oo = get_suite(originosuite, session) if oo is None: utils.fubar("Suite '%s' not recognised." % (originosuite)) originosuite_id = oo.suite_id c = get_component(component, session) if c is None: utils.fubar("Component '%s' not recognised." % (component)) component_id = c.component_id ot = get_override_type(otype, session) if ot is None: utils.fubar("Type '%s' not recognised. (Valid types are deb, udeb and dsc)" % (otype)) type_id = ot.overridetype_id dsc_type_id = get_override_type("dsc", session).overridetype_id source_priority_id = get_priority("optional", session).priority_id if otype == "deb" or otype == "udeb": packages = {} # TODO: Fix to use placeholders (check how to with arrays) q = session.execute("""
Debian/dak
[ 14, 13, 14, 4, 1399335066 ]
def main(): global Logger, Options, sections, priorities cnf = Config() Arguments = [('h', "help", "Check-Overrides::Options::Help"), ('n', "no-action", "Check-Overrides::Options::No-Action")] for i in ["help", "no-action"]: key = "Check-Overrides::Options::%s" % i if key not in cnf: cnf[key] = "" apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv) Options = cnf.subtree("Check-Overrides::Options") if Options["Help"]: usage() session = DBConn().session() # init sections, priorities: # We need forward and reverse sections = get_sections(session) for name, entry in list(sections.items()): sections[entry] = name priorities = get_priorities(session) for name, entry in list(priorities.items()): priorities[entry] = name if not Options["No-Action"]: Logger = daklog.Logger("check-overrides") else: Logger = daklog.Logger("check-overrides", 1) for suite in session.query(Suite).filter(Suite.overrideprocess == True): # noqa:E712 originosuite = None originremark = '' if suite.overrideorigin is not None: originosuite = get_suite(suite.overrideorigin, session) if originosuite is None: utils.fubar("%s has an override origin suite of %s but it doesn't exist!" % (suite.suite_name, suite.overrideorigin)) originosuite = originosuite.suite_name originremark = " taking missing from %s" % originosuite print("Processing %s%s..." % (suite.suite_name, originremark)) # Get a list of all suites that use the override file of 'suite.suite_name' as # well as the suite ocodename = suite.codename suiteids = [x.suite_id for x in session.query(Suite).filter(Suite.overridecodename == ocodename).all()] if suite.suite_id not in suiteids: suiteids.append(suite.suite_id) if len(suiteids) < 1: utils.fubar("Couldn't find id's of all suites: %s" % suiteids) for component in session.query(Component).all(): # It is crucial for the dsc override creation based on binary # overrides that 'dsc' goes first component_name = component.component_name otypes = ['dsc'] for ot in session.query(OverrideType): if ot.overridetype == 'dsc': continue otypes.append(ot.overridetype) for otype in otypes: print("Processing %s [%s - %s]" % (suite.suite_name, component_name, otype)) sys.stdout.flush() process(suite.suite_name, suiteids, originosuite, component_name, otype, session) Logger.close()
Debian/dak
[ 14, 13, 14, 4, 1399335066 ]
def engine(): engine = create_engine('sqlite://', echo=True) Base.metadata.create_all(engine) return engine
Debian/dak
[ 14, 13, 14, 4, 1399335066 ]
def initAlgorithm(self, config): """ Parameter setting. """ self.addParameter( QgsProcessingParameterMultipleLayers( self.INPUT_LAYERS, self.tr('Input Layers'), QgsProcessing.TypeVectorAnyGeometry ) ) self.addParameter( QgsProcessingParameterString( self.FILTER, self.tr('Filter') ) ) self.modes = [self.tr('Append to existing filter with AND clause'), self.tr('Append to existing filter with OR clause'), self.tr('Replace filter') ] self.addParameter( QgsProcessingParameterEnum( self.BEHAVIOR, self.tr('Behavior'), options=self.modes, defaultValue=0 ) ) self.addOutput( QgsProcessingOutputMultipleLayers( self.OUTPUT, self.tr('Original layers with assigned styles') ) )
lcoandrade/DsgTools
[ 42, 22, 42, 15, 1412914139 ]
def adaptFilter(self, lyr, inputFilter, behavior): """ Adapts filter according to the selected mode """ originalFilter = lyr.subsetString() if behavior == AssignFilterToLayersAlgorithm.ReplaceMode or originalFilter == '': return inputFilter clause = ' AND ' if behavior == AssignFilterToLayersAlgorithm.AndMode else ' OR ' return clause.join([originalFilter, inputFilter])
lcoandrade/DsgTools
[ 42, 22, 42, 15, 1412914139 ]
def displayName(self): """ Returns the translated algorithm name, which should be used for any user-visible display of the algorithm name. """ return self.tr('Assign Filter to Layers')
lcoandrade/DsgTools
[ 42, 22, 42, 15, 1412914139 ]
def groupId(self): """ Returns the unique ID of the group this algorithm belongs to. This string should be fixed for the algorithm, and must not be localised. The group id should be unique within each provider. Group id should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'DSGTools: Layer Management Algorithms'
lcoandrade/DsgTools
[ 42, 22, 42, 15, 1412914139 ]
def warp_images(from_points, to_points, images, output_region, interpolation_order = 1, approximate_grid=2): """Define a thin-plate-spline warping transform that warps from the from_points to the to_points, and then warp the given images by that transform. This transform is described in the paper: "Principal Warps: Thin-Plate Splines and the Decomposition of Deformations" by F.L. Bookstein. Parameters: - from_points and to_points: Nx2 arrays containing N 2D landmark points. - images: list of images to warp with the given warp transform. - output_region: the (xmin, ymin, xmax, ymax) region of the output image that should be produced. (Note: The region is inclusive, i.e. xmin <= x <= xmax) - interpolation_order: if 1, then use linear interpolation; if 0 then use nearest-neighbor. - approximate_grid: defining the warping transform is slow. If approximate_grid is greater than 1, then the transform is defined on a grid 'approximate_grid' times smaller than the output image region, and then the transform is bilinearly interpolated to the larger region. This is fairly accurate for values up to 10 or so. """ transform = _make_inverse_warp(from_points, to_points, output_region, approximate_grid) return [ndimage.map_coordinates(numpy.asarray(image), transform, order=interpolation_order) for image in images]
zpincus/celltool
[ 23, 8, 23, 1, 1404710019 ]
def _U(x): return (x**2) * numpy.where(x<_small, 0, numpy.log(x))
zpincus/celltool
[ 23, 8, 23, 1, 1404710019 ]
def _make_L_matrix(points): n = len(points) K = _U(_interpoint_distances(points)) P = numpy.ones((n, 3)) P[:,1:] = points O = numpy.zeros((3, 3)) L = numpy.asarray(numpy.bmat([[K, P],[P.transpose(), O]])) return L
zpincus/celltool
[ 23, 8, 23, 1, 1404710019 ]
def __init__(self): self.re_pid = re.compile(r'ktmp([0-9a-f]{5})$', re.IGNORECASE) self.temp_path = os.path.join(tempfile.gettempdir(), 'ktmp%05x' % os.getpid()) if not os.path.exists(self.temp_path): try: os.mkdir(self.temp_path) except (IOError, OSError) as e: self.temp_path = tempfile.gettempdir()
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def mktemp(self): return tempfile.mktemp(prefix='ktmp', dir=self.temp_path)
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def __init__(self, filename=None, level=0): self.__fs = {} if filename: self.set_default(filename, level)
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def set_default(self, filename, level): import kernel self.__fs['is_arc'] = False # 압축 여부 self.__fs['arc_engine_name'] = None # 압축 해제 가능 엔진 ID self.__fs['arc_filename'] = '' # 실제 압축 파일 self.__fs['filename_in_arc'] = '' # 압축해제 대상 파일 self.__fs['real_filename'] = filename # 검사 대상 파일 self.__fs['additional_filename'] = '' # 압축 파일의 내부를 표현하기 위한 파일명 self.__fs['master_filename'] = filename # 출력용 self.__fs['is_modify'] = False # 수정 여부 self.__fs['can_arc'] = kernel.MASTER_IGNORE # 재압축 가능 여부 self.__fs['level'] = level # 압축 깊이
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def is_archive(self): # 압축 여부 return self.__fs['is_arc']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_archive_engine_name(self): # 압축 엔진 ID return self.__fs['arc_engine_name']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_archive_filename(self): # 실제 압축 파일 return self.__fs['arc_filename']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_filename_in_archive(self): # 압축해제 대상 파일 return self.__fs['filename_in_arc']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_filename(self): # 실제 작업 파일 이름 return self.__fs['real_filename']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def set_filename(self, fname): # 실제 작업 파일명을 저장 self.__fs['real_filename'] = fname
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_master_filename(self): # 압축일 경우 최상위 파일 return self.__fs['master_filename'] # 출력용
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_additional_filename(self): return self.__fs['additional_filename']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def set_additional_filename(self, filename): self.__fs['additional_filename'] = filename
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def is_modify(self): # 수정 여부 return self.__fs['is_modify']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def set_modify(self, modify): # 수정 여부 self.__fs['is_modify'] = modify
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_can_archive(self): # 재압축 가능 여부 return self.__fs['can_arc']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def set_can_archive(self, mode): # 재압축 가능 여부 self.__fs['can_arc'] = mode
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def get_level(self): # 압축 깊이 return self.__fs['level']
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def set_level(self, level): # 압축 깊이 self.__fs['level'] = level
hanul93/kicomav
[ 285, 127, 285, 3, 1368656165 ]
def intersect(i, j, **gb_opts): """ This functions intersects two ideals. The first ring variable is used as helper variable for this intersection. It is assumed, that it doesn't occur in the ideals, and that we have an elimination ordering for this variables. Both assumptions are checked. >>> from brial.frontend import declare_ring >>> from brial import Block >>> r=declare_ring(Block("x", 1000), globals()) >>> x = r.variable >>> intersect([x(1),x(2)+1],[x(1),x(2)]) [x(1)] """ if not i or not j: return [] uv = used_vars_set(i) * used_vars_set(j) t = next(iter(i)).ring().variable(0) if uv.reducible_by(t): raise ValueError("First ring variable has to be reserved as helper variable t") if not t > uv: raise ValueError("need elimination ordering for first ring variable") gb = groebner_basis(list(chain((t * p for p in i), ((1 + t) * p for p in j ))), **gb_opts) return [p for p in gb if p.navigation().value() > t.index()]
BRiAl/BRiAl
[ 16, 16, 16, 1, 1440372546 ]
def __new__(cls, value, phrase, description=''): obj = int.__new__(cls, value) obj._value_ = value obj.phrase = phrase obj.description = description return obj
bruderstein/PythonScript
[ 310, 62, 310, 74, 1280013973 ]
def __init__(self, inputAudioFilename, windowSize=0.0464, hopsize=None, NFT=None, nbIter=10, numCompAccomp=40, minF0=39, maxF0=2000, stepNotes=16, chirpPerF0=1, K_numFilters=4, P_numAtomFilters=30, imageCanvas=None, wavCanvas=None, progressBar=None, verbose=True, outputDirSuffix='/', minF0search=None, maxF0search=None, tfrepresentation='stft', cqtfmax=4000, cqtfmin=50, cqtbins=48, cqtWinFunc=slf.minqt.sqrt_blackmanharris, cqtAtomHopFactor=0.25, initHF00='random', freeMemory=True): """During init, process is initiated, STFTs are computed, and the parameters are stored.
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def setOutputFileNames(self, outputDirSuffix): """ If already loaded a wav file, at this point, we can redefine where we want the output files to be written.
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def computeWF0(self): """Computes the frequency basis for the source part of SIMM, if tfrepresentation is a CQT, it also computes the cqt/hybridcqt transform object.
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def computeMonoX(self, start=0, stop=None): """Computes and return SX, the mono channel or mean over the channels of the power spectrum of the signal """ fs, data = wav.read(self.files['inputAudioFilename']) data = np.double(data) / self.scaleData if len(data.shape)>1 and data.shape[1]>1: data = data.mean(axis=1)
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def computeNFrames(self): """ compute Nb Frames: """ if not hasattr(self, 'totFrames'): if self.tfrepresentation in knownTransfos: # NB for hybridcqt should be the same formula, # but the values are a bit different in nature. fs, data = wav.read(self.files['inputAudioFilename']) self.lengthData = data.shape[0] self.totFrames = ( np.int32(np.ceil((self.lengthData - 0) / # self.stftParams['windowSizeInSamples']) / self.stftParams['hopsize'] + 1) + 1)# same number as in slf.stft ) self.N = self.totFrames
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def computeStereoX(self, start=0, stop=None, ): """Compute the transform on each of the channels.
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def computeStereoSX(self, start=0, stop=None, ): fs, data = wav.read(self.files['inputAudioFilename']) data = np.double(data) / self.scaleData if self.tfrepresentation == 'stft': starttime = start * self.stftParams['hopsize'] if stop is not None: stoptime = stop * self.stftParams['hopsize'] else: stoptime = data.shape[0] self.originalDataLen = stoptime - starttime
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def estimSIMMParams(self, R=1): ## section to estimate the melody, on monophonic algo: SX = self.computeMonoX() # First round of parameter estimation: print " Estimating IMM parameters, on mean of channels, with",R,\ "\n accompaniment components." HGAMMA, HPHI, HF0, HM, WM, recoError1 = SIMM.SIMM( # the data to be fitted to: SX, # the basis matrices for the spectral combs WF0=self.SIMMParams['WF0'], # and for the elementary filters: WGAMMA=self.SIMMParams['WGAMMA'], # number of desired filters, accompaniment spectra: numberOfFilters=self.SIMMParams['K'], numberOfAccompanimentSpectralShapes=R,#self.SIMMParams['R'], # putting only 2 elements in accompaniment for a start... # if any, initial amplitude matrices for HGAMMA0=None, HPHI0=None, HF00=None, WM0=None, HM0=None, # Some more optional arguments, to control the "convergence" # of the algo numberOfIterations=self.SIMMParams['niter'], updateRulePower=1., stepNotes=self.SIMMParams['stepNotes'], lambdaHF0 = 0.0 / (1.0 * SX.max()), alphaHF0=0.9, verbose=self.verbose, displayEvolution=self.displayEvolution, imageCanvas=self.imageCanvas, F0Table=self.SIMMParams['F0Table'], chirpPerF0=self.SIMMParams['chirpPerF0'])
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def estimHF0(self, R=1, maxFrames=1000): """ estimating and storing only HF0 for the whole excerpt, with only """ ## section to estimate the melody, on monophonic algo: #SX = self.computeMonoX() # too heavy, try to guess before hand instead #totFrames = SX.shape[1] totFrames, nChunks, maxFrames = self.checkChunkSize(maxFrames) # First round of parameter estimation: print " Estimating IMM parameters, on mean of channels, with",R,\ "\n accompaniment components."+\ " Nb of chunks: %d." %nChunks # del SX self.SIMMParams['HF0'] = np.zeros([self.SIMMParams['NF0'] * \ self.SIMMParams['chirpPerF0'], totFrames]) for n in range(nChunks): if self.verbose: print "Chunk nb", n+1, "out of", nChunks start = n*maxFrames stop = np.minimum((n+1)*maxFrames, totFrames) SX = self.computeMonoX(start=start, stop=stop) if self.SIMMParams['initHF00'] == 'nnls': # probably slower than running from random... HF00 = np.ones((self.SIMMParams['NF0'] * self.SIMMParams['chirpPerF0'], stop-start)) for framenb in range(stop-start): if self.verbose>1: print "frame", framenb HF00[:,framenb], _ = scipy.optimize.nnls( self.SIMMParams['WF0'], SX[:,framenb]) HF00 += eps else: HF00 = None HGAMMA, HPHI, HF0, HM, WM, recoError1 = SIMM.SIMM( # the data to be fitted to: SX, # the basis matrices for the spectral combs WF0=self.SIMMParams['WF0'], # and for the elementary filters: WGAMMA=self.SIMMParams['WGAMMA'], # number of desired filters, accompaniment spectra: numberOfFilters=self.SIMMParams['K'], numberOfAccompanimentSpectralShapes=R,#self.SIMMParams['R'], # putting only 2 elements in accompaniment for a start... # if any, initial amplitude matrices for HGAMMA0=None, HPHI0=None, HF00=HF00, WM0=None, HM0=None, # Some more optional arguments, to control the "convergence" # of the algo numberOfIterations=self.SIMMParams['niter'], updateRulePower=1., stepNotes=self.SIMMParams['stepNotes'], lambdaHF0 = 0.0 / (1.0 * SX.max()), alphaHF0=0.9, verbose=self.verbose, displayEvolution=self.displayEvolution, imageCanvas=self.imageCanvas, F0Table=self.SIMMParams['F0Table'], chirpPerF0=self.SIMMParams['chirpPerF0'])
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def computeChroma(self, maxFrames=3000): """Compute the chroma matrix. """ if hasattr(self, 'SIMMParams'): if 'HF0' not in self.SIMMParams.keys(): self.estimHF0(maxFrames=maxFrames) else: raise AttributeError("The parameters for the SIMM are not"+\ " well initialized") if not hasattr(self, 'N'): warnings.warn("Issues with the attributes, running again"+\ " the estimation.") self.estimHF0(maxFrames=maxFrames)
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def determineTuning(self): """Determine Tuning by checking the peaks corresponding to all possible patterns """ if not hasattr(self, 'chroma'): self.computeChroma()
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def automaticMelodyAndSeparation(self): """Fully automated estimation of melody and separation of signals. """ raise warnings.warn("This function does not work well with framed " + "estimation.") self.runViterbi() self.initiateHF0WithIndexBestPath() self.estimStereoSIMMParams() self.writeSeparatedSignals() self.estimStereoSUIMMParams() self.writeSeparatedSignalsWithUnvoice()
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def autoMelSepAndWrite(self, maxFrames=1000): """Fully automated estimation of melody and separation of signals. """ self.estimHF0(maxFrames=maxFrames) self.runViterbi() self.initiateHF0WithIndexBestPath() self.estimStereoSIMMParamsWriteSeps(maxFrames=maxFrames)
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def runViterbi(self): if not('HF0' in self.SIMMParams.keys()): raise AttributeError("HF0 has probably not been estimated yet.") ##SX = self.computeMonoX() # useless here? self.computeNFrames() # just to be sure self.N is total nb of frames
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def initiateHF0WithIndexBestPath(self): # Second round of parameter estimation, with specific # initial HF00: NF0 = self.SIMMParams['NF0'] chirpPerF0 = self.SIMMParams['chirpPerF0'] stepNotes = self.SIMMParams['stepNotes']
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def estimStereoSIMMParamsWriteSeps(self, maxFrames=1000): """Estimates the parameters little by little, by chunks, and sequentially writes the signals. In the end, concatenates all these separated signals into the desired output files """ #SX = self.computeMonoX() totFrames, nChunks, maxFrames = self.checkChunkSize(maxFrames) # del SX
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def overlapAddChunks(self, nChunks, suffixIsSUIMM='.wav'): # Now concatenating the wav files wlen = self.stftParams['windowSizeInSamples'] offsetTF = self.stftParams['offsets'][self.tfrepresentation] # overlap add on the chunks: if self.tfrepresentation == 'stft': hopsize = self.stftParams['hopsize'] overlapSamp = wlen - hopsize # for stft, the overlap is taken into account at computation # using rectangle synthesis function: overlapFunc = np.ones(overlapSamp) elif self.tfrepresentation in knownTransfos: hopsize = self.mqt.cqtkernel.atomHOP # for hybridcqt, have to compensate the overlap procedure: overlapSamp = wlen - hopsize # using sinebell ** 2 for overlapping function # (rectangle as analysis function for hybridcqt): overlapFunc = slf.sinebell(2 * overlapSamp)[overlapSamp:]**2 if self.verbose>3: print "[DEBUG] check that window adds to 1:", print overlapFunc + overlapFunc[::-1] nuDataLen = ( self.totFrames * hopsize + 2 * wlen) data = np.zeros([nuDataLen, 2], np.int16)
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]
def estimStereoSUIMMParamsWriteSeps(self, maxFrames=1000): """same as estimStereoSIMMParamsWriteSeps, but adds the unvoiced element in HF0 """ totFrames, nChunks, maxFrames = self.checkChunkSize(maxFrames) print " Estimating IMM parameters, on stereo channels, with",\ self.SIMMParams['R'],\ "\n accompaniment components."+\ " Nb of chunks: %d." %nChunks
wslihgt/pyfasst
[ 87, 21, 87, 6, 1375254776 ]