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
Mortal/eggpy
ircutils/client.py
Python
mit
13,186
0.00857
""" This module provides a direct client interface for managing an IRC connection. If you are trying to build a bot, :class:`ircutils.bot.SimpleBot` inherits from :class:`SimpleClient` so it has the methods listed below. """ import collections from . import connection from . import ctcp from . import events from . ...
: self.events.register_listener
(name, self.custom_listeners[name]) def _add_built_in_handlers(self): """ Adds basic client handlers. These handlers are bound to events that affect the data the the client handles. It is required to have these in order to keep track of things like client nick changes, join...
CQTools/analogIO-miniUSB
analogIO.py
Python
mit
2,908
0.013755
# -*- coding: utf-8 -*- """ Created on Fri Sep 5 14:44:52 2014 @author: nick Pyserial interface for communicating with mini usb Analog IO board Usage: Send plaintext commands, separated by newline/cr or semicolon. An eventual reply comes terminated with cr+lf. Important commands: *IDN? Returns device i...
: # Module for communicating with the mini usb IO board baudrate = 115200 def __init__(self, port): self.serial = self._open_port(port) self._serial_write('a')# flush io buffer print self._serial_read() #will read unknown command def _open_port(self, port):
ser = serial.Serial(port, timeout=5) #ser.readline() #ser.timeout = 1 #causes problem with nexus 7 return ser def _serial_write(self, string): self.serial.write(string + '\n') def _serial_read(self): msg_string = self.serial.readline() # Remove any line...
eepp/lttngc
lttngc/about_dialog.py
Python
mit
763
0
from lttngc import __version__ from lttngc import util
s from PyQt4 import Qt import os.path class QLttngcAboutDialog(utils.QCommonDialog, utils.QtUiLoad): _UI_NAME = 'about' def __init__(self): super().__init__() self._setup_ui() def _set_version(self): self.version_label.setText('v{}'.format(__version__)) def _set_contents(sel...
ogo-80.png')) pixmap = Qt.QPixmap(path) self._logo_lbl.setPixmap(pixmap) self._logo_lbl.setMask(pixmap.mask()) self._logo_lbl.setText('') def _setup_ui(self): self._load_ui() self._set_contents() self._set_logo()
JVMartin/grammar-analyzer
tests.py
Python
mit
7,593
0.018833
#!/usr/bin/env python3 """ Unit tests for the Grammar class and for the GrammarAnalyzer class. Tests each grammar in the "grammars" folder against a variety of strings. """ import unittest from grammar import Grammar from grammaranalyzer import GrammarAnalyzer class TestGrammar(unittest.TestCase): def test_nonexis...
lyzer = GrammarAnalyzer(grammar) # Check accepted strings. self.assertTrue(grammar_anal
yzer.test_string("a#b#c#d")) self.assertTrue(grammar_analyzer.test_string("aa#bb#c#d")) self.assertTrue(grammar_analyzer.test_string("a#b#cc#dd")) self.assertTrue(grammar_analyzer.test_string("aaa#bbb#c#d")) self.assertTrue(grammar_analyzer.test_string("a#b#ccc#ddd")) self.assertTrue(grammar_analyzer.test_str...
ppasq/geonode
geonode/base/forms.py
Python
gpl-3.0
17,648
0.000793
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 ...
output.append(options) output.append('</select>') return mark_safe('\n'.join(output)) def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def render_option_va...
selected_choices, option_value, option_label, data_section=None): if option_value is None: option_value = '' option_value = force_text(option_value) if option_value in selected_choices: selected_html = mark_safe(' selected')...
edmorley/treeherder
tests/selenium/test_switch_app.py
Python
mpl-2.0
790
0
from pages.treeherder import Treeherder def test_switch_app(base_url, selenium, test_repository): """Switch between Treeherder and Perfherder using header dropdown""" page = Treeherder(selenium, base_url).open() assert page.header.active_app == 'Treeherder' page = page.switch_to_perfherder() asser...
# Be aware that when switching back from Perfherder, it will try to
# default to mozilla-inbound, which does not exist in this test scenario. # So part of this test is to ensure what happens when the ``repo`` param # in the url is an invalid repo. We should still display the nav bars # and a meaningful error message. assert page.header.active_app == 'Treeherder'
xbmc/atv2
xbmc/lib/libPython/Python/Lib/bsddb/test/test_associate.py
Python
gpl-2.0
11,198
0.009109
""" TestCases for DB.associate. """ import sys, os, string import tempfile import time from pprint import pprint try: from threading import Thread, currentThread have_threads = 1 except ImportError: have_threads = 0 import unittest from test_all import verbose try: # For Pythons w/distutils pybsddb ...
("Linda Ronstadt", "Don't Know Much", "Rock"), 6 : ("Michael Bolton", "How Am I Supposed To Live Without You", "Blues"),
7 : ("Paul Young", "Oh Girl", "Rock"), 8 : ("Paula Abdul", "Opposites Attract", "Rock"), 9 : ("Richard Marx", "Should've Known Better", "Rock"), 10: ("Rod Stewart", "Forever Young", "Rock"), 11: ("Roxette", "Dangerous", "Rock"), 12: ("Sheena Easton", "The Lover In Me", "Rock"), 13: ("Sinead O'Connor", "Nothing Compare...
arthurpro/HopperPlugins
tools/dumpbinary.py
Python
bsd-2-clause
5,539
0
#!/usr/bin/env python # Copyright (c) 2014, Alessandro Gatti - frob.it # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice...
4 def dump(input_file, length, endian, strip_spaces): if length == 1: dump_byte(input_f
ile) elif length == 2: dump_word(input_file, endian, strip_spaces) elif length == 4: dump_dword(input_file, endian, strip_spaces) else: pass return 0 if __name__ == '__main__': parser = argparse.ArgumentParser(prog=NAME, description=DESCRIPTION) endianness = parser.add_...
arunkgupta/gramps
gramps/plugins/textreport/summary.py
Python
gpl-2.0
10,795
0.004354
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # Copyright (C) 2008 Brian G. Matherly # Copyright (C) 2010 Jakim Friant # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publi...
t(self): """ Overridden function to generate the report. """ self.doc.start_paragraph("SR-Title") title = _("Database Summary Report") mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() sel...
ize_media() def summarize_people(self): """ Write a summary of all the people in the database. """ with_media = 0 incomp_names = 0 disconnected = 0 missing_bday = 0 males = 0 females = 0 unknowns = 0 namelist = [] ...
andnovar/kivy
kivy/core/text/__init__.py
Python
mit
28,172
0.000461
''' Text ==== An abstraction of text creation. Depending of the selected backend, the accuracy of text rendering may vary. .. versionchanged:: 1.5.0 :attr:`LabelBase.line_height` added. .. versionchanged:: 1.0.7 The :class:`LabelBase` does not generate any texture if the text has a width <= 1. This is t...
__ = ('LabelBase', 'Label') import re import os from functools import partial from copy import copy from kivy import kivy_data_dir from kivy.utils import platform from kivy.graphics.texture import Texture from kivy.core import core_select_lib from kivy.core.text.text_layout import layout_text, LayoutWord from kivy.res...
ces import resource_find, resource_add_path from kivy.compat import PY2 from kivy.setupconfig import USE_SDL2 DEFAULT_FONT = 'Roboto' FONT_REGULAR = 0 FONT_ITALIC = 1 FONT_BOLD = 2 FONT_BOLDITALIC = 3 whitespace_pat = re.compile('( +)') class LabelBase(object): '''Core text label. This is the abstract clas...
pascalweiss/LSFEventScraper
LSFFetcher.py
Python
mit
2,374
0.001264
from LSFEventType import LSFEventType __author__ = 'pascal' from urllib import urlopen import time from threading import Thread from glob import glob class LSFFetcher: _overview_url = '' _event_urls = [] simultaneous_threads = 10 def add_overview_url(self, overview_url): self._overview_url ...
) callback(html) def fetch_event_overview(self, callback): event_overview = self.fetch_url(self._overview_url) callback(event_overview) def fetch_event_
sites(self, callback): threads = [] for event_url in self._event_urls: thread = Thread(target=self.fetch_event_site, args=(event_url, callback)) threads.append(thread) while threads != []: aux_threads = [] for i in range(self.simultaneous_threads)...
hunch/hunch-gift-app
django/contrib/gis/db/backends/oracle/adapter.py
Python
mit
157
0.006369
from cx_Oracle import CLOB from d
jango.contrib.gis.db.backends.adapter import WKTAdapter class OracleSpatialAdapter(WKTAdapter): inpu
t_size = CLOB
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/terminal/aireos.py
Python
bsd-3-clause
1,999
0.0005
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible is d...
re.compile(br"'[^']' +returned error code: ?\d+"), ] def on_open_shell(self): try: comman
ds = ('{"command": "' + self._connection._play_context.remote_user + '", "prompt": "Password:", "answer": "' + self._connection._play_context.password + '"}', '{"command": "config paging disable"}') for cmd in commands: self._exec_cli_command(c...
grzes/djangae
djangae/db/backends/appengine/dnf.py
Python
bsd-3-clause
9,768
0.001536
import copy from itertools import product from django.conf import settings from django.db.models.sql.datastructures import E
mptyResultSet from djangae.db.backends.appengine.query import WhereNode from django.db import NotSupportedError # Maximum number of subqueries in a mult
iquery DEFAULT_MAX_ALLOWABLE_QUERIES = 100 def preprocess_node(node, negated): to_remove = [] # Go through the children of this node and if any of the # child nodes are leaf nodes, then explode them if necessary for child in node.children: if child.is_leaf: if child.operator == "...
anhstudios/swganh
data/scripts/templates/object/creature/npc/droid/shared_wed_treadwell_base.py
Python
mit
460
0.045652
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEAS
E SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/creature/
npc/droid/shared_wed_treadwell_base.iff" result.attribute_template_id = 3 result.stfName("droid_name","wed_treadwell_base") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
tnwhitwell/lexicon
tests/test_main.py
Python
mit
1,149
0.008703
import lexicon.__main__ import pytest def test_BaseProviderParser(): baseparser = lexicon.__main__.BaseProviderParser() parsed = baseparser.parse_args(['list','capsulecd.com','TXT']) assert parsed.action == 'list' assert parsed.domain == 'capsulecd.com' assert parsed.type == 'TXT' assert parsed...
def test_BaseProviderParser_without_options(): baseparser = lexicon.__main__.BaseProviderParser() with pytest.raises(SystemExit): baseparser.parse_args([]) def test_MainParser(): baseparser
= lexicon.__main__.MainParser() parsed = baseparser.parse_args(['cloudflare','list','capsulecd.com','TXT']) assert parsed.provider_name == 'cloudflare' assert parsed.action == 'list' assert parsed.domain == 'capsulecd.com' assert parsed.type == 'TXT' def test_MainParser_without_args(): basepars...
igor-rangel7l/igorrangelteste.repository
script.module.urlresolver/lib/urlresolver/plugins/userscloud.py
Python
gpl-2.0
2,595
0.004624
# -*- coding: UTF-8 -*- """ Copyright (C) 2014 smokdpi 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. ...
rsCloudResolver(Plugin, UrlResolver, PluginSettings): implements = [UrlResolver, PluginSettings] name = "userscloud" domains = ["userscloud.com"] pattern = '(?://|\.)(userscloud\.com)/(?:embed-)?([0-9a-zA-Z/]+)' def __init__(self): p = self.get_setting('priority') or 100 self.priori...
self.headers = {'User-Agent': self.user_agent} def get_media_url(self, host, media_id): web_url = self.get_url(host, media_id) stream_url = None self.headers['Referer'] = web_url html = self.net.http_GET(web_url, headers=self.headers).content r = re.search('>(eval\(functio...
FrancoisRheaultUS/dipy
dipy/direction/tests/test_pmf.py
Python
bsd-3-clause
3,786
0
import warnings import numpy as np import numpy.testing as npt from dipy.core.gradients import gradient_table from dipy.core.sphere import HemiSphere, unit_octahedron from dipy.direction.pmf import SimplePmfGen, SHCoeffPmfGen, BootPmfGen from dipy.reconst.csdeconv import Constrai
nedSph
ericalDeconvModel from dipy.reconst.dti import TensorModel from dipy.sims.voxel import single_tensor response = (np.array([1.5e3, 0.3e3, 0.3e3]), 1) def test_pmf_from_sh(): sphere = HemiSphere.from_sphere(unit_octahedron) pmfgen = SHCoeffPmfGen(np.ones([2, 2, 2, 28]), sphere, None) # Test that the pmf i...
googleapis/python-dialogflow-cx
samples/generated_samples/dialogflow_v3beta1_generated_test_cases_batch_run_test_cases_sync.py
Python
apache-2.0
1,663
0.000601
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache Lice
nse, 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://w
ww.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed 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 ...
Clinical-Genomics/taboo
genotype/cli/match_cmd.py
Python
mit
3,397
0.000294
"""Cli for matching samples""" import logging import math import click from genotype.constants import TYPES from genotype.match.core import compare_analyses from genotype.store import api from genotype.store.models import Analysis LOG = logging.getLogger(__name__) def log_result(sample_id, result, hide_fail=False...
analysis_obj = sample_obj.analysis(analysis) # compare against all other samples other_analyses = Analysis.query.filter(Analysis.type != analysis) if len(sample_ids) > 1: # compare only with the specified samples sample_filter = Analysis.sample_id.in_(sample_ids) other_analyses ...
s.sample_id, result, hide_fail=True) @click.command("check") @click.argument("sample_id") @click.pass_context def check_cmd(context, sample_id): """Check integrity of a sample.""" LOG.info("Running genotype check") sample_obj = api.sample(sample_id, notfound_cb=context.abort) # 1. check no calls from...
mattaustin/django-thummer
thummer/templatetags/thummer.py
Python
apache-2.0
3,380
0
# -*- coding: utf-8 -*- # # Copyright 2011-2018 Matt Austin # # 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 applicabl...
options = {} for key, expr in self.options: noresolve = {'True': True, 'False': False, 'None': None} value = noresolve.get('{}'.format(expr), expr.resolve(context)) if key == 'options': options.update(value) else: options[key] =...
context.push() context[self.as_var] = thumbnail output = self.nodelist_url.render(context) context.pop() return output def __iter__(self): for node in self.nodelist_url: yield node for node in self.nodelist_empty: yield node
Sefrwahed/alfred-news
alfred_news/models.py
Python
mit
791
0
from alfred.modules.api.a_base_model import ABaseModel class Article(ABaseModel): def __init__(self, title, summary, date, url, image): super().__init__() self.title = title self.summary = sum
mary self.date = date self.url = url self.image = image class Source(ABaseModel): def __init__(self, name, url, category_id): super().__init__() self.name = name self.url = url self.category_id = category_id class Category(ABaseModel): def __init__(sel...
self.name = name def sources(self): lst = [] for source in Source.all(): if str(source.category_id) == str(self.id): lst.append(source) return lst
mizdebsk/pkgdb2
tests/test_groups.py
Python
gpl-2.0
9,297
0.00043
# -*- coding: utf-8 -*- # # Copyright © 2013-2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2, or (at your option) any later # version. This program is distributed...
en" type="hidden" value="')[1].split('">')[0] data = { 'branches': 'master', 'poc': 'spot', 'csrf_token': csrf_token, } output = self.app.post('/package/rpms/guake/give', data=data, follow_redirects
=True) self.assertEqual(output.status_code, 200) self.assertTrue( 'rpms/<span property="doap:name">guake</span>' in output.data) self.assertEqual( output.data.count('<a href="/packager/spot/">'), 2) user.username = 'spot' ...
reyoung/Paddle
python/paddle/fluid/layers/layer_function_generator.py
Python
apache-2.0
10,724
0.000466
# Copyright (c) 2018 PaddlePaddle 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 appli...
gs_lines=None): """ Generate docstring by OpProto Args: op_proto (framework_pb2.OpProto): a protobuf message typed OpProto Returns: str: the document string """ if not isinstance(op_proto, framework_pb2.OpProto): raise TypeError("OpPr
oto should be `framework_pb2.OpProto`") buf = cStringIO() buf.write(escape_math(op_proto.comment)) buf.write('\nArgs:\n') for each_input in op_proto.inputs: line_begin = ' {0}: '.format(_convert_(each_input.name)) buf.write(line_begin) buf.write(escape_math(each_input.comment...
eufarn7sp/egads-eufar
egads/algorithms/thermodynamics/temp_virtual_cnrm.py
Python
bsd-3-clause
3,161
0.016134
__author__ = "mfreer" __date__ = "2011-05-27 14:27" __version__ = "1.0" __all__ = ["TempVirtualCnrm"] import egads.core.egads_core as egads_core import egads.core.metadata as egads_metadata class TempVirtualCnrm(egads_core.EgadsAlgorithm): """ FILE temp_virtual_cnrm.py VERSION 1.0 CA...
'Description':'Calculates virtual temperature given static pressure and mixing ratio', 'Category':'Thermodynamics', 'Source':'CNRM/GMEI/TRAMM', ...
'ProcessorDate':__date__, 'ProcessorVersion':__version__, 'DateProcessed':self.now()}, self.output_metadata) def ...
wang1352083/pythontool
python-2.7.12-lib/test/test_curses.py
Python
mit
11,284
0.004165
# # Test script for the curses module # # This script doesn't actually display anything very coherent. but it # does call (nearly) every method and function. # # Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(), # init_color() # Only called, not tested: getmouse(), ungetmouse() # import os import...
stdscr.bkgd(' ', curses.A_REVERS
E) stdscr.bkgdset(' ') stdscr.bkgdset(' ', curses.A_REVERSE) win.border(65, 66, 67, 68, 69, 70, 71, 72) win.border('|', '!', '-', '_', '+', '\\', '#', '/') with self.assertRaises(TypeError, msg="Expected win.bo...
terranum-ch/GraphLink
graphlink/core/gk_graphic.py
Python
apache-2.0
1,424
0.002107
#!/urs/bin/python import os import graphviz # from gk_node import GKNode # from gk_link import GKLink
class GKGraphic(object): """Manage graphic""" def __init__(self, label=None): self.m_label = label self.m_nodes_list = [] self.m_link_list = [] def add_link(self, link):
"""add link and related node to the diagram""" if link is None: return False self.m_link_list.append(link) if link.m_node1 not in self.m_nodes_list: self.m_nodes_list.append(link.m_node1) if link.m_node2 not in self.m_nodes_list: self.m_nodes...
dashmoment/facerecognition
py/apps/scripts/fisherfaces_example.py
Python
bsd-3-clause
2,253
0.008877
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) Philipp Wagner. All rights reserved. # Licensed under the BSD license. See LICENSE file in the project root for full license information. import sys # append facerec to module search path sys.path.append("../..") # import facerec stuff from facerec.dataset...
estNeighbor(dist_metric=EuclideanDistance(), k=1) # define the model as the combination model = PredictableModel(feature=feature, classifier=classifier) # show fisherfaces model.compute(dataSet.data, dataSet.labels) # turn the first (at most) 16 eigenvectors into grayscale # images (note: eigenvectors are stored by col...
aSet.data[0].shape) E.append(minmax_normalize(e,0,255, dtype=np.uint8)) # plot them and store the plot to "python_fisherfaces_fisherfaces.pdf" subplot(title="Fisherfaces", images=E, rows=4, cols=4, sptitle="Fisherface", colormap=cm.jet, filename="fisherfaces.pdf") # perform a 10-fold cross validation cv = KFoldCros...
liosha2007/plone-groupdocs-comparison-source
src/groupdocs/comparison/testing.py
Python
apache-2.0
653
0
from plone.app.testing import PloneWithPackageLayer from plone.a
pp.testing import IntegrationTesting from plone.app.testing import FunctionalTesting import groupdocs.comparison GROUPDOCS_COMPARISON = PloneWithPackageLayer( zcml_package=groupdocs.comparison, zcml_filename='testing.zcml', gs_profile_id='groupdocs.comparison:testing', name="GROUPDOCS_COMPARISON") G...
CS_COMPARISON_INTEGRATION") GROUPDOCS_COMPARISON_FUNCTIONAL = FunctionalTesting( bases=(GROUPDOCS_COMPARISON, ), name="GROUPDOCS_COMPARISON_FUNCTIONAL")
yelley/sssd-gpo
src/config/SSSDConfigTest.py
Python
gpl-3.0
71,528
0.001566
#!/usr/bin/python ''' Created on Sep 18, 2009 @author: sgallagh ''' import unittest import os from stat import * import sys srcdir = os.getenv('srcdir') if srcdir: sys.path.insert(0, "./src/config") srcdir = srcdir + "/src/config" else: srcdir = "." import SSSDConfig class SSSDConfigTestValid(unittest....
.unlink(of) except: pass #Write out the file sssdc
onfig.write(of) #Verify that the output file has the correct permissions mode = os.stat(of)[ST_MODE] #Output files should not be readable or writable by #non-owners, and should not be executable by anyone self.assertFalse(S_IMODE(mode) & 0177) #Remove the output file ...
simontakite/sysadmin
pythonscripts/webprogrammingwithpython/Working Files/Chapter 2/0206 loops.py.py
Python
gpl-2.0
381
0.015748
#number = 1
#while number < 11: # print(number) # number += 1 # balance = 1000 # rate = 1.02 # years = 0 # while balance < 5000: # balance *= rate # years += 1 # print("It takes " + str(years) + " years to reach $5000.") # for i in [1,2,3,4,5,6,7,8,9,10]: # print(i) #for name in ["Jane", "John", "Matt", "George"]: #...
ange(1,11): print(i)
Finn10111/PimuxBot
pimuxbot.py
Python
gpl-3.0
7,396
0.001893
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pip3 install dnspython import re import random import sleekxmpp import configparser import smtplib from email.mime.text import MIMEText from sqlalchemy import Column, String, Integer, Boolean from sqlalchemy.ext.declarative import declarative_base from collections impor...
print('Database Type is not set.') if db_type == 'postgres':
engine = create_engine('postgresql://%s:%s@%s/%s' % (db_user, db_pass, db_host, db_name)) if db_type == 'mysql': engine = create_engine('mysql+mysqlconnector://%s:%s@%s/%s' % (db_user, db_pass, db_host, db_name)) session = sessionmaker() session.configure(bind=engine) Base.metadata.create_...
ebertti/nospam
contador_linhas.py
Python
mit
581
0.005164
# coding=utf-8 import os import glob import configuracao def main(): for arquivo in glob.glob(configuracao.DATASET_PREPARADO + '/*.csv'): linhas = 0 spam = 0 with op
en(arquivo, 'r') as arquivo_aberto: tupla = arquivo_aberto.readline() while tupla: linhas += 1 if str(tupla).endswith('True"\
n'): spam += 1 tupla = arquivo_aberto.readline() print os.path.basename(arquivo)[:2] + ',' + str(linhas) + ',' + str(spam) if __name__ == "__main__": main()
allmende/synnefo
snf-astakos-app/astakos/test/stress.py
Python
gpl-3.0
6,652
0.000903
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010-2014 GRNET S.A. # # 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 l...
INFO) def random_name(): alphabet = u'abcdef_123490αβγδεζ' length = randint(1, 15) return ''.join(choice(alphabet) for _ in xrange(length)) def random_email(): alphabet = u'abcdef_123490' length = randint(1, 10) first = ''.join(choice(alphabet) for _ in xrange(length)) alph
abet = u'abcdef' length = randint(2, 4) last = ''.join(choice(alphabet) for _ in xrange(length)) return first + '@' + last + '.com' def new_user(): email = random_email() backend = activation_backends.get_backend() try: AstakosUser.objects.get(email=email) return None excep...
thedod/gistodon
gistodon.py
Python
gpl-3.0
8,763
0.005592
import os, sys, re, argparse, time, json, logging import requests from glob import glob from urlparse import urlsplit from getpass import getpass from mastodon import Mastodon from markdown import markdown from html_text import extract_text from flask import (Flask, render_template, abort, request, redirect, jsonif...
dates[0] instance = client_cred_filename[len(args.app_name)+1:-len('.client.secret')] email = args.email if email: user_cred_filename = '{}.{}.{}.user.secret'.format( args.app_name, instance, email.replace('@','.')) else: candidates = glob('{}.{}.*.user.secret'.format( ...
ister.sh first.".format( args.app_name, instance) user_cred_filename = candidates[0] assert \ os.path.exists(client_cred_filename) and \ os.path.exists(user_cred_filename), \ "App/user not registered. Please run register.sh" logging.info("Connecting to {}..."....
Salamek/git-deploy
git_deploy/git_deploy_remote.py
Python
gpl-3.0
2,740
0.015693
""" 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. This program 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 copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ __author__="Adam Sch...
Shell class DeployWorker(threading.Thread): caller = None def __init__(self, caller): super(DeployWorker, self).__init__() self.caller = caller work_list = [] def run(self): while(len(self.work_list) > 0): current, branch, ssh_path, tmp = self.work_list.pop() try: self.sync(tmp...
arante/udacity
cs101/lesson3/different_stooges.py
Python
gpl-3.0
374
0.005348
#!/usr/bin/env
python # -*- coding: utf-8 -*- # Answered by Billy Wilson Arante # Last updated on 2016/12/31 EST # We defined: stooges = ['Moe','Larry','Curly'] # but in
some Stooges films, Curly was # replaced by Shemp. # Write one line of code that changes # the value of stooges to be: stooges[2] = "Shemp" print stooges # but does not create a new List # object.
johankaito/fufuka
microblog/venv/lib/python2.7/site-packages/kazoo/tests/test_counter.py
Python
apache-2.0
883
0
import uuid fr
om nose.tools import eq_ from kazoo.testing import KazooTestCase class KazooCounterTests(KazooTestCase): def _makeOne(self, **kw): path = "/" + uuid.uuid4().hex return self.client.
Counter(path, **kw) def test_int_counter(self): counter = self._makeOne() eq_(counter.value, 0) counter += 2 counter + 1 eq_(counter.value, 3) counter -= 3 counter - 1 eq_(counter.value, -1) def test_float_counter(self): counter = self._m...
jbarriosc/ACSUFRO
LGPL/CommonSoftware/acscourse/ws/src/ACSCOURSE_MOUNTImpl/Mount1.py
Python
lgpl-2.1
2,155
0.015313
#--CORBA STUBS----------------------------------------------------------------- import ACSCOURSE_MOUNT__POA #--ACS Imports----------------------------------------------------------------- from Acspy.Servants.ContainerServices import ContainerServices from Acspy.Servants.ComponentLifecycle import ComponentLifecycle fro...
--------------------------- #--Main defined only for generic testing--------------------------------------- #------------------------------------------------------------------------------ if __name__ == "__main__": import ACSErrTypeACSCourse print "Creating an object" g = Mount1() try: g.objfix(...
ourseImpl.TargetOutOfRangeExImpl(exception=e, create=0) h.Print() print "Done..."
sbobovyc/LabNotes
bk_precision_8500/profile_solarcell.py
Python
gpl-3.0
4,756
0.004626
''' Open Source Initiative OSI - The MIT License:Licensing Tue, 2006-10-31 04:56 nelson The MIT License Copyright (c) 2009 BK Precision 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 re...
of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and t
his permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ...
yrchen/CommonRepo
commonrepo/infor_api/serializers.py
Python
apache-2.0
842
0
# -*- coding: utf-8 -*- # # Copyright 2016 edX PDR Lab, National Central University, Taiwan. # # http://edxpdrlab.ncu.cc/ # # 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://w...
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. # # Created B
y: [email protected] # Maintained By: [email protected] # from __future__ import absolute_import, unicode_literals from rest_framework import serializers
ULHPC/easybuild-easyblocks
easybuild/easyblocks/c/cp2k.py
Python
gpl-2.0
35,231
0.003293
## # Copyright 2009-2017 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
y of # MERCHANTABILITY or FITNE
SS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for building and installing CP2K, implemented as an easyblock @author:...
niklasf/python-prompt-toolkit
prompt_toolkit/contrib/regular_languages/lexer.py
Python
bsd-3-clause
2,621
0.000763
""" `GrammarLexer` is compatible with Pygments lexers and can be used to highlight the input using a regular grammar with token annotations. """ from __future__ import unicode_literals from pygments.token import Token from prompt_toolkit.layout.lexers import Lexer from .compiler import _CompiledGrammar __all__ = ( ...
his part. (This can call other lexers recursively.) If you wish a part of the grammar to just get one token, use a `prompt_toolkit.layout.lexers.SimpleLexer`. """ def __init__(self, compiled_grammar, default_token=None, lexers=None): assert isinst...
tuple) assert lexers is None or all(isinstance(v, Lexer) for k, v in lexers.items()) assert lexers is None or isinstance(lexers, dict) self.compiled_grammar = compiled_grammar self.default_token = default_token or Token self.lexers = lexers or {} def get_tokens(self, cli, ...
teddywing/pubnub-python
python/examples/history.py
Python
mit
1,293
0.007734
## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 ## PubNub Real-time Push APIs and Notifications Framework ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ import sys from pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys....
cipher_key=cipher_key, ssl_on=ssl_on) channel = 'a' # Synchronous usage print pubnub.history(channel, count=2) # Asynchronous usage def callback(message): print(message) pubnub.history(channel, count=2, callback=callback, error=callback) # Synchronous usage print pubnub.history(channel, count=2, include_tok...
callback=callback, error=callback)
benmiroglio/pymatch
pymatch/Matcher.py
Python
mit
21,944
0.003418
from __future__ import print_function from pymatch import * import pymatch.functions as uf class Matcher: """ Matcher Class -- Match data for an observational study. Parameters ---------- test : pd.DataFrame Data representing the test group control : (pd.DataFrame) Data represe...
B4" self.test_color = "#FF7F0E" self.yvar = yvar self.exclude = exclude + [self.yvar] + aux_match self.formula = formula self.nmodels = 1 # for now self.models = [] self.swdata = None self.model_accuracy = [] self.data[yvar] = self.data[yvar].asty...
i != yvar] self.data = self.data.dropna(subset=self.xvars) self.matched_data = [] self.xvars_escaped = [ "Q('{}')".format(x) for x in self.xvars] self.yvar_escaped = "Q('{}')".format(self.yvar) self.y, self.X = patsy.dmatrices('{} ~ {}'.format(self.yvar_escaped, '+'.join(self.xv...
jmmL/misc
eights.py
Python
mit
931
0.022556
def main(): """A simulation-ish of Summer Eights bumps racing""" import random course_length = 1000.0 bung_line_separation = 20 number_of_bung_lines = 12 class Boat: def __init__(self,name,speed,bung_line):
self.name = name self.speed = speed self.bung_line = bung_line def time_to_complete_course(boat): if (random.random() > 0.95): boat.speed *= 0.8 return ((course_length - ((number_of_bung_lines - boat.bung_line) * bung_line_separation)) /...
(time_to_complete_course(univ) < time_to_complete_course(balliol)): print(univ.name + " won!") else: print(balliol.name + " won!") main()
UpSea/thirdParty
pyqtgraph-0.9.10/examples/relativity/relativity.py
Python
mit
28,282
0.013896
import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore from pyqtgraph.parametertree import Parameter, ParameterTree from pyqtgraph.parametertree import types as pTypes import pyqtgraph.configfile import numpy as np import user import collections import sys, os class RelativityGUI(QtGui.QWidget): def __ini...
lf.inertWor
ldlinePlot) self.inertWorldlinePlot.autoRange(padding=0.1) ## reference simulation ref = self.params['Reference Frame'] dur = clocks1[ref].refData['pt'][-1] ## decide how long to run the reference simulation sim2 = Simulation(clocks2, ref=clocks2[ref], duration=dur, dt=d...
bittner/django-media-tree
demo_project/demo_project/urls.py
Python
bsd-3-clause
1,273
0.007855
from media_tree.models import FileNode from media_tree.contrib.views.listing import FileNodeListingView from media_tree.contrib.views.detail import FileNodeDetailView f
rom media_tree.contrib.views.detail.image import ImageNodeDetailView from django.views.generic.base import TemplateView from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^$', TemplateView.as_view( template_name="media_tree/base....
ance a list: queryset=FileNode.objects.filter(level=0), ), name="demo_listing"), url(r'^files/(?P<path>.+)/$', FileNodeDetailView.as_view( queryset=FileNode.objects.filter(extension='txt') ), name="demo_detail"), url(r'^images/(?P<path>.+)/$', ImageNodeDetailView.as_view( query...
soylentdeen/Graffity
src/BCI/IRS16NM.py
Python
mit
4,007
0.010482
import sys sys.path.append('../') import Graffity import numpy import PlotTools import glob import astropy.io.fits as pyfits from scipy import optimize from os import walk from os.path import join def fitGaussian(x, y): errfunc = lambda p, x, y: numpy.abs(p[0]*numpy.exp(-(x**2.0)/(2*p[1]**2.0)) - y) coeffs = [...
iles: SObjName = pyfits.getheader(f).get("ESO INS SOBJ NAME") if SObjName == 'IRS16NW': Grav = Graffity.GRAVITY_Dual_Sci_P2VM(fileBase=f[:-20], processAcqCamData=True) print "Good - %s" %f for i in Grav.AcqCamDat.newS
trehl.data.keys(): FiberOffset = (Grav.MET_SOBJ_DRA[i]**2.0 + Grav.MET_SOBJ_DDEC[i]**2.0)**0.5 offsets[i] = numpy.append(offsets[i], FiberOffset) strehls[i] = numpy.append(strehls[i], Grav.Strehl[i]) flux[i] = numpy.append(flux[i], numpy.mean(Grav.AcqCamDat.TOTALFLUX_SC.d...
haskelladdict/sconcho
sconcho/gui/icons_rc.py
Python
gpl-3.0
575,342
0.000009
# -*- coding: utf-8 -*- # Resource object code # # Created: Sat May 11 12:28:54 2013 # by: The Resource Compiler for PyQt (Qt v4.8.4) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = b"\ \x00\x00\x04\x58\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\...
x8a\xe3\x94\x8b\xa5\ \x92\x5d\x1f\x89\x54\x5b\xac\xf6\x4f\x11\x7f\xf9\x12\x16\x0f\xae\ \x04\x60\x89\x15\xe5\xd9\x4e\x31\x46\x03\x07\xa1
\x45\x29\x18\x3e\ \x52\xd3\xcb\x9f\x79\x47\x0b\xa7\x5a\x29\x95\x46\x16\x32\x99\x41\ \x07\x74\x20\x14\xfa\xef\xbf\xc3\xb6\x1c\x61\xb8\xb2\x49\xf5\x37\ \x20\xbc\x2c\xef\x97\x79\x05\x4c\x2d\x2d\x41\x38\xc5\x8a\xab\x63\ \x9c\xf1\x78\x3a\x3d\x40\x02\x1b\x5f\x01\x72\x95\xb3\xe5\xf2\x88\ \x70\xfe\x0b\x44\xcb\xf0\x2c\x1e\xa0\x...
Cabalist/Mycodo
3.5/cgi-bin/Test-Sensor-HT-AM2315.py
Python
gpl-3.0
302
0
#!/usr/bin/python
import time from tentacle_pi.AM2315 import AM2315 am = AM2315(0x5c, "/dev/i2c-1") for x in range(10): temperature, humidity, crc_check = am.sense() print "Temperat
ure: %s" % temperature print "Humidity: %s" % humidity print "CRC: %s" % crc_check time.sleep(2)
bdestombe/flopy-1
flopy/modflow/mfdrn.py
Python
bsd-3-clause
9,662
0.001035
""" mfdrn module. Contains the ModflowDrn class. Note that the user can access the ModflowDrn class as `flopy.modflow.ModflowDrn`. Additional information for this MODFLOW package can be found at the `Online MODFLOW Guide <http://water.usgs.gov/ogw/modflow/MODFLOW-2005-Guide/index.html?drn.htm>`_. """ import...
model name and .cbc extension (for example, modflowtest.cbc), if ipakcbc is a number greater than zero. If a
single string is passed the package will be set to the string and cbc output names will be created using the model name and .cbc extension, if ipakcbc is a number greater than zero. To define the names for all package files (input and output) the length of the list of strings should...
hunch/hunch-gift-app
django/conf/locale/es_AR/formats.py
Python
mit
735
0.005442
# -*- encoding: utf-
8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j N Y' TIME_FORMAT = r'H:i:s' DATETIME_FORMAT = r'j N Y H:i:s' YEAR_MONTH_FORMAT = r'F Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = r'd/m/Y' SHORT_DATETIME_FORMAT = r'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # 0...
ATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
twiest/openshift-tools
openshift/installer/vendored/openshift-ansible-git-2016-04-18/roles/lib_openshift_api/library/oadm_router.py
Python
apache-2.0
28,872
0.003221
#!/usr/bin/env python # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) | | .` | (_) || | | _|| |) | | ...
.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) def _replace(self, fname, force=False): '''return all pods ''' cmd = ['-n', self.namespace, 'replace', '-f', fname] if force: cmd.append('--force') return self.openshift...
, resource, rname): '''return all pods ''' return self.openshift_cmd(['delete', resource, rname, '-n', self.namespace]) def _get(self, resource, rname=None): '''return a secret by name ''' cmd = ['get', resource, '-o', 'json', '-n', self.namespace] if rname: cmd....
libstorage/libstoragemgmt
tools/smisping/smisping.py
Python
lgpl-2.1
3,066
0
#!/usr/bin/env python2 # Simple tool to see if we have a SMI-S provider talking on the network and # if it has any systems we can test. # # Can use for s
cripting as exit value will be: # 0 if array is online and enumerate systems has some # 1 if we can talk to provider, but no systems # 2 Wrong credentials (Wrong username or password) # 3 Unable to lookup RegisteredName in registered profile (interop support) # 4
if we cannot talk to provider (network error, connection refused etc.) from pywbem import Uint16, CIMError import pywbem import sys DEFAULT_NAMESPACE = 'interop' INTEROP_NAMESPACES = ['interop', 'root/interop', 'root/PG_Interop'] def get_cim_rps(c): cim_rps = [] for n in INTEROP_NAMESPACES: try: ...
nugget/home-assistant
homeassistant/components/vera/cover.py
Python
apache-2.0
2,003
0
"""Support for Vera cover - curtains, rollershutters etc.""" import logging from homeassistant.components.cover import CoverDevice, ENTITY_ID_FORMAT, \ ATTR_POSITION from homeassistant.components.vera import ( VERA_CONTROLLER, VERA_DEVICES, VeraDevice) DEPENDENCIES = ['vera'] _LOGGER = logging.getLogger(__na...
0 is closed, 100 is fully open. """ position = self.vera_device.get_level() if position <= 5: return 0 if position >= 95: return 100 return position def set_cover_position(self, **kwargs): """Move the cover to a specific po
sition.""" self.vera_device.set_level(kwargs.get(ATTR_POSITION)) self.schedule_update_ha_state() @property def is_closed(self): """Return if the cover is closed.""" if self.current_cover_position is not None: return self.current_cover_position == 0 def open_cove...
DataDog/integrations-extras
cyral/tests/conftest.py
Python
bsd-3-clause
479
0.004175
impor
t os import mock import pytest @pytest.fixture() def mock_agent_data(): f_name = os.path.join(os.path.dirname(__file__), 'fixtures', 'a
gent_metrics.txt') with open(f_name, 'r') as f: text_data = f.read() with mock.patch( 'requests.get', return_value=mock.MagicMock( status_code=200, iter_lines=lambda **kwargs: text_data.split("\n"), headers={'Content-Type': "text/plain"} ), ): yie...
ausarbluhd/EternalLLC
scripts/mallory/src/fuzz.py
Python
gpl-2.0
1,915
0.019321
from random import randint overflowstrings = ["A" * 255, "A" * 256, "A" * 257, "A" * 420, "A" * 511, "A" * 512, "A" * 1023, "A" * 1024, "A" * 2047, "A" * 2048, "A" * 4096, "A" * 4097, "A" * 5000, "A" * 10000, "A" * 20000, "A" * 32762, "A" * 32763, "A" * 32764, "A" * 32765, "A" * 32766, "A" * 32767, "A" * 32768, "A" * ...
56x%%x%%s%%p%%n%%d%%o%%u%%c%%h%%l%%q%%j%%z%%Z%%t%%i%%e%%g%%f%%a%%C%%S%%08x"] def bitflipping(data,mangle_percentage = 7): l = len(data) n = int(l*mangle_percentage/100) # 7% of the bytes to be modified for i in range(0,n): # We change the bytes r = randint(0,l-1) data = data[0:r] + chr(ran...
int(0,255)) + data[r+1:] return data def bofinjection(data): l = len(data) r = randint(0,len(overflowstrings)-1) data = data[0:r] + overflowstrings[r] + data[r-l:] return data def fuzz(data, bit_flip_percentage = 20, bof_injection_percentage = 20, bit_flip_density = 7): #print "Fuzz:" ...
rocky/python3-trepan
trepan/processor/cmdbreak.py
Python
gpl-3.0
5,998
0.001334
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2010, 2013, 2015-2018, 2020 Rocky Bernstein # 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 opt...
ner import ScannerError from trepan.processor.location import resolve_location
def set_break( cmd_obj, func, filename, lineno, condition, temporary, args, force=False, offset=None, ): if lineno is None and offset is None: part1 = "I don't understand '%s' as a line number, offset, or function name," % " ".join( args[1:] ) ...
atsareg/VMDIRAC
VMDIRAC/WorkloadManagementSystem/Agent/VirtualMachineMonitorAgent.py
Python
gpl-3.0
9,987
0.039652
""" VirtualMachineMonitorAgent plays the role of the watch dog for the Virtual Machine """ import os import time import glob # DIRAC from DIRAC import S_OK, S_ERROR, gConfig, rootPath from DIRAC.ConfigurationSystem.Client.Helpers import Operations from DIRAC.Core.Base.AgentModule ...
BeforeMargin ) self.log.info( "HeartBeat Period : %d" % self.heartBeatPeriod ) if self.vmID: self.log.info( "DIRAC ID : %s
" % self.vmID ) if self.uniqueID: self.log.info( "Unique ID : %s" % self.uniqueID ) self.log.info( "*************" ) return S_OK() def __declareInstanceRunning( self ): #Connect to VM monitor and register as running retries = 3 sleepTime = 30 for i in range( retries ): ...
MaxIV-KitsControls/netspot
netspot/lib/spotmax/nsinv.py
Python
mit
4,110
0.012895
#!/usr/bin/python -tt """Module to convert data in MongoDB to Ansible inventory JSON.""" # pylint: disable=C0103 import json import os import argparse from netspot import NetSPOT from spotmax import SPOTGroup SPECIAL_FIELDS = ['_id', 'lastModified'] class Host(object): """Class to hold a host.""" def __init_...
nt=4, separators=(',', ': ')) else: return data def main(): """Print Ansible dynamic inventory.""" # Arguments parser = argparse.ArgumentParser(description='MAX IV Network SPOT - netspot') parser.add_argument('-l', '--list', help='List all', action='store_true', required=True) parser.add_argument('-f',...
default=None) args = parser.parse_args() if args.list: if args.filter: print AnsibleInventory(attribute=args.filter, inventory=NetSPOT()) elif os.environ.get('FILTER'): print AnsibleInventory(attribute=os.environ['FILTER'], inventory=NetSPOT()) else: print "Need filter criteria. ...
linkdebian/pynet_course
class4/exercise5.py
Python
apache-2.0
563
0.005329
# Use Netmiko to enter into configuration mode on pynet-rtr2. # Also use Netmiko to verify your state (i.e. that yo
u are currently in configuration mode). from getpass import getpass import time from netmiko import ConnectHandler password = getpass() pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022} ssh_connection = ConnectHandler(**pynet_rtr2) time.sleep(2)...
put
anthrotype/ctypes-binding-generator
test/suite_clang_cindex.py
Python
gpl-3.0
238
0.004202
import sys import unittest import cbind cbind.choose_cindex_impl(cbind.CLA
NG_CINDEX) import suite_all if _
_name__ == '__main__': runner = unittest.TextTestRunner() sys.exit(not runner.run(suite_all.suite_all).wasSuccessful())
amitsaha/learning
python/strings/difflib_closest_match.py
Python
unlicense
697
0.011478
import difflib class Repository: def __init__(self, fname=None): if not fname: fname = '/usr/share/dict/words' with open(f
name) as f: self.repository = [x.rstrip('\n') for x in f.readlines()] def find_close_matches(r, w, count=3): return difflib.get_close_matches(w, r.repository, count) if __name__ == '__main__': r = Repository() w = raw_input('Your word p
lease: ') if len(w.split()) != 1: sys.exit('please enter a word only') try: count = int(raw_input('Number of matches: ')) except ValueError: sys.exit('Enter a number please') print find_close_matches(r, w, count)
witchard/grole
examples/example-async.py
Python
mit
188
0.021277
#!/usr/bin/env p
ython3 import asyncio from grole import Grole app = Grole() @app.route('/(\d+)') async def index(env, req): await asynci
o.sleep( int(req.match.group(1)) ) app.run()
Gaojiaqi/spark-ec2
test_speed_master.py
Python
apache-2.0
789
0.00507
import sys import os import subprocess import time def get_slaves(): slaves = subprocess.check_output(['cat', '/root/spark-ec2/slaves']) return slaves.strip().split('\n') slaves =
get_slaves() for slave in slaves: subprocess.call(['ssh', slave, 'killall', 'iperf3']) subprocess.call(['scp', '/root/spark-ec2/test_speed_slave.py', slave+':/root/']) iperf_master = subprocess.Popen(['iperf3', '-s', '-p', '6789']) iperf_slaves = [] for slave in slaves: iperf_slaves.append(subprocess.che...
1) print "checking slaves speed" for iperf_slave in iperf_slaves: print iperf_slave.strip()
webadmin87/midnight
midnight_news/models.py
Python
bsd-3-clause
2,757
0.003709
from django.core.urlresolvers import reverse from django.db import models from midnight_main.models import BaseTree, Base, BreadCrumbsMixin, BaseComment from ckeditor.fields import RichTextField from django.utils.translation import ugettext_lazy as _ from sorl.thumbnail import ImageField from mptt.fields import TreeMan...
rField(max_length=2000, blank=True, verbose_name=_('Title')) keywords = models.CharField(max_length=2000, blank=True, verbose_name=_('Keywords')) description = models.CharField(max_length=2000, blank=True, verbose_name=_('Description')) def get_absolute_url(self): return reverse('midnight_news:ne...
) def __str__(self): return self.title class Meta: verbose_name = _('NewsItem') verbose_name_plural = _('News') class NewsComment(BaseComment): """ Модель комментария к новости """ obj = models.ForeignKey(News) class Meta: verbose_name = _('NewsCommen...
tuttle/django-new-project-template
src/myproject/myproject/conf/base_settings.py
Python
mit
5,761
0.001389
#@PydevCodeAnalysisIgnore ######################################################################## # This module is a direct copy of the current # django.conf.project_template.settings # Compare when the Django is upgraded. Make your project settings # changes in settings modules that are importing this one. #########...
: 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.Requi
reDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], ...
smathot/quiedit
libquiedit/theme.py
Python
gpl-2.0
3,523
0.026114
# -*- coding: utf-8 -*- """ This file is part of quiedit. quiedit 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. quiedit is distributed i...
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with quiedit. If not, se
e <http://www.gnu.org/licenses/>. """ from PyQt4 import QtGui, QtCore import yaml class theme(object): """Handles theming.""" def __init__(self, editor): """ Constructor. Arguments: editor -- A qtquiedit object. """ self.editor = editor self.themeDict = yaml.load(open(self.editor.get_resource( \ ...
CACTUS-Mission/TRAPSat
rpi/tim/parallel_read_arduino.py
Python
mit
929
0.020452
# For Arduino Data: import serial, signal, sys ################################################################################################ ARDUINO_SERIAL_PORT = '/dev/ttyACM0' # Serial port should be set to the port found in the Arduino Program when programming the board parallel_data_file = "parallel_data_file....
ensures port and file are closed properly def signal_handler(signal, frame): print("Exiting Arduino S
erial Read!") ard_ser.close() file.close() sys.exit(0) # Register signal handler signal.signal(signal.SIGINT, signal_handler) # Read Data From Arduino Serial Port print "Arduino Serial Read Running" while 1: data = ard_ser.read(1) file.write( str(data) )
TUB-Control/PaPI
papi/event/data/DataBase.py
Python
gpl-3.0
1,072
0.008396
#!/usr/bin/python3 #-*- coding: latin-1 -*- """ Copyright (C) 2014 Technische Universität Berlin, Fakultät IV - Elektrotechnik und Informatik, Fachgebiet Regelungssysteme, Einsteinufer 17, D-10587 Berlin, Germany This file is part of PaPI. PaPI is free software: you can redistribute it and/or modify it under the t...
ur option) any later version. PaPI 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 copy of the GNU General Public Li...
e import PapiEventBase class DataBase(PapiEventBase): def __init__(self, oID, destID, operation, opt): super().__init__(oID, destID, 'data_event', operation, opt)
dafrito/trac-mirror
trac/db/tests/util.py
Python
bsd-3-clause
1,572
0.001272
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2013 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consi...
%'''", sql_escape_percent("'''%'''")) self.assertEqual("'''%%'", sql_escape_percent("'''%'")) self.assertEqual("%s", sql_escape_percent("%s")) self.assertEqual("% %", sql_escape_percent("% %")) self.assertEqual("%s %i", sql_escape_percent("%s %i")) self.assertEqual("'%%s'", sql_e...
cape_percent("'%s'")) self.assertEqual("'%% %%'", sql_escape_percent("'% %'")) self.assertEqual("'%%s %%i'", sql_escape_percent("'%s %i'")) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(SQLEscapeTestCase, 'test')) return suite if __name__ == '__main__': un...
wolverineav/horizon-bsn
horizon_bsn/future_enabled/_8005_bsnextensions.py
Python
apache-2.0
356
0
from django.utils.translation import ugettext_lazy as _ # The slug of the pan
el group to be added to HORIZON_CONFIG. Required. PANEL_GROUP = 'bsnextensions' # The display name of the PANEL_GROUP. Required. PANEL_GROUP_NAME = _('BSN Extensions') # The slug of the dashboard t
he PANEL_GROUP associated with. Required. PANEL_GROUP_DASHBOARD = 'bsndashboard'
mlperf/training_results_v0.7
Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/preprocessing.py
Python
apache-2.0
10,808
0.007494
# Lint as: python3 # Copyright 2018 Google 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 applicable law or agr...
records=True, shuffle_examples=True, shuffle_buffer_size=None, filter_amount=0.05, random_rotation=True): """Read tf.Records and prepare them for ingestion by
dual_net. See `read_tf_records` for parameter documentation. Returns a dict of tensors (see return value of batch_parse_tf_example) """ print('Reading tf_records from {} inputs'.format(len(tf_records))) dataset = read_tf_records( batch_size, tf_records, num_repeats=num_repeats, ...
duncan-r/SHIP
ship/fmp/ief.py
Python
mit
11,467
0.002703
""" Summary: Ief file data holder. Contains the functionality for loading ISIS .ief files from disk. Author: Duncan Runnacles Created: 01 Apr 2016 Copyright: Duncan Runnacles 2016 TODO: Updates: """ import os from ship.utils import utilfunctions as uf from ship.utils i...
if the given key does not exist. """ if key in self.event_header.keys(): return self.event_header[key] elif key in self.event_details.keys():
return self.event_details[key] def getIedData(self): """Get all of the ied data stored in this object. There can be multiple ied files referenced by an ief. This will return a dictionary containing all of them. If no ied files are included in the ief file the returned list w...
titilambert/home-assistant
homeassistant/components/homekit/type_cameras.py
Python
apache-2.0
15,437
0.000518
"""Class to hold all camera accessories.""" import asyncio from datetime import timedelta import logging from haffmpeg.core import HAFFmpeg from pyhap.camera import ( VIDEO_CODEC_PARAM_LEVEL_TYPES, VIDEO_CODEC_PARAM_PROFILE_ID_TYPES, Camera as PyhapCamera, ) from pyhap.const import CATEGORY_CAMERA from ho...
de the Home Assistant event loop. """ if self._char_motion_detected: async_track_state_change_event( self.hass, [self.linked_motion_sensor], self._async_update_motion_state_event, ) if self._char_doorbell_detected: ...
event( self.hass, [self.linked_doorbell_sensor], self._async_update_doorbell_state_event, ) await super().run_handler() @callback def _async_update_motion_state_event(self, event): """Handle state change event listener callback.""" ...
tjgavlick/whiskey-blog
app/__init__.py
Python
mit
908
0.002203
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy from app.markdown import markdown from app.function
s import format_price, format_age, format_age_range, \ format_proof, format_date, format_dat
etime, modify_query app = Flask(__name__) app.config.from_object('app.config.DevelopmentConfig') app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals.update(format_price=format_price) app.jinja_env.globals.update(format_age=format_age) app.jinja_env.globals.update(format_age_range...
andrewsosa/hackfsu_com
api/api/migrations/0018_hackathonsponsor_on_mobile.py
Python
apache-2.0
466
0
# -*- codi
ng: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-09 08:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0017_mentorinfo_availability'), ] operations = [ migrations.AddField( ...
), ]
weolar/miniblink49
v8_7_5/tools/clusterfuzz/v8_fuzz_config.py
Python
apache-2.0
1,510
0.003311
# Copyright 2018 the V8 project 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 random # List of configuration experiments for correctness fuzzing. # List of <probability>, <1st config name>, <2nd config name>, <2nd d8>. # Prob...
ndom() def choose_foozzie_flags(self): """Randomly chooses a configuration from FOOZZIE_EXPERIMENTS. Returns: List of flags to pass to v8_foozzie.py fuzz harness. """ acc = 0 threshold = self.rng.random() * 100 for prob, first_config, second_config, second_d8 in FOOZZIE_EXPERIMENTS: ac...
'--second-d8=' + second_d8, ] assert False
RasaHQ/rasa_nlu
tests/nlu/emulators/test_no_emulator.py
Python
apache-2.0
948
0.001055
def test_dummy_request(): from rasa.nlu.emulators.no_emulator import NoEmulator em = NoEmulator() norm = em.normalise_request_json({"text": ["arb text"]}) assert norm == {"text": "arb text", "time": None} norm = em.normalise_request_json({"text": ["arb text"], "time": "1499279161658"}) assert ...
or import NoEmulator em = NoEmulator() data = {"intent": "greet", "text": "hi", "entities": {}, "confidence": 1.0} assert em.normalise_response_json(data) == data def test_emulators_can_handle_missing_d
ata(): from rasa.nlu.emulators.luis import LUISEmulator em = LUISEmulator() norm = em.normalise_response_json( {"text": "this data doesn't contain an intent result"} ) assert norm["prediction"]["topIntent"] is None assert norm["prediction"]["intents"] == {}
jesford/AstroLabels
images/sample.py
Python
mit
481
0.004158
imp
ort numpy as np import matplotlib.pyplot as plt; plt.ion() import matplotlib import seaborn; seaborn.set() from astrolabels import AstroLabels al = AstroLabels() matplotlib.rcParams["axes.labelsize"] = 15 matplotlib.rcParams["legend.fontsize"] = 15 # hopefully your data doesn't look like this... plt.figure(figsize=(...
lt.savefig('sample_plot.png')
ryanhorn/tyoiOAuth2
setup.py
Python
mit
463
0.00216
from setuptools import setup setup( name="tyoi.OAuth2",
version="0.2.1", author="Ryan Horn", author_email="[email protected]", description=("Implements the client side of the OAuth 2 protocol"), keywords="oauth oauth2 auth authentication", url="https://github.com/ryanhorn/tyoiOAuth2", packages=["tyoi", "tyoi.oauth2", "tyoi.oauth2.grants", "ty...
], test_suite="tests", tests_require=["mox"] )
ASCIT/donut-python
donut/modules/voting/ranked_pairs.py
Python
mit
2,107
0.000949
from itertools import chain, combinations, permutations class RankedPairsResult: def __init__(self, tallies, winners): self.tallies = tallies self.winners = winners def results(responses): """ Returns the list of ranked-pairs winners based on responses. Takes as input a list of ranki...
in rank_A: for B in rank_B: tallies[A, B] += 1 def tally_ranking(pair): """ The keyfunction which implements the 'ranking' in ranked pairs. Sorts pairs by highest in favor, or if equal, fewest opposed. """ A, B = pair return (-tal...
# Vertices reachable from A in win graph lower = {A: set((A, )) for A in all_candidates} # Vertices A is reachable from in win graph higher = {A: set((A, )) for A in all_candidates} for A, B in possible_pairs: if A not in lower[B]: # if we don't already have B > A, set A > B for ...
100grams/flask-security
tests/functional_tests.py
Python
mit
9,642
0.000104
# -*- coding: utf-8 -*- from __future__ import with_statement import base64 import simplejson as json from cookielib import Cookie from werkzeug.utils import parse_cookie from tests import SecurityTest def get_cookies(rv): cookies = {} for value in rv.headers.get_all("Set-Cookie"): cookies.update(...
"[email protected]:password") }) self.assertIn('Basic', r.data) def test_multi_auth_token(self): r = self.json_authenticate() data = json.loads(r.data) token = data['response']['user']['authenticat
ion_token'] r = self._get('/multi_auth?auth_token=' + token) self.assertIn('Token', r.data) def test_multi_auth_session(self): self.authenticate() r = self._get('/multi_auth') self.assertIn('Session', r.data) def test_user_deleted_during_session_reverts_to_anonymous_use...
SpectraLogic/ds3_python3_sdk
samples/getService.py
Python
apache-2.0
784
0.002551
# Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" ...
. # This file 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 ds3 import ds3 client = ds3.createClientFromEnv() getServiceResponse = clien
t.get_service(ds3.GetServiceRequest()) for bucket in getServiceResponse.result['BucketList']: print(bucket['Name'])
SalemHarrache/PyVantagePro
setup.py
Python
gpl-3.0
2,383
0.000839
# coding: utf8 ''' PyVantagePro ------------ Communication tools for the Davis VantagePro2 devices. :copyright: Copyright 2012 Salem Harrache and contributors, see AUTHORS. :license: GNU GPL v3. ''' import re import sys import os from setuptools import setup, find_packages here =...
dience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming La...
hon :: 3.2', 'Topic :: Internet', 'Topic :: Utilities', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=find_packages(), zip_safe=False, install_requires=REQUIREMENTS, test_suite='pyvantagepro.tests', entry_points={ 'console_sc...
dayatz/taiga-back
taiga/base/api/settings.py
Python
agpl-3.0
8,478
0.000472
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <[email protected]> # Copyright (C) 2014-2017 Jesús Esp
ino <[email protected]> # Copyright (C) 2014-2017 David Barragán <[email protected]> # Copyright (C) 2014-2017 Alejandro Alonso <[email protected]> # 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 F...
he 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. ...
hammerlab/immuno
immuno/ui.py
Python
apache-2.0
14,247
0.004633
from os import environ, getcwd from os.path import exists, join from common import str2bool, env_var from group_epitopes import group_epitopes_dataframe from hla_file import read_hla_file from immunogenicity import ImmunogenicityPredictor from load_file import expand_transcripts from load_file import load_variants fro...
ABLE_RETYPE_PASSWORD = True USER_ENABLE_USERNAME = False USER_CONFIRM_EMAIL_EXPIRATION = 2 * 24 * 3600 USER_PASSWORD_HASH = 'bcrypt' USER_PASSWORD_HASH_MODE = 'passlib' USER_REQUIRE_INVITATION = False USER_RESET_PASSWORD_EXPIRATION = 2 * 24 * 3600 USER_SEND_PASSWORD_CHANGED_EMAIL = True ...
e USER_SEND_USERNAME_CHANGED_EMAIL = False # Flask-Mail config MAIL_SERVER = environ.get('IMMUNO_MAIL_SERVER') assert MAIL_SERVER, \ "Environment variable IMMUNO_MAIL_SERVER must be set" MAIL_PORT = env_var('IMMUNO_MAIL_PORT', int, 5000) MAIL_USE_SSL = env_var('IMMUNO_MAIL_USE_SSL', str...
keyru/hdl-make
tests/counter/syn/proasic3_sk_libero/verilog/Manifest.py
Python
gpl-3.0
242
0.016529
target = "microsemi" action = "synthesis"
syn_device = "a3p250" syn_grade = "-2" syn_package = "208 pqfp" syn_top = "proasic3_top" syn_project = "demo" syn_t
ool = "libero" modules = { "local" : [ "../../../top/proasic3_sk/verilog" ], }
hdzierz/Kaka
gene_expression/models.py
Python
gpl-2.0
644
0.001553
import mongoeng
ine from mongcore.models import Feature, Species from jsonfield import JSONField # Create your models here. class Target(Feature): species = mongoengine.ReferenceField(Species, default=1) kea_id = mongoengine.StringField(max_length=255) ebrida_id = mongoengine.StringField(max_length=255) file_name ...
pe = mongoengine.StringField(max_length=255) class Gene(Feature): gene_id = mongoengine.StringField(max_length=255) length = mongoengine.IntField()
houshengbo/nova_vmware_compute_driver
nova/tests/baremetal/db/test_bm_interface.py
Python
apache-2.0
2,308
0.000433
# Copyright (c) 2012 NTT DOCOMO, 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 requ...
:11', '0x1', 1) self.assertRaises(exception.DBError, db.bm_interface_create, self.context, 2, '11:11:11:11:11:11', '0x2', 2) # succeed after delete pif1 db.bm_interface_destroy(self.context, pif1_id) ...
, 2) self.assertTrue(pif2_id is not None) def test_unique_vif_uuid(self): pif1_id = db.bm_interface_create(self.context, 1, '11:11:11:11:11:11', '0x1', 1) pif2_id = db.bm_interface_create(self.context, 2, '22:22:22:22:22:22', ...
DailyActie/Surrogate-Model
01-codes/numpy-master/numpy/polynomial/tests/test_hermite_e.py
Python
mit
18,726
0
"""Tests for hermite_e module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.hermite_e as herme from numpy.polynomial.polynomial import polyval from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run...
rmedomain(self): assert_equal(herme.hermedomain, [-1, 1]) def test_hermezero(self): assert_equal(herme.hermezero, [0]) def test_hermeone(self): assert_equal(herme.hermeone, [1]) def test_hermex(self): assert_equal(herme.hermex, [0, 1]) class TestArithmetic(TestCase): ...
d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = herme.hermeadd([0] * i + [1], [0] * j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_hermesub(self): for i in range(5): for j ...
anthonyclays/pyAPT
set_velocity_params.py
Python
mit
1,322
0.020424
#!/usr/bin/env python """ Usage: python get_status.py <acceleration (mm/s/s)> <max velocity (mm/s) [<serial>] Gets the status of all APT controllers, or of the one specified """ import pylibftdi import pyAPT def set_vel_params(serial, acc, max_vel): with pyAPT.MTS50(serial_number=serial) as con: print '\tSettin...
at(args[2]) if
len(args)>3: serial = args[3] else: serial = None if serial: set_vel_params(serial, acc, max_vel) return 0 else: print 'Looking for APT controllers' drv = pylibftdi.Driver() controllers = drv.list_devices() if controllers: for con in controllers: print 'Found %s %s ...
mitnk/letsencrypt
letsencrypt/errors.py
Python
apache-2.0
2,342
0.000854
"""Let's Encrypt client errors.""" class Error(Exception): """Generic Let's Encrypt client error.""" class AccountStorageError(Error): """Generic `.AccountStorage` error.""" class AccountNotFound(AccountStorageError): """Account not found error.""" class ReverterError(Error): """Let's Encrypt Re...
"""Standalone plugin bind error.""" def __init__(self, socket_error, port): super(StandaloneBindError, self).__init__( "Problem binding to port {0}: {1}".format(port, socket_error)) self.socket_error = socket_error self.port = port
class ConfigurationError(Error): """Configuration sanity error.""" # NoninteractiveDisplay iDisplay plugin error: class MissingCommandlineFlag(Error): """A command line argument was missing in noninteractive usage"""
RobotTurtles/mid-level-routines
Apps/TurtleCommands.py
Python
apache-2.0
1,101
0.006358
__author__ = 'Alex' from Movement import Movement class BaseCommand: def __init__(self, movement):
assert isinstance(movement, Movement) self.name = 'unknown' self.m = movement def execute(selfself):pass class Forward(BaseCommand): def __init__(self, movement):
assert isinstance(movement, Movement) self.name = 'forward' self.m = movement def execute(self): self.m.moveCM(10) class Reverse(BaseCommand): def __init__(self, movement): assert isinstance(movement, Movement) self.name = 'reverse' self.m = movement ...
ansible/ansible-lint
src/ansiblelint/rules/MercurialHasRevisionRule.py
Python
mit
1,951
0
# Copyright (c) 2013-2014 Will Thames <[email protected]> # # 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...
ckouts must contain
explicit revision' description = ( 'All version control checkouts must point to ' 'an explicit commit or tag, not just ``latest``' ) severity = 'MEDIUM' tags = ['idempotency'] version_added = 'historic' def matchtask( self, task: Dict[str, Any], file: 'Optional[Lintable]...
AlexandroPQC/django_discusion
SistemaDiscusiones/home/urls.py
Python
gpl-3.0
118
0
fr
om django.conf.urls import url from .views import Inde
xView urlpatterns = [ url(r'^$', IndexView.as_view()), ]
c4fcm/DataBasic
databasic/logic/tfidfanalysis.py
Python
mit
4,459
0.01054
import os import codecs, re, time, string, logging, math from operator import itemgetter from nltk import FreqDist from nltk.corpus import stopwords import textmining from scipy import spatial from . import filehandler def most_frequent_terms(*args): tdm = textmining.TermDocumentMatrix(simple_tokenize_remove_our_s...
ist_of_file_paths): # Create some very short sample documents doc_list = [ filehandler.convert_to_txt(file_path) for file_path in list_of_file_paths ] # Initialize class to create term-document matrix tdm = textmining.TermDocumentMatrix(tokenizer=simple_tokenize_remove_our_stopwords) for doc in doc_...
for row1 in tdm.rows(cutoff=1): if is_first_row1: is_first_row1 = False continue is_first_row2 = True cols = [] for row2 in tdm.rows(cutoff=1): if is_first_row2: is_first_row2 = False continue cols.append(...
maheshp212/find-to-run
findtorun/findtorun/settings.py
Python
apache-2.0
3,920
0.001276
""" Django settings for findtorun project. Generated by 'django-admin startproject' using Django 1.11.2. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import ...
s.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', ...
ps://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'findtorun', 'USER': 'findtorun_user', 'PASSWORD': 'p@$$w0rd111!!!', 'HOST': 'localhost', 'PORT': '5432', 'TEST': { ...
philipgian/pre-commit
pre_commit/output.py
Python
mit
2,217
0
from __future__ import unicode_literals import sys from pre_commit import color from pre_commit import five def get_hook_message( start, postfix='', end_msg=None, end_len=0, end_color=None, use_color=None, cols=80, ): """Prints a message for running a hook...
end_color=color.RED, use_color=True, ) start...........................................................postfix end """ if bool(end_msg) == bool(end_len): raise ValueError('Expected one of (`end_msg`, `end_len`)') if end_msg is not None and (end_color is None or use_color is None)...
else: return '{}{}{}{}\n'.format( start, '.' * (cols - len(start) - len(postfix) - len(end_msg) - 1), postfix, color.format_color(end_msg, end_color, use_color), ) stdout_byte_stream = getattr(sys.stdout, 'buffer', sys.stdout) def write(s, stream=...