function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def get_value( self, trans, grid, repository_metadata ): datatypes_str = '0' if repository_metadata: metadata = repository_metadata.metadata if metadata: if 'datatypes' in metadata: # We used to display the following, but grid was too cluttered. #for datatype_metadata_dict in metadata[ 'datatypes' ]: # datatypes_str += '%s<br/>' % datatype_metadata_dict[ 'extension' ] return '%d' % len( metadata[ 'datatypes' ] ) return datatypes_str
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def get_value( self, trans, grid, repository_metadata ): workflows_str = '0' if repository_metadata: metadata = repository_metadata.metadata if metadata: if 'workflows' in metadata: # We used to display the following, but grid was too cluttered. #workflows_str += '<b>Workflows:</b><br/>' # metadata[ 'workflows' ] is a list of tuples where each contained tuple is # [ <relative path to the .ga file in the repository>, <exported workflow dict> ] #workflow_tups = metadata[ 'workflows' ] #workflow_metadata_dicts = [ workflow_tup[1] for workflow_tup in workflow_tups ] #for workflow_metadata_dict in workflow_metadata_dicts: # workflows_str += '%s<br/>' % workflow_metadata_dict[ 'name' ] return '%d' % len( metadata[ 'workflows' ] ) return workflows_str
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def get_value( self, trans, grid, repository_metadata ): if repository_metadata.repository.deleted: return 'yes' return ''
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def get_value( self, trans, grid, repository_metadata ): if repository_metadata.repository.deprecated: return 'yes' return ''
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def get_value( self, trans, grid, repository_metadata ): if repository_metadata.malicious: return 'yes' return ''
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def shortcut_xml_gen(shortcut_entries): root = etree.Element("interface") root.append(create_object_tree(shortcut_entries)) content = etree.tostring(root, xml_declaration=True, encoding="UTF-8", pretty_print=True) content = content.decode("UTF-8") return content
mozbugbox/liferea-plugin-studio
[ 6, 3, 6, 6, 1428496840 ]
def objnode(adict): prefix = "GtkShortcuts" if not adict["klass"].startswith(prefix): adict["klass"] = prefix + adict["klass"] if "attrib" not in adict: adict["attrib"]= {} aobj = etree.Element ("object", attrib=adict["attrib"]) aobj.attrib["class"] = adict["klass"] return aobj
mozbugbox/liferea-plugin-studio
[ 6, 3, 6, 6, 1428496840 ]
def append_props(parent, item): if "properties" in item: props = [propnode(x, y) for x, y in item["properties"].items()] [parent.append(x) for x in props]
mozbugbox/liferea-plugin-studio
[ 6, 3, 6, 6, 1428496840 ]
def shortcut_entry(title, accel=None, gesture=None, **kwargs): props = { "title": title, "visible": 1, } if accel: props["accelerator"] = accel if gesture: props["shortcut-type"] = gesture props.update(kwargs) entry = { "klass": "Shortcut", "properties": props, } return entry
mozbugbox/liferea-plugin-studio
[ 6, 3, 6, 6, 1428496840 ]
def section_entry(name, groups, **kwargs): entry = { "klass": "Section", "properties": { "visible": 1, "section-name": name, }, "childs": groups, } entry["properties"].update(kwargs) return entry
mozbugbox/liferea-plugin-studio
[ 6, 3, 6, 6, 1428496840 ]
def main(): def set_stdio_encoding(enc=NATIVE): import codecs; stdio = ["stdin", "stdout", "stderr"] for x in stdio: obj = getattr(sys, x) if not obj.encoding: setattr(sys, x, codecs.getwriter(enc)(obj)) set_stdio_encoding() log_level = log.INFO log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level) shortcuts1 = [ shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"), ] shortcuts2 = [ shortcut_entry("Import channels from file", "<ctrl>o"), shortcut_entry("Export channels to file", "<ctrl>e"), ] groups = [ group_entry("Application", shortcuts1), group_entry("Import/Export Channels", shortcuts2), ] sections = [ section_entry("shortcut", groups) ] entry = shortcut_window_entry("shortcut-window", sections, modal=1) content = shortcut_xml_gen(entry) print(content) def test_gui(shortcut_xml): import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk builder = Gtk.Builder() builder.add_from_string(shortcut_xml) win = builder.get_object("shortcut-window") win.connect("delete-event", lambda *w: Gtk.main_quit()) win.show_all() Gtk.main() test_gui(content)
mozbugbox/liferea-plugin-studio
[ 6, 3, 6, 6, 1428496840 ]
def test_stream_type_parsing(): """Make sure we can parse each type of stream.""" # Make sure parsing stream type works stream = DataStream.FromString('buffered 1') assert stream.stream_type == stream.BufferedType stream = DataStream.FromString(u'buffered 1') assert stream.stream_type == stream.BufferedType stream = DataStream.FromString('unbuffered 1') assert stream.stream_type == stream.UnbufferedType stream = DataStream.FromString(u'unbuffered 1') assert stream.stream_type == stream.UnbufferedType stream = DataStream.FromString('counter 1') assert stream.stream_type == stream.CounterType stream = DataStream.FromString(u'counter 1') assert stream.stream_type == stream.CounterType stream = DataStream.FromString('constant 1') assert stream.stream_type == stream.ConstantType stream = DataStream.FromString(u'constant 1') assert stream.stream_type == stream.ConstantType stream = DataStream.FromString('output 1') assert stream.stream_type == stream.OutputType stream = DataStream.FromString(u'output 1') assert stream.stream_type == stream.OutputType
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def test_system_parsing(): """Make sure we can parse the system prefix.""" stream = DataStream.FromString('buffered 1') assert stream.system is False stream = DataStream.FromString(u'buffered 1') assert stream.system is False stream = DataStream.FromString('system buffered 1') assert stream.system is True stream = DataStream.FromString(u'system buffered 1') assert stream.system is True
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def test_selector_parsing(): """Make sure we can parse DataStreamSelector strings.""" # Make sure parsing stream type works stream = DataStreamSelector.FromString('buffered 1') assert stream.match_type == DataStream.BufferedType stream = DataStreamSelector.FromString(u'buffered 1') assert stream.match_type == DataStream.BufferedType stream = DataStreamSelector.FromString('unbuffered 1') assert stream.match_type == DataStream.UnbufferedType stream = DataStreamSelector.FromString(u'unbuffered 1') assert stream.match_type == DataStream.UnbufferedType stream = DataStreamSelector.FromString('counter 1') assert stream.match_type == DataStream.CounterType stream = DataStreamSelector.FromString(u'counter 1') assert stream.match_type == DataStream.CounterType stream = DataStreamSelector.FromString('constant 1') assert stream.match_type == DataStream.ConstantType stream = DataStreamSelector.FromString(u'constant 1') assert stream.match_type == DataStream.ConstantType stream = DataStreamSelector.FromString('output 1') assert stream.match_type == DataStream.OutputType stream = DataStreamSelector.FromString(u'output 1') assert stream.match_type == DataStream.OutputType
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def test_matching(): """Test selector stream matching.""" sel = DataStreamSelector.FromString(u'all system buffered') assert sel.matches(DataStream.FromString('system buffered 1')) assert not sel.matches(DataStream.FromString('buffered 1')) assert not sel.matches(DataStream.FromString('counter 1')) sel = DataStreamSelector.FromString(u'all user outputs') assert sel.matches(DataStream.FromString('output 1')) assert not sel.matches(DataStream.FromString('system output 1')) assert not sel.matches(DataStream.FromString('counter 1')) sel = DataStreamSelector.FromString(u'all combined outputs') assert sel.matches(DataStream.FromString('output 1')) assert sel.matches(DataStream.FromString('system output 1')) assert not sel.matches(DataStream.FromString('counter 1')) sel = DataStreamSelector.FromString(u'all outputs') assert sel.matches(DataStream.FromString('output 1')) assert sel.matches(DataStream.FromString('system output 1024')) assert not sel.matches(DataStream.FromString('system output 1')) assert not sel.matches(DataStream.FromString('counter 1'))
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def test_selector_from_encoded(): """Make sure we can create a selector from an encoded value.""" sel = DataStreamSelector.FromEncoded(0x5FFF) assert str(sel) == 'all system outputs' sel = DataStreamSelector.FromEncoded(0xD7FF) assert str(sel) == 'all outputs' sel = DataStreamSelector.FromEncoded(0x100a) assert str(sel) == 'unbuffered 10' assert str(DataStreamSelector.FromEncoded(DataStreamSelector.FromString('all combined output').encode())) == 'all combined outputs'
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def formatCase(text): """Formats code to contain only one indentation and terminate with a \n""" return indent(dedent(text.lstrip("\n")), " ") + "\n"
ethereum/solidity
[ 19651, 4867, 19651, 712, 1439814446 ]
def setUp(self): self.maxDiff = 10000
ethereum/solidity
[ 19651, 4867, 19651, 712, 1439814446 ]
def test_solidity_block_with_directives(self): expected_cases = [formatCase(case) for case in [ """ // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract C { function foo() public view {} } """, """ contract C {} """, """ contract D {} :linenos: """, """ contract E {} """, ]] self.assertEqual(extract_solidity_docs_cases(CODE_BLOCK_WITH_DIRECTIVES_RST_PATH), expected_cases)
ethereum/solidity
[ 19651, 4867, 19651, 712, 1439814446 ]
def register_field(name): """add resolver class to registry""" def add_class(clazz): field_registry[name] = clazz return clazz return add_class
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def __init__(self, key, props): self.key = key self.props = props
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def create(key, context): # normalize if isinstance(context, str): context = { "lookup": "literal", "prop": { "value": context } } field_type = context["lookup"] return field_registry[field_type](key, context["prop"])
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def __init__(self, key, props): super().__init__(key, props)
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def value(self): return self.props["value"]
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def __init__(self, key, props): super().__init__(key, props)
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def value(self): return os.environ[self.props["variable"]]
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def __init__(self, key, props): super().__init__(key, props)
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def value(self): return self.resolver.get( self.props["value"], self.props.get("index", None) )
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def provider(self): provider_manager = ProviderManager.instance() return provider_manager.get(self.props["provider"])
2pisoftware/cmfive-boilerplate
[ 1, 10, 1, 3, 1485729376 ]
def setupUi(self, CanardPreferencesDialog): CanardPreferencesDialog.setObjectName(_fromUtf8("CanardPreferencesDialog")) CanardPreferencesDialog.resize(512, 375) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/actions/preferences-system-2.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) CanardPreferencesDialog.setWindowIcon(icon) self.verticalLayout = QtGui.QVBoxLayout(CanardPreferencesDialog) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.tabWidget = FingerTabWidget(CanardPreferencesDialog) self.tabWidget.setTabPosition(QtGui.QTabWidget.West) self.tabWidget.setIconSize(QtCore.QSize(32, 32)) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab_4 = QtGui.QWidget() self.tab_4.setObjectName(_fromUtf8("tab_4")) self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab_4) self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.checkForUpdates = QtGui.QCheckBox(self.tab_4) self.checkForUpdates.setEnabled(False) self.checkForUpdates.setObjectName(_fromUtf8("checkForUpdates")) self.horizontalLayout_2.addWidget(self.checkForUpdates) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem) self.pushButton = QtGui.QPushButton(self.tab_4) self.pushButton.setEnabled(False) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.horizontalLayout_2.addWidget(self.pushButton) self.verticalLayout_3.addLayout(self.horizontalLayout_2) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.label_6 = QtGui.QLabel(self.tab_4) self.label_6.setObjectName(_fromUtf8("label_6")) self.horizontalLayout_3.addWidget(self.label_6) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.spinBox = QtGui.QSpinBox(self.tab_4) self.spinBox.setMaximum(1000) self.spinBox.setSingleStep(10) self.spinBox.setObjectName(_fromUtf8("spinBox")) self.horizontalLayout_3.addWidget(self.spinBox) self.verticalLayout_3.addLayout(self.horizontalLayout_3) spacerItem2 = QtGui.QSpacerItem(20, 270, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_3.addItem(spacerItem2) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/Canard_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.tabWidget.addTab(self.tab_4, icon1, _fromUtf8("")) self.tab = QtGui.QWidget() self.tab.setObjectName(_fromUtf8("tab")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.tab) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.label_3 = QtGui.QLabel(self.tab) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout.addWidget(self.label_3) self.defaultDisplayLanguage = QtGui.QComboBox(self.tab) self.defaultDisplayLanguage.setEditable(False) self.defaultDisplayLanguage.setObjectName(_fromUtf8("defaultDisplayLanguage")) self.horizontalLayout.addWidget(self.defaultDisplayLanguage) self.verticalLayout_2.addLayout(self.horizontalLayout) self.horizontalLayout_4 = QtGui.QHBoxLayout() self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.label_5 = QtGui.QLabel(self.tab) self.label_5.setObjectName(_fromUtf8("label_5")) self.horizontalLayout_4.addWidget(self.label_5) self.comboBox = QtGui.QComboBox(self.tab) self.comboBox.setEnabled(False) self.comboBox.setObjectName(_fromUtf8("comboBox")) self.comboBox.addItem(_fromUtf8("")) self.horizontalLayout_4.addWidget(self.comboBox) self.verticalLayout_2.addLayout(self.horizontalLayout_4) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label = QtGui.QLabel(self.tab) self.label.setWordWrap(True) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 0, 0, 1, 1) spacerItem3 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem3, 2, 1, 1, 1) self.addDefaultNewLang = QtGui.QPushButton(self.tab) self.addDefaultNewLang.setObjectName(_fromUtf8("addDefaultNewLang")) self.gridLayout.addWidget(self.addDefaultNewLang, 3, 1, 1, 1) self.removeDefaultNewLang = QtGui.QPushButton(self.tab) self.removeDefaultNewLang.setObjectName(_fromUtf8("removeDefaultNewLang")) self.gridLayout.addWidget(self.removeDefaultNewLang, 4, 1, 1, 1) self.label_2 = QtGui.QLabel(self.tab) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout.addWidget(self.label_2, 0, 2, 1, 1) spacerItem4 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem4, 5, 1, 1, 1) self.label_4 = QtGui.QLabel(self.tab) self.label_4.setWordWrap(True) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout.addWidget(self.label_4, 1, 1, 1, 1) self.defaultNewLangs = QtGui.QListWidget(self.tab) self.defaultNewLangs.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.defaultNewLangs.setObjectName(_fromUtf8("defaultNewLangs")) self.gridLayout.addWidget(self.defaultNewLangs, 1, 0, 5, 1) self.possibleDefaultNewLangs = QtGui.QListWidget(self.tab) self.possibleDefaultNewLangs.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.possibleDefaultNewLangs.setObjectName(_fromUtf8("possibleDefaultNewLangs")) self.gridLayout.addWidget(self.possibleDefaultNewLangs, 1, 2, 5, 1) self.verticalLayout_2.addLayout(self.gridLayout) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/file/actions/applications-development-translation.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.tabWidget.addTab(self.tab, icon2, _fromUtf8("")) self.verticalLayout.addWidget(self.tabWidget) self.buttonBox = QtGui.QDialogButtonBox(CanardPreferencesDialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.verticalLayout.addWidget(self.buttonBox) self.retranslateUi(CanardPreferencesDialog) self.tabWidget.setCurrentIndex(0) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), CanardPreferencesDialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), CanardPreferencesDialog.reject) QtCore.QMetaObject.connectSlotsByName(CanardPreferencesDialog)
LegoStormtroopr/canard
[ 13, 4, 13, 10, 1368350533 ]
def setup(): print("SETUP")
nanounanue/pipeline-template
[ 5, 8, 5, 1, 1489206972 ]
def formatFrameToTime(start, current, frameRate): total = current - start seconds = float(total) / float(frameRate) minutes = int(seconds / 60.0) seconds -= minutes * 60 return ":".join(["00", str(minutes).zfill(2), str(round(seconds, 1)).zfill(2), str(int(current)).zfill(2)])
dsparrow27/zoocore
[ 3, 2, 3, 2, 1485309529 ]
def __init__(self, protocol): self.protocol = protocol self.calls = WeakSet() self.loops = WeakSet()
piqueserver/piqueserver
[ 165, 59, 165, 87, 1482889715 ]
def call_end(self, *arg, **kw): call = self.protocol.call_end(*arg, **kw) self.calls.add(call) return call
piqueserver/piqueserver
[ 165, 59, 165, 87, 1482889715 ]
def __init__(self, meaning, glue, indices=None): if not indices: indices = set()
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def applyto(self, arg): """ self = (\\x.(walk x), (subj -o f)) arg = (john , subj) returns ((walk john), f) """ if self.indices & arg.indices: # if the sets are NOT disjoint raise linearlogic.LinearLogicApplicationException, "'%s' applied to '%s'. Indices are not disjoint." % (self, arg) else: # if the sets ARE disjoint return_indices = (self.indices | arg.indices) try: return_glue = linearlogic.ApplicationExpression(self.glue, arg.glue, arg.indices) except linearlogic.LinearLogicApplicationException: raise linearlogic.LinearLogicApplicationException, "'%s' applied to '%s'" % (self.simplify(), arg.simplify()) arg_meaning_abstracted = arg.meaning if return_indices: for dep in self.glue.simplify().antecedent.dependencies[::-1]: # if self.glue is (A -o B), dep is in A.dependencies arg_meaning_abstracted = self.make_LambdaExpression(logic.Variable('v%s' % dep), arg_meaning_abstracted) return_meaning = self.meaning.applyto(arg_meaning_abstracted) return self.__class__(return_meaning, return_glue, return_indices)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def make_VariableExpression(self, name): return logic.VariableExpression(name)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def make_LambdaExpression(self, variable, term): return logic.LambdaExpression(variable, term)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def lambda_abstract(self, other): assert isinstance(other, GlueFormula) assert isinstance(other.meaning, logic.AbstractVariableExpression) return self.__class__(self.make_LambdaExpression(other.meaning.variable, self.meaning), linearlogic.ImpExpression(other.glue, self.glue))
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def simplify(self): return self.__class__(self.meaning.simplify(), self.glue.simplify(), self.indices)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __str__(self): assert isinstance(self.indices, set) accum = '%s : %s' % (self.meaning, self.glue) if self.indices: accum += ' : {' + ', '.join([str(index) for index in self.indices]) + '}' return accum
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __repr__(self): return str(self)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __init__(self, filename): self.filename = filename self.read_file()
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def read_file(self, empty_first=True): if empty_first: self.clear() try: f = nltk.data.find( os.path.join('grammars', 'sample_grammars', self.filename)) # if f is a ZipFilePathPointer or a FileSystemPathPointer # then we need a little extra massaging if hasattr(f, 'open'): f = f.open() except LookupError, e: try: f = open(self.filename) except LookupError: raise e lines = f.readlines() f.close() for line in lines: # example: 'n : (\\x.(<word> x), (v-or))' # lambdacalc -^ linear logic -^ line = line.strip() # remove trailing newline if not len(line): continue # skip empty lines if line[0] == '#': continue # skip commented out lines parts = line.split(' : ', 2) # ['verb', '(\\x.(<word> x), ( subj -o f ))', '[subj]']
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __str__(self): accum = '' for pos in self: for relset in self[pos]: i = 1 for gf in self[pos][relset]: if i==1: accum += str(pos) + ': ' else: accum += ' '*(len(str(pos))+2) accum += str(gf) if relset and i==len(self[pos][relset]): accum += ' : ' + str(relset) accum += '\n' i += 1 return accum
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def lookup(self, node, depgraph, counter): semtype_names = self.get_semtypes(node)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def add_missing_dependencies(self, node, depgraph): rel = node['rel'].lower()
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def _lookup_semtype_option(self, semtype, node, depgraph): relationships = frozenset([depgraph.nodelist[dep]['rel'].lower() for dep in node['deps'] if depgraph.nodelist[dep]['rel'].lower() not in OPTIONAL_RELATIONSHIPS])
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_semtypes(self, node): """ Based on the node, return a list of plausible semtypes in order of plausibility. """ semtype_name = None
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_glueformulas_from_semtype_entry(self, lookup, word, node, depgraph, counter): glueformulas = [] glueFormulaFactory = self.get_GlueFormula_factory() for meaning, glue in lookup: gf = glueFormulaFactory(self.get_meaning_formula(meaning, word), glue) if not len(glueformulas): gf.word = word else: gf.word = '%s%s' % (word, len(glueformulas)+1) gf.glue = self.initialize_labels(gf.glue, node, depgraph, counter.get()) glueformulas.append(gf) return glueformulas
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def initialize_labels(self, expr, node, depgraph, unique_index): if isinstance(expr, linearlogic.AtomicExpression): name = self.find_label_name(expr.name.lower(), node, depgraph, unique_index) if name[0].isupper(): return linearlogic.VariableExpression(name) else: return linearlogic.ConstantExpression(name) else: return linearlogic.ImpExpression( self.initialize_labels(expr.antecedent, node, depgraph, unique_index), self.initialize_labels(expr.consequent, node, depgraph, unique_index))
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_label(self, node): """ Pick an alphabetic character as identifier for an entity in the model.
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def lookup_unique(self, rel, node, depgraph): """ Lookup 'key'. There should be exactly one item in the associated relation. """ deps = [depgraph.nodelist[dep] for dep in node['deps'] if depgraph.nodelist[dep]['rel'].lower() == rel.lower()]
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_GlueFormula_factory(self): return GlueFormula
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __init__(self, semtype_file=None, remove_duplicates=False, depparser=None, verbose=False): self.verbose = verbose self.remove_duplicates = remove_duplicates self.depparser = depparser
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def train_depparser(self, depgraphs=None): if depgraphs: self.depparser.train(depgraphs) else: self.depparser.train_from_file(nltk.data.find( os.path.join('grammars', 'sample_grammars', 'glue_train.conll')))
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def parse_to_meaning(self, sentence): readings = [] for agenda in self.parse_to_compiled(sentence): readings.extend(self.get_readings(agenda)) return readings
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_readings(self, agenda): readings = [] agenda_length = len(agenda) atomics = dict() nonatomics = dict() while agenda: # is not empty cur = agenda.pop() glue_simp = cur.glue.simplify() if isinstance(glue_simp, linearlogic.ImpExpression): # if cur.glue is non-atomic for key in atomics: try: if isinstance(cur.glue, linearlogic.ApplicationExpression): bindings = cur.glue.bindings else: bindings = linearlogic.BindingDict() glue_simp.antecedent.unify(key, bindings) for atomic in atomics[key]: if not (cur.indices & atomic.indices): # if the sets of indices are disjoint try: agenda.append(cur.applyto(atomic)) except linearlogic.LinearLogicApplicationException: pass except linearlogic.UnificationException: pass try: nonatomics[glue_simp.antecedent].append(cur) except KeyError: nonatomics[glue_simp.antecedent] = [cur]
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def _add_to_reading_list(self, glueformula, reading_list): add_reading = True if self.remove_duplicates: for reading in reading_list: try: if reading.equiv(glueformula.meaning, self.prover): add_reading = False break; except Exception, e: #if there is an exception, the syntax of the formula #may not be understandable by the prover, so don't #throw out the reading. print 'Error when checking logical equality of statements', e pass if add_reading: reading_list.append(glueformula.meaning)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def parse_to_compiled(self, sentence='a man sees Mary'): gfls = [self.depgraph_to_glue(dg) for dg in self.dep_parse(sentence)] return [self.gfl_to_compiled(gfl) for gfl in gfls]
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def dep_parse(self, sentence='every cat leaves'): #Lazy-initialize the depparser if self.depparser is None: self.depparser = MaltParser(tagger=self.get_pos_tagger()) if not self.depparser._trained: self.train_depparser() return [self.depparser.parse(sentence, verbose=self.verbose)]
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def depgraph_to_glue(self, depgraph): return self.get_glue_dict().to_glueformula_list(depgraph)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_glue_dict(self): return GlueDict(self.semtype_file)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def gfl_to_compiled(self, gfl): index_counter = Counter() return_list = [] for gf in gfl: return_list.extend(gf.compile(index_counter))
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_pos_tagger(self): regexp_tagger = RegexpTagger( [(r'^-?[0-9]+(.[0-9]+)?$', 'CD'), # cardinal numbers (r'(The|the|A|a|An|an)$', 'AT'), # articles (r'.*able$', 'JJ'), # adjectives (r'.*ness$', 'NN'), # nouns formed from adjectives (r'.*ly$', 'RB'), # adverbs (r'.*s$', 'NNS'), # plural nouns (r'.*ing$', 'VBG'), # gerunds (r'.*ed$', 'VBD'), # past tense verbs (r'.*', 'NN') # nouns (default) ]) brown_train = brown.tagged_sents(categories='news') unigram_tagger = UnigramTagger(brown_train, backoff=regexp_tagger) bigram_tagger = BigramTagger(brown_train, backoff=unigram_tagger) trigram_tagger = TrigramTagger(brown_train, backoff=bigram_tagger)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __init__(self, meaning, glue, indices=None): if not indices: indices = set() if isinstance(meaning, str): self.meaning = drt.DrtParser().parse(meaning) elif isinstance(meaning, drt.AbstractDrs): self.meaning = meaning else: raise RuntimeError, 'Meaning term neither string or expression: %s, %s' % (meaning, meaning.__class__)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def make_VariableExpression(self, name): return drt.DrtVariableExpression(name)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def make_LambdaExpression(self, variable, term): return drt.DrtLambdaExpression(variable, term)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def get_GlueFormula_factory(self): return DrtGlueFormula
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __init__(self, semtype_file=None, remove_duplicates=False, depparser=None, verbose=False): if not semtype_file: semtype_file = 'drt_glue.semtype' Glue.__init__(self, semtype_file, remove_duplicates, depparser, verbose)
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def demo(show_example=-1): examples = ['David sees Mary', 'David eats a sandwich', 'every man chases a dog', 'every man believes a dog sleeps', 'John gives David a sandwich', 'John chases himself']
markgw/jazzparser
[ 5, 1, 5, 1, 1368367354 ]
def __str__(self) -> str: return str(self.dict())
declension/squeeze-alexa
[ 60, 20, 60, 27, 1483607926 ]
def __init__(self): # Set the instance-level things: for k, v in type(self).__dict__.items(): if not k.startswith('_') and k not in Settings.__dict__: setattr(self, k.lower(), v)
declension/squeeze-alexa
[ 60, 20, 60, 27, 1483607926 ]
def human_log(callback, host, res): if hasattr(res, 'startswith'): if callback == 'runner_on_unreachable': print('-----> ERROR: {host} was unreachable'.format(host=host)) print('\n'.join([' %s' % line for line in res.splitlines()])) elif type(res) == type(dict()): for field in FIELDS: if field in res.keys(): print('-----> {host} [|] {cmd} [|] {field}'.format( host=host, cmd=res['cmd'], field=field)) lines = res[field].splitlines() print('\n'.join([' %s' % line for line in lines]))
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def on_any(self, *args, **kwargs): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def runner_on_ok(self, host, res): human_log('runner_on_ok', host, res)
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def runner_on_skipped(self, host, item=None): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def runner_on_no_hosts(self): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def runner_on_async_ok(self, host, res, jid): human_log('runner_on_async_ok', host, res)
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def playbook_on_start(self): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def playbook_on_no_hosts_matched(self): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def playbook_on_task_start(self, name, is_conditional): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def playbook_on_setup(self): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def playbook_on_not_import_for_host(self, host, missing_file): pass
soarpenguin/python-scripts
[ 63, 40, 63, 1, 1397484324 ]
def parse_datetime(s: str) -> datetime.datetime: return iso8601.parse_date(s).replace(tzinfo=None)
sfu-fas/coursys
[ 61, 17, 61, 39, 1407368110 ]
def add_arguments(self, parser): parser.add_argument('offering_slug', type=str, help='CourseOffering slug') parser.add_argument('activity_slug', type=str, help='the slug of the Activity with the quiz') parser.add_argument('section', type=str, help='lab/tutorial section to modify') parser.add_argument('start_time', type=parse_datetime, help='start time for this section') parser.add_argument('end_time', type=parse_datetime, help='end time for this section')
sfu-fas/coursys
[ 61, 17, 61, 39, 1407368110 ]
def GetName(self): return "SFM10"
turdusmerula/kicad-plugins
[ 3, 1, 3, 1, 1489351432 ]
def GetValue(self): return "SFM10"
turdusmerula/kicad-plugins
[ 3, 1, 3, 1, 1489351432 ]
def CheckParameters(self): self.CheckParamInt( "Pads", '*' + self.pad_num_pads_horz_key, is_multiple_of=2)
turdusmerula/kicad-plugins
[ 3, 1, 3, 1, 1489351432 ]
def GetPad(self, rot_degree=0): pad_length = self.parameters["Pads"][self.pad_length_key] pad_width = self.parameters["Pads"][self.pad_width_key] pad_handsolder = self.parameters["Pads"][self.pad_handsolder_key]
turdusmerula/kicad-plugins
[ 3, 1, 3, 1, 1489351432 ]
def BuildThisFootprint(self):
turdusmerula/kicad-plugins
[ 3, 1, 3, 1, 1489351432 ]
def __init__(self, timeout=5, attempts=3): self._timeout = timeout self._attempts = attempts self._transaction_id = b""
xmikos/qopenvpn
[ 36, 11, 36, 6, 1360971075 ]
def _generate_id(self): """Generate random Transaction ID""" return os.urandom(16)
xmikos/qopenvpn
[ 36, 11, 36, 6, 1360971075 ]
def _parse_response(self, data): """Parse server response to get mapped address""" packet_type, length = struct.unpack(">2H", data[:4]) if packet_type != BINDING_RESPONSE: raise ValueError("Invalid response type!") if data[4:20] != self._transaction_id: raise ValueError("Invalid response transaction ID!") # Walk through all response attributes to find MAPPED_ADDRESS for attr_id, value_length, value, start_offset in self._parse_attributes(data[20:length + 20]): if attr_id == MAPPED_ADDRESS: ip_address, port = self._parse_mapped_address(value) break return (ip_address, port)
xmikos/qopenvpn
[ 36, 11, 36, 6, 1360971075 ]
def _parse_mapped_address(self, value): """Get IP address and port from MAPPED_ADDRESS attribute""" family, recv_port = struct.unpack(">xBH", value[:4]) if family != FAMILY_IPV4: raise ValueError("IPv6 is not supported!") ip_address = socket.inet_ntoa(value[4:]) return (ip_address, recv_port)
xmikos/qopenvpn
[ 36, 11, 36, 6, 1360971075 ]
def __init__(self,waitTime): self.waitTime = waitTime threading.Thread.__init__(self)
surajshanbhag/Indoor_SLAM
[ 11, 7, 11, 1, 1492211651 ]
def right(): global rightC rightC += 1 print "right: ",rightC,"\t","left :",leftC
surajshanbhag/Indoor_SLAM
[ 11, 7, 11, 1, 1492211651 ]
def checkArgs(): global IP,host if(len(sys.argv)!=1): IP = sys.argv[1] host = sys.argv[2]
surajshanbhag/Indoor_SLAM
[ 11, 7, 11, 1, 1492211651 ]
def render_aspect_ratio(aspect_ratio, use_default=False): ''' Returns the aspect ratio if one is defined for the source, otherwise if defaults are accepted a default value of 1.0 is returned or else a ValueError is raised :param float aspect_ratio: Ratio of along strike-length to down-dip width of the rupture :param bool use_default: If true, when aspect_ratio is undefined will return default value of 1.0, otherwise will raise an error. ''' if aspect_ratio: assert aspect_ratio > 0. return aspect_ratio else: if use_default: return 1.0 else: raise ValueError('Rupture aspect ratio not defined!')
gem/oq-hazardlib
[ 23, 49, 23, 9, 1323944086 ]
def npd_to_pmf(nodal_plane_dist, use_default=False): """ Returns the nodal plane distribution as an instance of the PMF class """ if isinstance(nodal_plane_dist, PMF): # Aready in PMF format - return return nodal_plane_dist else: if use_default: return PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))]) else: raise ValueError('Nodal Plane distribution not defined')
gem/oq-hazardlib
[ 23, 49, 23, 9, 1323944086 ]