repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
sidzan/netforce
netforce_support/netforce_support/models/report_issue.py
Python
mit
2,805
0.012834
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
time.strptime(s,"%Y-%m-%d %H:%M:%S") return time.mktime(d.timetuple()) * 1000 def js_date(s): d=datetime.strptime(s,"%Y-%m-%d") return time.mktime(d.timetuple()) * 1000 class ReportIssue(Model): _name = "report.issue" _store = False def get_issue_chart(self, context={}): actions=[] ...
tions.append((issue.date_created,"open")) if issue.state=="closed" and issue.date_closed: actions.append((issue.date_closed,"close")) actions.sort() values=[] num_issues=0 for d,action in actions: if action=="open": num_issues+=1 ...
bailey-lab/graphSourceCode
scripts/etags.py
Python
gpl-3.0
316
0.012658
#!/usr/bin/python import o
s path = os.path.join(os.path.dirname(__file__), "../") path = os.path.abspath(path) regex = '-regex ".*\.[cChH]\(pp\)?"' exclude = '-not -path "*/external/*" -not -name "*#*"' cmd = 'find {p} {r} {e} -print | xargs etags '.format
(p=path, e=exclude, r=regex) print cmd os.system(cmd)
drnextgis/QGIS
python/plugins/processing/algs/otb/maintenance/OTBTester.py
Python
gpl-2.0
17,027
0.001879
# -*- coding: utf-8 -*- """ *************************************************************************** OTBTester.py --------------------- Copyright : (C) 2013 by CS Systemes d'information (CS SI) Email : otb at c-s dot fr (CS SI) Contributors : Julien Malik (CS SI...
lse: values = ct new_env[key] = values for stringcommand in stringcommands: key = stringcommand.body[-1].contents ct = stringcommand.body[-2].contents ct = mini_clean(ct.lower()) if "$" in ct: values = LowerTemplate(c...
new_env[key] = values resolve_dict(environment, new_env) environment.update(new_env) return environment def get_apps(self, the_makefile, the_dict): with open(the_makefile) as f: input = f.read() output = parse(input) apps = [each for each in output...
MVReddy/WhenPy
when.py
Python
bsd-3-clause
22,733
0.000044
# -*- coding: utf-8 -*- """ Friendly Dates and Times """ # Disable pylint's invalid name warning. 'tz' is used in a few places and it # should be the only thing causing pylint to include the warning. # pylint: disable-msg=C0103 import calendar import datetime import locale import os import pytz import random # Some...
Date in locale-based format. .. data:: when.formats.DATETIME Date and time in locale-based format. .. data:: when.formats.TIME Time in locale-based format. .. data:: when.formats.TIME_AMPM 12-hour time in locale-based format. :param value: A d
atetime object. :type value: datetime.datetime, datetime.date, datetime.time. :param format_string: A string specifying formatting the directives or to use. :type format_string: str. :returns: str -- the formatted datetime. :raises: AssertionError .. versionadded:: 0.3...
bbsan2k/nzbToMedia
nzbToMylar.py
Python
gpl-3.0
3,087
0.011986
#!/usr/bin/env python2 # coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to Mylar. # # This script sends the download to your automated media management servers. # # NOTE: This sc...
e has changed status. #myswait_for=1 # Mylar watch directory. # # set
this to where your Mylar completed downloads are. #mywatch_dir= # Mylar and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. #myremote_path=0 ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice com...
compiteing/flask-ponypermission
venv/lib/python2.7/site-packages/pony/orm/tests/test_core_find_in_cache.py
Python
mit
6,105
0.00475
from __future__ import absolute_import, print_function, division import unittest from pony.orm.tests.testutils import raises_exception from pony.orm import * db = Database('sqlite', ':memory:') class AbstractUser(db.Entity): username = PrimaryKey(unicode) class User(AbstractUser): diagrams = Set...
subuser1'] finally: self.assertEqual(last_sql, db.last_sql) def test_user_6(self): u1 = SubUser1['subuser1'] last_sql = db.last_sql u2 = SubUser1['subuser1'] self.assertEqual(last_sql, db.last_sql) self.assertEqual(u1, u2) def test_user_7(se...
ser1['subuser1'] u1.delete() last_sql = db.last_sql u2 = SubUser1.get(username='subuser1') self.assertEqual(last_sql, db.last_sql) self.assertEqual(u2, None) def test_user_8(self): u1 = SubUser1['subuser1'] last_sql = db.last_sql u2 = SubUser1...
rockwotj/shiloh-ranch
backend/utils/deletions.py
Python
mit
543
0.001842
from datetime import datet
ime from google.appengine.ext import ndb from models import Deletion from utils import updates def get_key(slug): return ndb.Key("Deletion", slug) def delete_entity(key): slug = key.string_id() kind = key.kind() key.delete() deletion_key = get_key(slug) deletion = Deletion(k...
_delete_time(deletion.time_added)
sorenh/python-django-cloudslave
cloudslave/migrations/0001_initial.py
Python
apache-2.0
6,224
0.007069
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Cloud' db.create_table(u'cloudslave_cloud', ( ('name', self.gf('django.db.models...
.CharField')(max_length=200)), ('state', self.gf('django.db.models.fields.CharField')(max_length=15, null=True, blank=True)),
)) db.send_create_signal(u'cloudslave', ['Slave']) def backwards(self, orm): # Removing unique constraint on 'KeyPair', fields ['cloud', 'name'] db.delete_unique(u'cloudslave_keypair', ['cloud_id', 'name']) # Deleting model 'Cloud' db.delete_table(u'cloudslave_clou...
pioneers/forseti
wxdash.py
Python
apache-2.0
10,763
0.00288
#!/usr/bin/python2.7 from __future__ import print_function # -*- coding: utf-8 -*- import wx import threading import lcm import random import Forseti import configurator BLUE = (24, 25, 141) GOLD = (241, 169, 50) class TeamPanel(wx.Panel): def __init__(self, remote, letter, number, name, colour, *args, **kwargs...
panel, 0) for panel in self.team_panels]) vbox.Add(teamSizer, flag=wx.CENTER) buttons = wx.BoxSizer(wx.HORIZONTAL) self.init_button = wx.Button(self, label='Init') self.init_button.Bind(wx.EVT_BUTTON, self.do_init) self.go_button = wx.
Button(self, label='GO!') self.go_button.Bind(wx.EVT_BUTTON, self.do_go) self.pause_button = wx.Button(self, label='Pause') self.pause_button.Bind(wx.EVT_BUTTON, self.do_pause) #self.save_button = wx.Button(self, label='Save') #self.save_button.Bind(wx.EVT_BUTTON, self.do_save) ...
nico202/pyNeMo
libs/pySpike.py
Python
gpl-2.0
5,430
0.005893
#!/bin/python2 """ ##################################### # iSpike-like joint conversion # ##################################### """ class sensNetIn(): #TODO: explain XD ''' This object gets as input and returns as output: ''' from sys import exit def __init__(self, ...
) )) return current_input class sensNetOut(): def __init__(self, neuron_idx, min_angle=-90, #The minimum angle to read max_angle=90, #The maximum angle to read decay_rate=0.25, #The rate of decay of the angle variables ...
ED!? #Increment of the input current to the neurons by each spike current_increment=10, dof=0, #Degree of freedom of joint. FIXME: NOT USED integration_steps=1 #Step after which integration occurs (1step = 1ms) ): self.neuron_i...
LabKey/argos_nlp
fhcrc_pathology/SecondaryField.py
Python
apache-2.0
3,282
0.012492
'''author@esilgard''' # #
Copyright (c) 2015-2016 Fred Hutchinson Cancer Research Center # # Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 # import re, os import global_strings as gb PATH = os.path.dirname(os.path.realpath(__file__)) + os.path.sep class SecondaryField(ob
ject): ''' extract the value of a field which is dependant on another value ''' __version__ = 'SecondaryField1.0' def __init__(self): self.field_name = 'Default' standardization_dictionary = {} self.return_d = {} ## variable window sizes based on primary field string...
nocarryr/blender-scripts
multicam_tools/multicam.py
Python
gpl-2.0
11,734
0.006051
import bpy from .utils import MultiCamContext class MultiCamFadeError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return repr(self.msg) class BlendObj(object): def __init__(self, **kwargs): self.children = set() p = self.parent = kwargs.g...
'start':{}, 'end':{}} start_frame = No
ne try: for key, prop in prop_iters.items(): frame, value = next(prop) if start_frame is None: start_frame = frame elif frame != start_frame: raise MultiCamFadeError('keyframes are not...
BirkbeckCTP/janeway
src/identifiers/migrations/0004_auto_20170921_1113.py
Python
agpl-3.0
750
0.001333
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-21 11:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('submission', '0011_auto_20170921_0937'), ('identifi...
_name='brokendoi', name='article', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='submission.Article'), preserve_default=False,
), ]
klmitch/pbr
pbr/tests/test_packaging.py
Python
apache-2.0
28,790
0.000278
# Copyright (c) 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL AURA BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CON
SEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS import email import email.errors import imp import os import re import sysconfig import tempfile import textwrap import fixtures import mock import pkg_resources import six import testtools from testtools import mat...
JamesMura/sentry
src/sentry/utils/sms.py
Python
bsd-3-clause
976
0.001025
from __future__ import absolute_import import logging import requests
from six.moves.urllib.parse import quote from sentry import options logger = logging.getLogger(__name__) def sms_available(): return bool(options.get('sms.twilio-account')) def send_sms(body, to, from_=None): account = options.get('sms.twilio-accoun
t') if not account: raise RuntimeError('SMS backend is not configured.') if account[:2] != 'AC': account = 'AC' + account url = 'https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json' % \ quote(account) rv = requests.post(url, auth=(account, opt...
gogoair/foremast
src/foremast/awslambda/api_gateway_event/__init__.py
Python
apache-2.0
661
0
# F
oremast - Pipeline Tooling # # Copyright 2018 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .api_gateway_event import *
detialiaj/pro
SYS/main/migrations/0010_auto_20160807_1508.py
Python
mit
771
0.001297
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-08-07 13:08 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('main', '0009_remove_item_last_modified'...
.AddField( model_name='item', name='status', field=models.BooleanFiel
d(default=True), ), ]
DavidLP/home-assistant
tests/components/dyson/test_air_quality.py
Python
apache-2.0
5,733
0
"""Test the Dyson air quality component.""" import json from unittest import mock import asynctest from libpurecool.dyson_pure_cool import DysonPureCool from libpurecool.dyson_pure_state_v2 import DysonEnvironmentalSensorV2State import homeassistant.components.dyson.air_quality as dyson from homeassistant.components ...
"hact": "0040", "va10": "0055", "p25r": "0161", "noxl": "0069", "pm25": "0035", "sltm": "OFF", "tact": "2960" } } device.environmental_state = \ DysonEnvironmentalSensorV2State(json.dumps(event)) for call in devic...
_args_list: callback = call[0][0] if type(callback.__self__) == dyson.DysonAirSensor: callback(device.environmental_state) await hass.async_block_till_done() fan_state = hass.states.get("air_quality.living_room") attributes = fan_state.attributes assert fan_state.state == '...
airbnb/streamalert
streamalert_cli/test/handler.py
Python
apache-2.0
22,898
0.002533
""" Copyright 2017-present Airbnb, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
d. See the License for the specific language governing permissions and limitations under the License. """ import argparse import os import jmespath from mock import patch, MagicMock from streamalert.alert_processor import main as alert_processor from streamalert.alert_processor.helpers import compose_alert from strea...
Dispatcher from streamalert.classifier import classifier from streamalert.rules_engine import rules_engine from streamalert.shared import rule from streamalert.shared.config import ConfigError from streamalert.shared.logger import get_logger from streamalert.shared.stats import RuleStatisticTracker from streamalert_cli...
Heufneutje/txircd
txircd/modules/rfc/cmd_whowas.py
Python
bsd-3-clause
4,564
0.027607
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import durationToSeconds, ipAddressToShow, ircLower, now from zope.interface import implementer from...
name") return None return { "nick": lowerParam, "param": params[0] } def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool: nick = data["nick"] allWhowas = self.ircd.storage["whowas"] whowasEntries = allWhowas[nick] whowasEntries = self.removeOldEntries(whowasEntries) if not whowasE...
") return True allWhowas[nick] = whowasEntries # Save back to the list excluding the removed entries self.ircd.storage["whowas"] = allWhowas for entry in whowasEntries: entryNick = entry["nick"] user.sendMessage(irc.RPL_WHOWASUSER, entryNick, entry["ident"], entry["host"], "*", entry["gecos"]) if self...
hradec/gaffer
python/GafferArnold/__init__.py
Python
bsd-3-clause
2,708
0.011078
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
lugs, this ensur
es that the bindings # are always loaded for these, even if people only import GafferArnold __import__( "GafferOSL" ) try : # Make sure we import _GafferArnold _without_ RTLD_GLOBAL. This prevents # clashes between the LLVM symbols in libai.so and the Mesa OpenGL driver. # Ideally we wouldn't use RTLD_GLOBAL anywh...
immstudios/nebula-core
nebulacore/meta_utils.py
Python
gpl-3.0
1,789
0.002236
import re from nxtools import * from .common import * def shorten(instr, nlen): line = instr.split("\n")[0] if len(line) < 100: return line return line[:nlen] + "..." de
f filter_match(f, r): """OR""" if type(f) in [list, tuple]: res = False for fl in f: if re.match(fl, r): return True return False else: return re.match(f, r) def tree_indent(data): has_children = False for i, row in enumerate(data):
value = row["value"] depth = len(value.split(".")) parentindex = None for j in range(i - 1, -1, -1): if value.startswith(data[j]["value"] + "."): parentindex = j data[j]["has_children"] = True break if parentindex is None:...
mattsmart/biomodels
transcriptome_clustering/baseline_reconstruction_error.py
Python
mit
7,422
0.004042
import matplotlib.pyplot as plt import numpy as np import os from inference import error_fn, infer_interactions, choose_J_from_general_form, solve_true_covariance_from_true_J from pitchfork_langevin import jacobian_pitchfork, gen_multitraj, steadystate_pitchfork from settings import DEFAULT_PARAMS, FOLDER_OUTPUT, TAU ...
assert mod in [
'num_traj', 'num_steps'] num_traj_set = [int(a) for a in np.linspace(10, 600, 6)] num_steps_set = [int(a) for a in np.linspace(10, 2000, 5)] param_vary_set = {'num_traj': num_traj_set, 'num_steps': num_steps_set}[mod] true_errors_mid = np.zeros(len(param_vary_set)) true_errors_...
tchellomello/home-assistant
homeassistant/components/comfoconnect/sensor.py
Python
apache-2.0
9,175
0.000109
"""Platform to control a Zehnder ComfoAir Q350/450/600 ventilation unit.""" import logging from pycomfoconnect import ( SENSOR_BYPASS_STATE, SENSOR_DAYS_TO_REPLACE_FILTER, SENSOR_FAN_EXHAUST_DUTY, SENSOR_FAN_EXHAUST_FLOW, SENSOR_FAN_EXHAUST_SPEED, SENSOR_FAN_SUPPLY_DUTY, SENSOR_FAN_SUPPLY_F...
ensor( name=f"{ccb.name} {SENSOR_TYPES[resource][ATTR_LABEL]}", ccb=ccb, sensor_type=resource, ) ) add_entities(sensors, True) class ComfoConnectSensor(Entity): """Representation of a ComfoConnect sensor.""" def __init__(self, name, ccb...
Initialize the ComfoConnect sensor.""" self._ccb = ccb self._sensor_type = sensor_type self._sensor_id = SENSOR_TYPES[self._sensor_type][ATTR_ID] self._name = name async def async_added_to_hass(self): """Register for sensor updates.""" _LOGGER.debug( "Reg...
Erechtheus/geolocation
predictText.py
Python
gpl-3.0
1,245
0.013655
#Minimal example for running location prediction from keras.models import load_model import pickle from keras.preprocessing.sequence import pad_sequences import numpy as np import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" binaryPath= 'data/binaries/' ...
eversed(predict.args
ort()[0][-5:]): print("%s with score=%.3f" % (colnames[index], float(predict[0][index])) )
bkolli/swift
test/unit/proxy/controllers/test_container.py
Python
apache-2.0
9,332
0
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
qual(context['headers']['x-timestamp'], '1.0') def test_sys_meta_headers_POST(self): # check that headers in sys meta namespace make it through # the container controller sys_meta_key = '%stest' % get_sys_meta_prefix('container')
sys_meta_key = sys_meta_key.title() user_meta_key = 'X-Container-Meta-Test' controller = proxy_server.ContainerController(self.app, 'a', 'c') context = {} callback = self._make_callback_func(context) hdrs_in = {sys_meta_key: 'foo', user_meta_key: 'bar', ...
bnbowman/BifoAlgo
src/Chapter1/Sec3_PatternMatching.py
Python
gpl-2.0
627
0.041467
#! /usr/bin/env python3 def find_locations( sequence_file, pattern ): """ Find the most common kmers of a given size in a given text """ sequence = parse_sequence_file( sequence_file ) k = len(pattern) for i in range(len(sequence)-k+1): if sequenc
e[i:i+k] == pattern: yield i def parse_sequence_file( sequence_file ): seq = '' with open(sequence_file) as handle: for line in handle: seq += line.strip() return seq if __name__ == '__main__': import sys
sequence_file = sys.argv[1] pattern = sys.argv[2] starts = list(find_locations(sequence_file, pattern)) print(' '.join([str(s) for s in starts]))
scheib/chromium
tools/perf/contrib/cluster_telemetry/ct_benchmarks_unittest.py
Python
bsd-3-clause
4,992
0.013021
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from optparse import OptionParser import unittest import six from telemetry.page import shared_page_state from contrib.cluster_telemetry import rasterize_...
list'", str(e)) else:
self.assertEquals( "'OptionParser' object has no attribute 'urls_list'", str(e)) # Now add an empty urls_list. parser.urls_list = '' benchmark.ProcessCommandLineArgs(self.mock_parser, parser) self.assertEquals('Please specify --urls-list.', self.mock_parser.err_msg)
jtauber/ultima4
shapes.py
Python
mit
800
0
EGA2RGB = [ (0x00, 0x00, 0x00), (0x00, 0x00, 0xAA), (0x00, 0xAA, 0x00), (0x0
0, 0xAA, 0xAA), (0xAA, 0x00, 0x00), (0xAA, 0x00, 0xAA), (0xAA, 0x55, 0x00), (0xAA, 0xAA, 0xAA), (0x55, 0x55, 0x55), (0x55, 0x55, 0xFF), (0x55, 0xFF, 0x55), (0x55, 0xFF, 0xFF), (0xFF, 0x55, 0x55), (0xFF, 0x55, 0xFF), (0xFF, 0xFF, 0x55), (0xFF, 0xFF, 0xFF), ] def load_sha...
in range(16): for k in range(8): d = ord(bytes[k + 8 * j + 128 * i]) a, b = divmod(d, 16) shape.append(EGA2RGB[a]) shape.append(EGA2RGB[b]) shapes.append(shape) return shapes
personal-robots/sar_social_stories
src/ss_script_handler.py
Python
mit
43,375
0.00302
# Jacqueline Kory Westlund # May 2016 # # The MIT License (MIT) # # Copyright (c) 2016 Personal Robots Group # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including w...
A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OT
HERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys # For getting generic exception info import datetime # For getting time deltas for timeouts import time # For sleep import json # For packing ros message properties import random # For picking ...
Phonemetra/TurboCoin
test/functional/interface_rpc.py
Python
mit
2,668
0.001124
#!/usr/bin/env python3 # Copyright (c) 2018-2019 TurboCoin # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Tests some generic aspects of the RPC interface.""" from test_framework.authproxy import JSONRPCException from test_fram...
fcn, *args): try: fcn(*args) raise AssertionError("Expected RPC error %d, got none" % expected_rpc_code) except JSON
RPCException as exc: assert_equal(exc.error["code"], expected_rpc_code) assert_equal(exc.http_status, expected_http_status) class RPCInterfaceTest(TurbocoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True def test_getrpcinfo(self): ...
pspacek/freeipa
ipatests/test_ipalib/test_frontend.py
Python
gpl-3.0
39,007
0.001077
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, ei...
LE_FLAG rule = frontend.rule def my_func(): pass assert not hasattr(my_func, flag) rule(my_func) assert getattr(my_func, flag) is True @rule def my_fu
nc2(): pass assert getattr(my_func2, flag) is True def test_is_rule(): """ Test the `ipalib.frontend.is_rule` function. """ is_rule = frontend.is_rule flag = frontend.RULE_FLAG class no_call(object): def __init__(self, value): if value is not None: ...
hy-2013/scrapy
tests/test_spidermiddleware_referer.py
Python
bsd-3-clause
639
0.001565
from unittest import TestCase from scrapy.http import Response, Request from scrapy.spider import Spider from scrapy.contrib.spidermiddleware.referer import RefererMiddleware class TestRefererMiddleware(TestCase): def setUp(self): self.spider = Spider('foo') self.mw = RefererMiddleware() de...
] out = list(self.mw.process_spider_output(res, reqs, self.spider)) self.assertEquals(out[0].headers.get('Referer'), 'http:/
/scrapytest.org')
bravesnow/nurbspy
assistlib/ode.py
Python
gpl-2.0
937
0.029883
#coding: cp936 #³£Î¢·Ö·½³Ì(ordinary differential equation)Çó½âÖ®¸Ä½øµÄÅ·À­·¨dy=f*dx import numpy as np def odeiem(f, y0, x): #for: f(x, y) '''fÊÇ΢·Ö·½³Ì£¬y0ÊdzõÖµ£¬xÊǸø¶¨µÄÐòÁУ¬×¢Òâf(x,y)º¯ÊýµÄ²ÎÊý˳ÐòÊÇxÓëy''' y = np.array([y0]) for i in xrange(len(x)-1):
h = x[i+1]-x[i] yp = y[i,:]+h*f(x[i],y[i]) yc = y[i,:]+h/2*(f(x[i],y[i])+f(x[i+1],yp)) y = np.vstack([y,yc]) return y def odeiems(f, y0, x): #for: f(x) '''fÊÇ΢·Ö·½³Ì£¬y0ÊdzõÖµ£¬xÊǸø¶¨µÄÐòÁУ¬×¢Òâf(x)´øÓÐΨһµÄ²ÎÊýx'''
y=np.array([y0]) for i in xrange(len(x)-1): h = x[i+1] - x[i] yc = y[i,:] + h/2 * (f(x[i]) + f(x[i+1])) y = np.vstack([y,yc]) return y if __name__=='__main__': f = lambda x, y: np.array([2*x, x, x**2]) #f(x, y) g = lambda x : np.array([2*x, x, x**2]) #f(x) print odeiem(f, ...
chrisxue815/leetcode_python
problems/test_0457_dfs_hashset.py
Python
unlicense
1,180
0
import unittest from typing import List import utils # O(n) time. O(n) space. DFS, hash set. class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: n = len(nums) for start, move in enumerate(nums): if move == 0: continue forward = move > 0 ...
= curr: break if nxt in visited: return True visited.add(nxt) curr = nxt return False class Test(unittest.TestCase): def test(self): cases = utils.load_test_json(__file__).test_cases for case in cas...
tion().circularArrayLoop(**case.args.__dict__) self.assertEqual(case.expected, actual, msg=args) if __name__ == '__main__': unittest.main()
mfil/getebook
getebook/epub.py
Python
isc
25,314
0.003713
# Copyright (c) 2015, Max Fillinger <max@max-fillinger.net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND...
nt for the guide. (Empty string if no guide title and type are given.)''' if self.guide_title and self.guide_type: return _make_xml_elem('reference', '', [ ('title', self.guide_title), ('type', self.guide_type), ('href', self.name...
, text, *args): '''The metadata entry is an XML element. *args is used for supplying the XML element's attributes as (key, value) pairs.''' self.tag = tag self.text = text self.attr = args def write_xml(self): 'Write the XML element.' return _make_xml_elem(sel...
mechaxl/mixer
mixer/backend/django.py
Python
bsd-3-clause
12,824
0.000468
""" Django support. """ from __future__ import absolute_import import datetime from os import path from types import GeneratorType import decimal from django import VERSION if VERSION < (1, 8): from django.contrib.contenttypes.generic import ( GenericForeignKey, GenericRelation) else: from django.cont...
d=None): if isinstance(value, GeneratorType): return self._get_value(name, next(value), field) if not isinstance(value, t.Mix) a
nd value is not SKIP_VALUE: if callable(value): return self._get_value(name, value(), field) if field: value = field.scheme.to_python(value) return name, value def gen_select(self, field_name, select): """ Select exists value from database....
ndp-systemes/odoo-addons
stock_procurement_split/__init__.py
Python
agpl-3.0
822
0
# -*- coding: utf8 -*- # # Copyright (C) 2017 NDP Systèmes (<http://www.ndp-systemes.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License,...
ut WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://w
ww.gnu.org/licenses/>. # from . import stock_procurement_split
juhalindfors/bazel-patches
tools/build_defs/pkg/make_rpm_test.py
Python
apache-2.0
3,259
0.006137
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
S" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for make_rpm.""" from __future__ import absolute_import from __future__ import division from __future__ import print_funct...
ile(filename, *contents): with open(filename, 'w') as text_file: text_file.write('\n'.join(contents)) def DirExists(dirname): return os.path.exists(dirname) and os.path.isdir(dirname) def FileExists(filename): return os.path.exists(filename) and not os.path.isdir(filename) def FileContents(filename): ...
andrecunha/coh-metrix-dementia
coh/database.py
Python
gpl-3.0
9,555
0.000419
# -*- coding: utf-8 -*- # Coh-Metrix-Dementia - Automatic text analysis and classification for dementia. # Copyright (C) 2014 Andre Luiz Verucci da Cunha # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software F...
roup={0}, word={1}, pos={2}, antonym={3}>'\ .format(self.group, self.word, self.pos, self.antonym) class Frequency(Base): __tablename__ = 'frequencies'
id = Column(Integer, primary_key=True) word = Column(String) freq = Column(Integer) freq_perc = Column(Float) texts = Column(Integer) texts_perc = Column(Float) def __repr__(self): return '<Frequency: word=%s, freq=%s, freq_perc=%s, texts=%s, texts_perc=%s>'\ % (self.word, s...
zhouyao1994/incubator-superset
superset/utils/decorators.py
Python
apache-2.0
4,658
0.000859
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
e logging.exception("Exception possibly due to cache backend.") # if no response was cached, compute it using the wrapped function if response is None: response = f(*args, **kwargs) # add headers for caching: Last Modified, Expires and ETag ...
_FUTURE response.expires = response.last_modified + timedelta( seconds=expiration ) response.add_etag() # if we have a cache, store the response from the request if cache: try: ...
mitnk/letsencrypt
letsencrypt/account.py
Python
apache-2.0
7,359
0.000408
"""Creates ACME accounts for server.""" import datetime import hashlib import logging import os import socket from cryptography.hazmat.primitives import serialization import pyrfc3339 import pytz import zope.component from acme import fields as acme_fields from acme import jose from acme import messages from letsenc...
) if acc.id != account_id: raise errors.AccountStorageError( "Account ids mismatch (expected: {0}, found: {1}".format( account_id, acc.id)) return acc def save(self, account): account_dir_path = self._acc
ount_dir_path(account.id) le_util.make_or_verify_dir(account_dir_path, 0o700, os.geteuid(), self.config.strict_permissions) try: with open(self._regr_path(account_dir_path), "w") as regr_file: regr_file.write(account.regr.json_dumps()) ...
mozafari/vprofiler
src/Restorer/Restorer.py
Python
apache-2.0
744
0.002688
import os import shutil import csv class Restorer:
def __init__(self, backupDir): self.backupDir = backupDir if not self.backupDir.endswith('/'): self.backupDir += '/' def Run(self, filenamesListFname, doDelete=False): if not os.path.exists(self.backupDir + filenamesListFname): return with open(self.backupDi...
List: filenameReader = reversed(list(csv.reader(fnamesList, delimiter='\t'))) for line in filenameReader: shutil.copyfile(line[0], line[1]) if doDelete: os.remove(line[0]) if doDelete: os.remove(self.backupDir + filenamesL...
ldgit/hours-calculator
calculator.py
Python
mit
592
0.003378
imp
ort sublime, sublime_plugin try: # ST 3 from .app.sublime_command import SublimeCommand from .app.settings import Settings except ValueError: # ST 2 from app.sublime_command import SublimeCommand from app.settings import Settings
class CalculateHoursCommand(sublime_plugin.TextCommand): def run(self, edit): SublimeCommand(Settings(sublime)).calculate_hours(edit, self.view) class ConvertHoursToSecondsCommand(sublime_plugin.TextCommand): def run(self, edit): SublimeCommand(Settings(sublime)).convert_hours_to_seconds(edit...
Reinaesaya/OUIRL-ChatBot
chatterbot/imgcaption/im2txt/show_and_tell_model_test.py
Python
bsd-3-clause
6,824
0.003957
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
top level scope.""" counter = {} for v in tf.global_variables(): name = v.op.name.split("/")[0] num_params = v.get_shape().num_elements() assert num_params counter[name] = counter.get(name, 0) + num_params return counter def _checkModelParameters(self): """Verifies the number...
model.""" param_counts = self._countModelParameters() expected_param_counts = { "InceptionV3": 21802784, # inception_output_size * embedding_size "image_embedding": 1048576, # vocab_size * embedding_size "seq_embedding": 6144000, # (embedding_size + num_lstm_units...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/astroid/tests/testdata/python3/data/format.py
Python
mit
421
0.023753
"""A multiline string """ function('aeozrijz\ earzer', hop) # XXX write test x = [i for i in range(5) if i % 4] fonction
(1, 2, 3, 4) def definition(a, b, c): return a + b + c class debile(dict,
object): pass if aaaa: pass else: aaaa,bbbb = 1,2 aaaa,bbbb = bbbb,aaaa # XXX write test hop = \ aaaa __revision__.lower();
nkubala/runtimes-common
ftl/common/ftl_util.py
Python
apache-2.0
8,151
0
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
elif k == 'ExposedPorts': # this key change is made as the key is # 'ports' in an Overrides object # but 'ExposedPorts' in the config_file overrides_dct['ports'] = v return metadata.Overrides(**overrides_dct) class Timing(object): def __init__(self, descriptor...
criptor = descriptor def __enter__(self): self.start = time.time() return self def __exit__(self, unused_type, unused_value, unused_traceback): end = time.time() logging.info('%s took %d seconds', self.descriptor, end - self.start) def zip_dir_to_layer_sha(pkg_dir): tar_p...
anshbansal/general
Python3/project_euler/001_050/034.py
Python
mit
474
0.004219
from math import factorial def prob_034(): facts = [factorial(i) for i in range(10)] ans = 0 limit = factorial(9) * 7 for num in range(10, limit): temp_num = num sums = 0 while temp_num:
sums += facts[temp_num % 10] temp_num //= 10 if sums == num: ans += num return ans if __name__ == "__
main__": import time s = time.time() print(prob_034()) print(time.time() - s)
zackster/HipHopGoblin
trunk/bitly.py
Python
bsd-3-clause
7,778
0.015042
#!/usr/bin/python2.4 # # Copyright 2009 Empeeric LTD. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
urce url """ request = self._getURL("info",shortURL,params) result = self._fetchUrl(request) json = simplejson.loads(result) self._CheckForError(json) return json['results'][string.split(shortURL, '/')[-1]] def stats(self,shortURL,params={}): """ Giv...
ts",shortURL,params) result = self._fetchUrl(request) json = simplejson.loads(result) self._CheckForError(json) return Stats.NewFromJsonDict(json['results']) def errors(self,params={}): """ Get a list of bit.ly API error codes. """ request = self._getURL("err...
KennethNielsen/SoCo
soco/groups.py
Python
mit
6,415
0
# -*- coding: utf-8 -*- # Disable while we have Python 2.x compatability # pylint: disable=useless-object-inheritance """This module contains classes and functionality relating to Sonos Groups.""" from __future__ import unicode_literals class ZoneGroup(object): """ A class representing a Sonos Group. It l...
02")} ) Any SoCo instance can tell you what group it is in:: >>> device = soco.discovery.any_
soco() >>> device.group ZoneGroup( uid='RINCON_000FD584236D01400:58', coordinator=SoCo("192.168.1.101"), members={SoCo("192.168.1.101"), SoCo("192.168.1.102")} ) From there, you can find the coordinator for the current group:: >>> device.group.co...
NorfairKing/sus-depot
shared/shared/vim/dotvim/bundle/YouCompleteMe/third_party/ycmd/ycmd/completers/rust/rust_completer.py
Python
gpl-2.0
12,458
0.031947
# Copyright (C) 2015 ycmd contributors # # This file is part of ycmd. # # ycmd is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ycmd...
le if it's not provided. """ rust_src_path = self.user_options
[ 'rust_src_path' ] # Early return if user provided config if rust_src_path: return rust_src_path # Fall back to environment variable env_key = 'RUST_SRC_PATH' if env_key in os.environ: return os.environ[ env_key ] return None def SupportedFiletypes( self ): return [ 'rust...
zalando/patroni
tests/test_patroni.py
Python
mit
7,937
0.00126
import etcd import logging import os import signal import time import unittest import patroni.config as config from mock import Mock, PropertyMock, patch from patroni.api import RestApiServer from patroni.async_executor import AsyncExecutor from patroni.dcs.etcd import AbstractEtcdClientWithFailover from patroni.excep...
ide_effect=Exception) self.p.shutdown() def test_check_psycopg(self): with patch.object(builtins, '__import__', Mock(side_effect=ImportError)): self.assertRaises(SystemExit, check_psycopg) with patch.object(builtins, '__im
port__', mock_import): self.assertRaises(SystemExit, check_psycopg)
asayler/moodle-offline-grading
moodle_grading_worksheet.py
Python
gpl-3.0
1,988
0.002012
#!/usr/bin/env python3 # Basic program to read csv file and spit it back out import argparse import csv import sys def read_worksheet(csv_f
ile): """ Read contents of worksheet_csv and return (contents, dialect, fields) """ contents = {} dialect = None fields = None with open(csv_file, 'r', newline='') as worksheet: dialect = csv.Sniffer().sniff(worksheet.read()) worksheet.seek(0) heade
r = csv.Sniffer().has_header(worksheet.read()) worksheet.seek(0) reader = csv.DictReader(worksheet, dialect=dialect) fields = reader.fieldnames for row in reader: contents[row['Full name']] = row return (contents, dialect, fields) def write_worksheet(csv_file, content...
oasis-open/cti-python-stix2
stix2/datastore/filesystem.py
Python
bsd-3-clause
28,607
0.000699
"""Python STIX2 FileSystem Source/Sink""" import errno import io import json import os import re import stat from stix2 import v20, v21 from stix2.base import _STIXBase from stix2.datastore import ( DataSink, DataSource, DataSourceError, DataStoreMixin, ) from stix2.datastore.filters import Filter, FilterSet, appl...
get_type_from_id(id_) for id_ in filter_.value ), ) opt_types = Au
thSet(allowed_types, prohibited_types) opt_ids = AuthSet(allowed_ids, prohibited_ids) # If we have both type and ID whitelists, perform a type-based intersection # on them, to further optimize. (Some of the cross-property constraints # occur above; this is essentially a second pass which operates on t...
kaplun/harvesting-kit
harvestingkit/jats_package.py
Python
gpl-2.0
11,580
0.001813
# -*- coding: utf-8 -*- ## ## This file is part of Harvesting Kit. ## Copyright (C) 2014 CERN. ## ## Harvesting Kit is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at ...
Tag in self.document.getElementsByTagName('pub-date'): if dateTag.getAttribute('pub-type') == 'final': try: day = int(get_value_in_tag(dateTag, 'day'))
month = int(get_value_in_tag(dateTag, 'month')) year = int(get_value_in_tag(dateTag, 'year')) final = str(date(year, month, day)) except ValueError: pass if dateTag.getAttribute('pub-type') == 'epub': try: ...
jrowan/zulip
zerver/lib/outgoing_webhook.py
Python
apache-2.0
6,862
0.00408
from __future__ import absolute_import from typing import Any, Iterable, Dict, Tuple, Callable, Text, Mapping import requests import json import sys import inspect import logging from six.moves import urllib from functools import reduce from requests import Response from django.utils.translation import ugettext as _ ...
ailure_message = "Failure! " + failure_message send_response_message(event['user_profile_id'], event['message'], fail
ure_message) def request_retry(event, failure_message): # type: (Dict[str, Any], Text) -> None event['failed_tries'] += 1 if event['failed_tries'] > MAX_REQUEST_RETRIES: bot_user = get_user_profile_by_id(event['user_profile_id']) failure_message = "Maximum retries exceeded! " + failure_mess...
edmorley/django
tests/auth_tests/test_basic.py
Python
bsd-3-clause
5,627
0.000534
from django.contrib.auth import get_user, get_user_model from django.contrib.auth.models import AnonymousUser, User from d
jango.core.exceptions import ImproperlyConfigured from django.db import IntegrityError from django.http import HttpRequest from django.test import TestCase, override_settings from django.utils import translation from .models imp
ort CustomUser class BasicTestCase(TestCase): def test_user(self): "Users can be created and can set their password" u = User.objects.create_user('testuser', 'test@example.com', 'testpw') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) sel...
maurob/timeperiod
serializers.py
Python
mit
1,063
0.001881
from rest_framework import serializers from .models import User, Activity, Period class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email') extra_kwargs = { 'url': {'view_name': 'timeperiod:user-detail'}, ...
class Meta: model = Activity fields = ('url', 'user', 'name', 'total', 'running') extra_kwargs = { 'url': {'view_name': 'timeperiod:activity-detail'}, 'user': {'view_name': 'timeperiod:user-detail'}, } class PeriodSerializer(serializers.HyperlinkedModelSerial...
'start', 'end', 'valid') extra_kwargs = { 'url': {'view_name': 'timeperiod:period-detail'}, 'activity': {'view_name': 'timeperiod:activity-detail'}, }
xiao0720/leetcode
145/Solution.py
Python
mit
597
0.0067
class Solution: def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] else: return list(self.postorderTraversalGen(root)) def postorderTraversalGen(self, node):
if node
.left is not None: for other in self.postorderTraversalGen(node.left): yield other if node.right is not None: for other in self.postorderTraversalGen(node.right): yield other yield node.val
vdjagilev/desefu-export
formatter/html/HtmlFormatter.py
Python
mit
7,031
0.003413
from formatter.AbstractFormatter import AbstractFormatter import html import os class IndexElement: anchor = 0 def __init__(self, content): self.content = content self.a = IndexElement.anchor self.node_list = [] IndexElement.anchor += 1 def addNode(self, e): self....
mod_id_index.addNode(IndexElement("Extracted data")) file_list = sorted(mod['extract_data'].keys()) for file_name i
n file_list: file_data = mod['extract_data'][file_name] table_views = sorted(file_data.keys()) result.content += "<b style=\"background-color: #ccc;\">%s</b><br />" % file_name for table in table_views: ...
unkyulee/elastic-cms
src/web/modules/dataservice/controllers/json.py
Python
mit
392
0.005102
import importlib from flask import render_templa
te import lib.es as es def get(p): # get data source definiton query = 'name:{}'.format(p['nav'][3]) p['ds'] = es.list(p['host'], 'core_data', 'datasource', query)[0] # load service path = "web.modules.dataservice.services.{}".format(p['ds']['type']) mod = importlib.import_module(path) ...
ute(p)
widdowquinn/pyani
pyani/pyani_graphics/sns/__init__.py
Python
mit
9,274
0.000647
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) The University of Strathclyde 2019 # Author: Leighton Pritchard # # Contact: # leighton.pritchard@strath.ac.uk # # Leighton Pritchard, # Strathclyde Institute of Pharmaceutical and Biomedical Sciences # The University of Strathclyde # Cathedral Street # Glasgow # G1 1...
ur for class in col 1 ... colour for class in col ... n colour for class in col n """ levels = sorted(list(set(classes.values()))) paldict = dict( zip( levels, sns.cubehelix_palette( len(levels), light=0.9, dark=0.1, reverse=True, start=1, rot=-2 ...
al = {cls: paldict[lvl] for (cls, lvl) in list(classes.items())} # Have to use string conversion of the dataframe index, here col_cb = pd.Series([str(_) for _ in dfr.index]).map(lvl_pal) # The col_cb Series index now has to match the dfr.index, but # we don't create the Series with this (and if we try, ...
markgw/jazzparser
src/jazzparser/utils/domxml.py
Python
gpl-3.0
3,282
0.012492
"""Handy XML processing utility functions. Various XML processing utilities, using minidom, that are used in various places throughout the code. """ """ =========================
===== License ======================================== Copyright (C) 2008, 2010-12 University of Edinburgh, Mark Granroth-Wilding This file is part of The Jazz Parser. The Jazz Parser is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by th...
icense, or (at your option) any later version. The Jazz Parser is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a...
eroicaleo/LearningPython
interview/leet/1446_Consecutive_Characters.py
Python
mit
471
0.002123
#!/usr/
bin/env python3 class Solution: def maxPower(self, s): p, cnt, ret = '', 1, 0 for c in s: if c == p: cnt += 1 else: ret, cnt = max(ret, cnt), 1 p = c return max(ret, cnt) str_list = [ 'cc', 'leetcode', 'abbcccd...
)
jgstew/tools
Python/get_filename_from_pathname.py
Python
mit
894
0.006711
def get_filename_from_pathname(pathnames): # if arg is a not a list, make it so # https://stackoverflow.com/a/922800/861745 if not isinstance(pathnames, (list, tuple)): pathnames = [pathnames] for pathname in pathnames: # print( pathname ) print( pathname.replace('\\','/')....
blah/ path \ this}file name.txt", r"path blah/ path \ this}file.txt", r"\test/test\test.txt" ] get_filename_from_pathname(str_pathname) get_filename_fr
om_pathname(array_pathnames) # if called directly, then run this example: if __name__ == '__main__': main() # https://forum.bigfix.com/t/get-filename-from-arbitrary-pathnames/34616
HKuz/Test_Code
CodeFights/digitsProduct.py
Python
mit
1,457
0
#!/usr/local/bin/python # Code Fights Digits Product Problem def digitsProduct(product): def get_single_dig_factors(product): # Helper function to generate single-digit factors of product n = product factors = [] for i in range(9, 1, -1): while n % i == 0 and n > 1: ...
i in factors])) else: return -1 def main(): tests = [ [12, 26], [19, -1], [450, 2559], [0, 10], [13, -1], [1, 1], [243, 399], [576, 889], [360, 589], [24, 38], [120, 358], [168, 378], [192, 388], ...
00, 3558], [33, -1], [81, 99] ] for t in tests: res = digitsProduct(t[0]) ans = t[1] if ans == res: print("PASSED: digitsProduct({}) returned {}" .format(t[0], res)) else: print("FAILED: digitsProduct({}) returned {}, ans...
zenn1989/scoria-interlude
L2Jscoria-Game/data/scripts/quests/644_GraveRobberAnnihilation/__init__.py
Python
gpl-3.0
2,948
0.04749
#Made by Kerb import sys from com.l2scoria import Config from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest qn = "644_GraveRobberAnnihilation" #Drop rate DROP_CHANCE = 75 #Npc ...
est(644, qn, "Grave Robber Annihilation") CREATED = State('Start', QUEST) STARTED = State('Started', QUEST) QUEST.setInitialState(CREATED) QUEST.add
StartNpc(KARUDA) QUEST.addTalkId(KARUDA) for i in MOBS : QUEST.addKillId(i) STARTED.addQuestDrop(KARUDA,ORC_GOODS,1)
k-pramod/channel.js
examples/chatter/chat/consumers/base.py
Python
mit
1,649
0.001213
from datetime import datetime from channels.generic.websockets import JsonWebsocketConsumer from channels import Group, Channel from channels.message import Message from ..models import Room class ChatServer(JsonWebsocketConsumer): # Set to True if you want them, else leave out strict_ordering = False sl...
lf, message, **kwargs):
# type: (Message, dict) """ Handles disconnecting from a room """ slug = kwargs['slug'] Group(slug).discard(message.reply_channel) # Handle a user-leave event message.content['event'] = 'user-leave' self.receive(message.content, **kwargs)
messagebird/python-rest-api
examples/conversation_read_webhook.py
Python
bsd-2-clause
878
0.002278
#!/usr/bin/env python import messagebird import argparse parser = argparse.ArgumentParser() parser.add_argument('--ac
cessKey', help='access key for Mes
sageBird API', type=str, required=True) parser.add_argument('--webhookId', help='webhook that you want to read', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhook = client.conversation_read_webhook(args['webhookId']) # Print the object i...
bdelliott/wordgame
web/djangoappengine/management/commands/runserver.py
Python
mit
3,475
0.000576
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
sys.modules['__main__'] = dev_appserver_main # Set bind ip/port if specified. addr, port = None, '8000' if len(argv) > 2: if not argv[2].startswith('-'): addrport = argv[2] try: addr, port = addrport.split(":") except ValueError: ...
if port: args.extend(["--port", port]) # Add email settings from django.conf import settings if '--smtp_host' not in args and '--enable_sendmail' not in args: args.extend(['--smtp_host', settings.EMAIL_HOST, '--smtp_port', str(settings.EMAIL_PORT), ...
epam/DLab
infrastructure-provisioning/src/ssn/scripts/resource_status.py
Python
apache-2.0
2,004
0.002495
#!/usr/bin/python # ***************************************************************************** # # Copyright (c) 2016, EPAM SYSTEMS INC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
********** from pymongo import MongoClient import sys import yaml import argparse path = "/etc/mongod.conf" outfile = "/etc/mongo_params.yml" parser = argparse.ArgumentParser() parser.add_argument('--res
ource', type=str, default='') parser.add_argument('--status', type=str, default='') args = parser.parse_args() def read_yml_conf(path, section, param): try: with open(path, 'r') as config_yml: config = yaml.load(config_yml) result = config[section][param] return result exce...
ThomasSweijen/TPF
py/bodiesHandling.py
Python
gpl-2.0
8,305
0.056713
# encoding: utf-8 """ Miscellaneous functions, which are useful for handling bodies. """ from yade.wrapper import * import utils,math,numpy try: from minieigen import * except ImportError: from miniEigen import * #spheresPackDimensions================================================== def spheresPackDimensions(idS...
]<minVal[dim]) or (counter==0)): minVal[dim]=sphereMin[dim] minId[dim
] = b.id volume += 4.0/3.0*math.pi*sphereRadius*sphereRadius*sphereRadius mass += b.state.mass counter += 1 center = (maxVal-minVal)/2.0+minVal extends = maxVal-minVal dimensions = {'max':maxVal,'min':minVal,'maxId':maxId,'minId':minId,'center':center, 'extends':extends, 'volume':volume, 'mass':mass, ...
SethGreylyn/gwells
gwells/forms.py
Python
apache-2.0
53,558
0.003697
""" Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
get' helper.form_action = '' helper.layout = Layout( Fieldset( '', 'well', 'addr', 'legal', 'owner', Hidden('sort', 'well_tag_number'), Hidden('dir', 'asc'), # sta...
lat_long', ''), Hidden('end_lat_long', ''), ), FormActions( Submit('s', 'Search'), HTML('<a class="btn btn-default" href="{% url \'search\' %}">Reset</a>'), css_class='form-group formButtons', ) ) return...
ludmilamarian/invenio
invenio/legacy/bibdocfile/plugins/bom_textdoc.py
Python
gpl-2.0
5,427
0.003317
# This file is part of Invenio. # Copyright (C) 2007, 2008, 2009, 2010, 2011, 2014 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any l...
@rtype: bool """ if version is None: version = self.get_latest_version() if os.path.exists(os.path.join(self.basedir, '.text;%i' % version)): if not require_up_to_date: return True else: docfiles = self.list_version_files(versio...
sedir, '.text;%i' % version))) for docfile in docfiles: if text_md <= docfile.md: return False return True return False def __repr__(self): return 'BibTextDoc(%s, %s, %s)' % (repr(self.id), repr(self.doctype), repr(self.hum...
noamelf/Open-Knesset
kikar/views.py
Python
bsd-3-clause
376
0.005319
from django.http.response import HttpResponse import requests def get_statuses(request): url = request.GET.get('path', 'http://www.kikar.org/api/v1/facebook_status/?limit=5') url = url.replace("'", "").replace('"', "") print(url) ki
kar_res = requests.get(url) res = HttpRespons
e(content=kikar_res.content, content_type='application/json') return res
piotrmaslanka/systemy
examples/catalogExample.py
Python
mit
382
0.010471
from yos.rt import BaseTask
let from yos.ipc import Catalog class CatalogExample(BaseTasklet): def on_startup(self): Catalog.store('test1', 'test2', catname='test3')
Catalog.get('test1', self.on_read, catname='test3') def on_read(self, val): if val == 'test2': print("Test passed") else: print("Test failed")
EmoryUniversity/PIAT
src/common/log-analysis/python-discard/LogDBIngester.py
Python
lgpl-3.0
2,170
0.007834
#!/usr/local/bin/python # check python version import sys ver_info = sys.version_info # parse commandlines if ver_info[0] < 3 and ver_info[1] < 7: from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="input log file", metavar="LOG_FILE...
t="dirname", help="input directory with log files", metavar="LOG_DIR") parser.add_option("-t", "--dbtype", dest="dbtype", help="database type", default="mongodb", metavar="DB_TYPE") (options, args) = parser.parse_args(); else: import argparse parser = argparse.ArgumentParser(description="Log to d...
="input directory with log files", metavar="LOG_DIR") parser.add_argument("-t, --dbtype", dest="dbtype", help="database type", default="mongodb", metavar="DB_TYPE") options = parser.parse_args() print "file {0} ".format(options.filename) # print "dirname {0} ".format(options.dirname) print "dbtype {...
pirate/bookmark-archiver
tests/conftest.py
Python
mit
417
0.009592
from multiprocessing import Process import pytest from .mock_server.server import start server_process = None @pytest.hookimpl def pytest_sessionstart(session): global server_process s
erver_process = Process(target=start) server_process.start() @pytest.hookimpl def pytest_sessionfinish(session): if server_process is
not None: server_process.terminate() server_process.join()
astrofrog/sedfitter
sedfitter/extinction/extinction.py
Python
bsd-2-clause
3,289
0.00152
from __future__ import print_function, division import numpy as np from astropy import units as u from astropy.table import Table from ..utils.validator import validate_array __all__ = ['Extinction'] class Extinction(object): def __init__(self): self.wav = None self.chi = None @property ...
self._chi = validate_array('chi', value, ndim=1, shape=None if self.wav is None else self.wav.shape, physical_type='area per unit mass') @classmethod def from_file(cls, filename, columns=(0, 1), wav_unit=...
rom an ASCII file. This reads in two columns: the wavelength, and the opacity (in units of area per unit mass). Parameters ---------- filename : str, optional The name of the file to read the extinction law from columns : tuple or list, optional ...
pmineiro/randembed
mulan/xmlcsv2xy.py
Python
unlicense
829
0.014475
from sys import argv from xml.dom import minidom import csv stem = argv[1][:-4] if argv[1].endswith('.xml') else argv[1] xmldoc = minidom.parse('%s.xml'%stem) labellist = xmldoc.getElementsByTagName('label') labels = [l.attributes['name'].value for l in labellist] labelset = set(labels) for split in 'train','test': ...
csv.DictReader(csvfile) features = [f for f in reader.fieldnames if f not in labelset] x = open('%s-%s.x.txt'%(stem,split), 'w') y = open('%s-%s.y.txt'%(stem,split), 'w') for row in reader: xbuf = ' '.join([row[f] for f in features]) ybuf = ' '.join([row[l] for l...
bels]) x.write('%s\n'%xbuf) y.write("%s\n"%ybuf) x.close() y.close()
credits-currency/credits
qa/pull-tester/pull-tester.py
Python
mit
8,944
0.007044
#!/usr/bin/python # Copyright (c) 2013 The Bitcoin Core developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json from urllib import urlopen import requests import getpass from string import Template import sys i...
path.exists(dir): os.system("rm -r " + dir) os.make
dirs(dir) currentdir = os.environ["RESULTS_DIR"] + "/current" os.system("rm -r "+currentdir) os.system("ln -s " + dir + " " + currentdir) out = open(dir + "test.log", 'w+') resultsurl = os.environ["RESULTS_URL"] + commit checkedout = checkout_pull(clone_url, commit, out) if checkedout != Tr...
erikrose/oedipus
oedipus/tests/test_groupby.py
Python
bsd-3-clause
2,566
0.00039
import fudge from oedipus import S from oedipus.tests import no_results, Biscuit, BaseSphinxMeta import sphinxapi class BiscuitWithGroupBy(object): """Biscuit with default groupby""" class SphinxMeta(BaseSphinxMeta): group_by = ('a', '@group') @fudge.patch('sphinxapi.SphinxClient') def test_group...
.expects('RunQueries') .returns(no_results)) S(Biscuit).group_b
y('a', '@group')._raw() @fudge.patch('sphinxapi.SphinxClient') def test_group_by_override(sphinx_client): """Test group by override.""" (sphinx_client.expects_call().returns_fake() .is_a_stub() .expects('SetGroupBy') .with_args('a', sphinxapi.SPH_GROUPBY_A...
stackforge/python-openstacksdk
openstack/dns/v2/_base.py
Python
apache-2.0
4,338
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
nk = None params = {} if isinstance(data, dict): links = data.get('links') if links: next_link = links.get('next') total = data.get('metadata', {}).get('total_count') if total: # We have a kill switch total_...
(next page URL) into params. # This prevents duplication of query parameters that with large # number of pages result in HTTP 414 error eventually. if next_link: parts = urllib.parse.urlparse(next_link) query_params = urllib.parse.parse_qs(parts.query) params....
tdfischer/organizer
sync/migrations/0004_auto_20190731_1553.py
Python
agpl-3.0
403
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-07-31 15:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [
('sync', '0003_synctarget_lastrun'), ] operations = [ migrations.RenameModel( old_name='SyncTarget', new_name='ImportSource', ), ]
DonJayamanne/pythonVSCode
build/ci/addEnvPath.py
Python
mit
739
0.00406
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT Li
cense. #Adds the virtual environment's executable path to json file import json,sys import os.path jsonPath = sys.argv[1] key = sys.argv[2] if os.path.isfile(jsonPath): with open(jsonPath, 'r') as read_file: data = json.load(read_file) else: directory = os.path.dirname(jsonPath) if not os.path.ex...
tory): os.makedirs(directory) with open(jsonPath, 'w+') as read_file: data = {} data = {} with open(jsonPath, 'w') as outfile: if key == 'condaExecPath': data[key] = sys.argv[3] else: data[key] = sys.executable json.dump(data, outfile, sort_keys=True, indent=4...
jesus2099/JonnyJD_musicbrainz-isrcsubmit
isrcsubmit.py
Python
gpl-3.0
41,557
0.002142
#!/usr/bin/env python # Copyright (C) 2009-2015 Johannes Dewender # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # #...
wser module is used when nothing is found in this list. # This especially happens on Windows and Mac OS X (browser mostly not in PATH) import os import re import sys import codecs import logging import getpass import tem
pfile import webbrowser from datetime import datetime from optparse import OptionParser from subprocess import Popen, PIPE, call try: import discid from discid import DiscError except ImportError: try: from libdiscid.compat import discid from libdiscid.compat.discid import DiscError exc...
hugobarzano/DispositivosMovilesBackEnd
ControlUsuarios/views.py
Python
gpl-3.0
16,446
0.014958
from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate, login from django.contrib.auth import logout from django.contrib.auth.decorators import login_required import time from ControlUsuarios.forms import * from ControlUsuarios.models import UserProfile # Create your views her...
lista.append(i) print lista[0]["clave_sesion"] form=SessionForm() return render(request, 'ControlUsuarios/sessions.html',{'form': form,"qr":
lista[0]["clave_sesion"],"clase":clase} ) class Preferencias(View): def get(self, request): print "Entrando por el get" form=FormEntrada() return render(request, 'ControlUsuarios/preferencias.html', {'form': form}) def post(self, request): print "Entrando por el post" ...
bcharlas/mytrunk
py/geom.py
Python
gpl-2.0
24,154
0.056543
# encoding: utf-8 """ Creates geometry objects from facets. """ from yade.wrapper import * import utils,math,numpy from minieigen import * #facetBox=============================================================== def facetBox(center,extents,orientation=Quaternion((0,1,0),0.0),wallMask=63,**kw): """ Create arbitrari...
Parameters inspired by ParaView sphere glyph :param Vector3 center: center of the create
d sphere :param float radius: sphere radius :param int thetaResolution: number of facets around "equator" :param int phiResolution: number of facets between "poles" + 1 :param bool returnElementMap: returns also tuple of nodes ((x1,y1,z1),(x2,y2,z2),...) and elements ((id01,id02,id03),(id11,id12,id13),...) if true,...
aschleg/mathpy
mathpy/numtheory/sequences.py
Python
mit
8,092
0.003089
# encoding=utf8 """ Module containing functions and methods related to sequences in number theory such as the Fibonacci sequence, the 3n + 1 problem, and more. """ import numpy as np from mathpy.numtheory.integers import iseven from decimal import Decimal, localcontext def catalan(n, prec=1000):...
-- Moler, C. (2011). Numerical computing with MA
TLAB (1st ed.). Philadelphia, Pa: Society for Industrial & Applied Mathematics. """ if output is 'last': return ((1 + np.sqrt(5)) ** n - (1 - np.sqrt(5)) ** n) / (2 ** n * np.sqrt(5)) fn = np.empty(n) fn[0] = 1 fn[1] = 1 if n >= 100: with localcontext() as ...
acq4/acq4
acq4/devices/PMT/PMT.py
Python
mit
705
0.004255
# -*- coding: utf-8 -*- from acq4.devices.OptomechDevice import OptomechDevice from acq4.devices.DAQGeneric import DAQGeneric class PMT(DAQGeneric, Optom
echDevice): def __init__(self, dm, config, name): self.omConf = {} for k in ['parentDevice', 'transform']: if k in config: self.omConf[k] = config.pop(k) DAQGeneric.__init__(self, dm, config, name) OptomechDevice.__init__(self, dm, config, name) def g...
return None
gynvael/stream
006-xoxoxo-more-con/input_interface.py
Python
mit
100
0.04
__all__ = [ "Inpu
tInterface" ] class InputInterface(): def get_move(self)
: pass
cobbler/cobbler
tests/module_loader_test.py
Python
gpl-2.0
5,203
0.004613
import pytest from cobbler.cexceptions import CX from cobbler import module_loader from tests.conftest import does_not_raise @pytest.fixture(scope="function") def reset_modules(): module_loader.MODULE_CACHE = {} module_loader.MODULES_BY_CATEGORY = {} @pytest.fixture(scope="function") def load_modules(): ...
r/triggers/change/*", ["cobbler.modules.managers.genders", "cobbler.modules.scm_track"]), ("/var/lib/cobbler/triggers/install/post/*", ["cobbler.modules.installation.post_log", "cobbler.modules.installation.post_power", ...
"cobbler.modules.installation.post_report"]), ("/var/lib/cobbler/triggers/install/pre/*", ["cobbler.modules.installation.pre_clear_anamon_logs", "cobbler.modules.installation.pre_log", ...
chromium/chromium
tools/binary_size/libsupersize/integration_test.py
Python
bsd-3-clause
24,004
0.006749
#!/usr/bin/env python3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import glob import io import itertools import os import unittest import re import shutil import subprocess import sys impo...
TEST_OUTPUT_DIR, 'size-info/test.apk.pak.info') _TEST_ELF_FILE_BEGIN = os.path.join(_TEST_OUTPUT_DIR, 'elf.begin') _TEST_APK_LOCALE_PAK_SUBPATH = 'assets/en-US.pak' _TEST_APK_PAK_SUBPATH = 'assets/resources.pak' _TEST_APK_LOCALE_PAK_PATH = os.path.join(_TEST_APK_ROOT_DIR,
_TEST_APK_LOCALE_PAK_SUBPATH) _TEST_APK_PAK_PATH = os.path.join(_TEST_APK_ROOT_DIR, _TEST_APK_PAK_SUBPATH) _TEST_ON_DEMAND_MANIFEST_PATH = os.path.join(_TEST_DATA_DIR, 'AndroidManifest_OnDemand.xml') _TEST_ALWAYS_INSTALLED_MANIFEST_PATH = os.path....
j831/zulip
zerver/webhooks/jira/view.py
Python
apache-2.0
10,755
0.003533
# Webhooks for external integrations. from __future__ import absolute_import from typing import Any, Dict, List, Optional, Text, Tuple from django.utils.translation import ugettext as _ from django.db.models import Q from django.conf import settings from django.http import HttpRequest, HttpResponse from zerver.models...
content += u" to {}\n".format(to_field) return content def handle_updated_issue_event(payload, user_profile): # Reassigned, commented, reopened, and resolved events are all bundled # into this one 'updated' event type, so we
try to extract the meaningful # event that happened # type: (Dict[str, Any], UserProfile) -> Text issue_id = get_in(payload, ['issue', 'key']) issue = get_issue_string(payload, issue_id) assignee_email = get_in(payload, ['issue', 'fields', 'assignee', 'emailAddress'], '') assignee_mention = get...
antoinecarme/pyaf
tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_LinearTrend_Seasonal_Hour_NoAR.py
Python
bsd-3-clause
160
0.05
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_m
odel( ['Difference'] , ['Linear
Trend'] , ['Seasonal_Hour'] , ['NoAR'] );
RNAer/qiita
qiita_db/support_files/patches/python_patches/6.py
Python
bsd-3-clause
1,165
0
# Nov 22, 2014 # This patch is to create all the prep/sample template files and link them in # the database so they are present for download from os.path import join from time import strftime from qiita_db.util import get_mountpoint from qiita_db.sql_connection import SQLConnectionHandler from qiita_db.metadata_templ...
y_id): st = SampleTemplate(study_id) fp = join(fp_base, '%d_%s.txt' % (study_id, strftime("%Y%m%d-%H%M%S")))
st.to_file(fp) st.add_filepath(fp) for prep_template_id in conn_handler.execute_fetchall( "SELECT prep_template_id FROM qiita.prep_template"): prep_template_id = prep_template_id[0] pt = PrepTemplate(prep_template_id) study_id = pt.study_id fp = join(fp_base, '%d_prep_%d_%s.txt...
luksan/kodos
modules/flags.py
Python
gpl-2.0
1,969
0.006094
# -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; truncate-lines: 0 -*- # vi: set fileencoding=utf-8 filetype=python expandtab tabstop=4 shiftwidth=4 softtabstop=4 cindent: # :mode=python:indentSize=4:tabSize=4:noTabs=true: #-----------------------------------------------------...
urn def deembed(self): if self.preEmbedState != None: self.checkBox.setEnabled(True) self.checkBox.setChecked(self.preEmbedState) self.preEmbedState = None return class reFlagList(list): def allFlagsORed(self): ret = 0 for f in self: ...
for f in self: f.clear() return #-----------------------------------------------------------------------------#
sanguinariojoe/FreeCAD
src/Mod/Path/PathScripts/PathIconViewProvider.py
Python
lgpl-2.1
4,713
0.002758
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2017 sliptonic <shopinthewoods@gmail.com> * # * * # * This program is free software; you can redistribute it a...
or__ = "sliptonic (Brad Collette)" __url__ = "https://www.freecadweb.org" __doc__ = "ViewProvider who's main and only task is to assign an icon." PathLog.setLevel(PathLog.Level.INFO, PathLog.thisModule()) #PathLog.trackModule(PathLog.thisModule()) class ViewProvider(object): '''Generic view provider to assign an ...
lf.editCallback = None vobj.Proxy = self def attach(self, vobj): self.vobj = vobj self.obj = vobj.Object def __getstate__(self): attrs = {'icon': self.icon } if hasattr(self, 'editModule'): attrs['editModule'] = self.editModule attrs['editCallba...
Akagi201/akcode
python/test_model/usemodel.py
Python
gpl-2.0
33
0
import mymodel reload(mymodel)
Kent1/nxpy
nxpy/device.py
Python
apache-2.0
2,884
0
from lxml import etree from nxpy.interface import Interface from nxpy.vlan import Vlan from nxpy.flow import Flow from util import tag_pattern class Device(object): # Singleton _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance =
super( Device, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self): self.name = '' self.domain_name = '' self.interfaces = [] self.vlans = [] self.routing_options = [] def export(self, netconf_config=False): config
= etree.Element("configuration") device = etree.Element('system') if self.name: etree.SubElement(device, "host-name").text = self.name if self.domain_name: etree.SubElement(device, "domain-name").text = self.domain_name if len(device.getchildren()): c...