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
vxgmichel/aioconsole
example/cli.py
Python
gpl-3.0
2,320
0.000862
"""Command line interface for echo server.""" import fnmatch import asyncio import argparse from aioconsole import AsynchronousCli, start_interactive_server from aioconsole.server import parse_server, print_server from . import echo async def get_history(reader, writer, pattern=None): history = asyncio.get_eve...
r.parse_args(args) host, port = parse_server(namespace.server, parser) if namespace.serve_cli is not None: serve_cli = parse_server(namespace.serve_cli, parser) else: serve_cli = None return host, port, serve_cli def main(args=None): host, port, serve_cli = parse_args(args) if ...
_event_loop().run_until_complete(coro) print_server(server, "command line interface") else: asyncio.ensure_future(make_cli().interact()) return echo.run(host, port) if __name__ == "__main__": main()
psi4/psi4
psi4/driver/molutil.py
Python
lgpl-3.0
9,885
0.004856
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2022 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
NTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Psi4; if not, write to the Free Software Foundation, Inc., # 51 Frankl...
import numpy as np import qcelemental as qcel from psi4 import core from psi4.driver.p4util import temp_circular_import_blocker from psi4.driver import qcdb from psi4.driver.p4util.exceptions import * def molecule_set_attr(self, name, value): """Function to redefine __setattr__ method of molecule class.""" f...
owenson/ardupilot-sdk-python
pymavlink/rotmat.py
Python
lgpl-3.0
12,026
0.004906
#!/usr/bin/env python # # vector3 and rotation matrix classes # This follows the conventions in the ArduPilot code, # and is essentially a python version of the AP_Math library # # Andrew Tridgell, March 2012 # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser...
) self.b = Vector3(0,1,0) self.c = Vector3(0,0,1) def transposed(self):
return Matrix3(Vector3(self.a.x, self.b.x, self.c.x), Vector3(self.a.y, self.b.y, self.c.y), Vector3(self.a.z, self.b.z, self.c.z)) def from_euler(self, roll, pitch, yaw): '''fill the matrix from Euler angles in radians''' cp = cos(pitc...
jordanemedlock/psychtruths
temboo/core/Library/Google/ComputeEngine/Instances/GetInstance.py
Python
apache-2.0
5,317
0.005266
# -*- coding: utf-8 -*- ############################################################################### # # GetInstance # Retrieves information about the specified Instance. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may n...
""" super(GetInstanceInputSet, self)._set_input('Instance', value) def set_Project(self, value): """ Set the value of the Project input for this Choreo. ((required, string
) The ID of a Google Compute project.) """ super(GetInstanceInputSet, self)._set_input('Project', value) def set_RefreshToken(self, value): """ Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token w...
angvp/angelvelasquez-crunchyfrog
cf/config/__init__.py
Python
gpl-3.0
4,652
0.001505
# -*- coding: utf-8 -*- # crunchyfrog - a database schema browser and query tool # Copyright (C) 2008 Andi Albrecht <albrecht.andi@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the G
NU 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 warra
nty 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/>. """Configuration""" import gobject from os.path import ab...
pni-libraries/python-pni
doc/examples/old_examples/test_string2.py
Python
gpl-2.0
494
0.036437
#!/usr/bin/env python from
__future__ import print_function import sys import numpy import pni.io.nx.h5 as nexus f = nexus.create_file("test_string2.nxs",True); d = f.root().create_group("scan_1","NXentry").\ create_group("detector","NXdetector") sa= d.create_field("Listo
fStrings","string",shape=(3,2)) sa[0,0]="safdfdsffdsfd" sa[1,0]="safdsfsfdsffdsfd" sa[2,0]="safdfsfd" print(sa[0,0]) print(sa[1,0]) print(sa[2,0]) print(sa[...]) f.close()
nylas/sync-engine
migrations/versions/004_drafts_as_required_folder.py
Python
agpl-3.0
459
0.006536
"""Drafts as required folder Revision ID: 41a7e825d108 Revises: 269247bc37d3 Create Date: 2014-03-13 21:14:25.652333 """ # revision identifie
rs, used by Ale
mbic. revision = '41a7e825d108' down_revision = '269247bc37d3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('imapaccount', sa.Column('drafts_folder_name', sa.String(255), nullable=True)) def downgrade(): op.drop_column('imapaccount', 'drafts_folder_name')
gx1997/chrome-loongson
third_party/webdriver/python/test/selenium/webdriver/firefox/test_ff_api.py
Python
bsd-3-clause
1,189
0.001682
#!/usr/bin/python # # Copyright 2008-2010 WebDriver committers # Copyright 2008-2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y
ou 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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Licen...
ations under the License. from selenium import webdriver from selenium.test.selenium.webdriver.common import api_examples from selenium.test.selenium.webdriver.common.webserver import SimpleWebServer def setup_module(module): webserver = SimpleWebServer() webserver.start() FirefoxApiExampleTest.webserver...
PhoenixRacing/PhoenixRacingWebApp-noregrets
run_server.py
Python
bsd-3-clause
327
0.003058
from application import app as application from gevent import monkey from socketio.server import SocketIOServer monkey.patch_all() if __name__ == '__main__': # SocketIOServer( # ('', application.config['PORT']), # application, # resource="soc
ket.io").serve_forever() socketio.run(application)
foligny/browsershots-psycopg2
shotserver/shotserver04/accounts/urls.py
Python
gpl-3.0
1,222
0.000818
# browsershots.org - Test your web design in different browsers # Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org> # # Browsershots 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 ...
ceived a cop
y of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ URL configuration for the accounts app. """ __revision__ = "$Rev: 2160 $" __date__ = "$Date: 2007-09-18 19:12:50 -0400 (Tue, 18 Sep 2007) $" __author__ = "$Author: johann $" from django.conf.urls.defaults i...
amoschou/openiv
public/views.py
Python
mpl-2.0
3,942
0.011935
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse from openiv.settings import * # Create your views here. def index(request): return redirect(reverse('public:event')) # Comment the above to have an independent home page. context = { 'imagesource': ...
' + ORGA
NISATION_SHORT_NAME + ' in ' + EVENT_YEAR + '. The organisation was elected by the members of ' + EVENT_HOSTED_BY + '.', 'We represent the ' + EVENT_CITY + ' contingent of a wider choral community across Australia with combined membership of over a thousand nationally in the Australian Intervarsity Choral Societi...
jebaum/neosyntax
rplugin/python3/neosyntax.py
Python
gpl-3.0
8,728
0.007218
import neovim # TODO figure out the python way to do these imports, this is probably wrong import pygments import pygments.lexers import pygments.token @neovim.plugin class Neosyntax(object): def __init__(self, nvim): self.nvim = nvim # swap src_ids. from brefdl: allocate two ids, and swap, a...
+ str(value)) self.msg("--------") # XXX issue with highlight groups # if `:syntax off` is set from vimrc, which is the entire goal of this plugin # then a lot (maybe all) of the language specific highlight groups will never be loaded # e.g., the "Comment" hi...
thonComment" will not. # This isn't great, because I want to maintain the ability of users to modify individual # language highlight groups if they feel like it # I am not going to worry about this just yet, but I will need to find a way to address this eventually # For n...
dpazel/music_rep
tests/transformation_tests/reflection_tests/test_t_chromatic_reflection.py
Python
mit
7,963
0.003014
import unittest import logging from harmoniccontext.harmonic_context import HarmonicContext from harmoniccontext.harmonic_context_track import HarmonicContextTrack from harmonicmodel.secondary_chord_template import SecondaryChordTemplate from harmonicmodel.tertian_chord_template import TertianChordTemplate from struc...
e('tii') chord_ii = chord_t_ii.create_chord(diatonic_tonality) hc_track = HarmonicContextTrack() hc_track.append(HarmonicContext(diatonic_tonality, chord_i, Duration(1))) hc_track.append(HarmonicContext(diatonic_tonality, chord_v_ii, Duration(1))) hc_track.append(HarmonicContext...
tonic_tonality, chord_ii, Duration(1))) TestTChromaticFlip.print_hct(hc_track) tune = [('C:5', (1, 1)), ('E:5', (1, 1)), ('E:5', (1, 1)), ('G:5', (1, 1))] line = TestTChromaticFlip.build_line(tune) cue = DiatonicPitch(5, 'd') tflip = TChromaticReflection(line, hc_track, cue) ...
WeirdCoder/rss-2014-team-3
devel/lib/python2.7/dist-packages/robotbrain/__init__.py
Python
mit
1,010
0.00099
# generated from catkin/cmake/template/__init__.py.in # keep symbol table as clean as possible by deleting all unnecessary symbols from os import path as os_path from sys import path as sys_path from pkgutil import extend_path __extended_path = "/home/rss-student/rss-2014-team-3/src/robotbrain/src".split(";") for p ...
os_path.join(p, __name__ + '.py') if os_path.isfile(src_init_file): __execfiles.append(src_init_file) else: src_init_file = os_path.join(p, __name__, '__init__.py') if os_path.isfile(src_init_file): __execfiles.append(src_init_file) del src_init_file del p d
el os_path del __extended_path for __execfile in __execfiles: with open(__execfile, 'r') as __fh: exec(__fh.read()) del __fh del __execfile del __execfiles
twchad/Adafruit_Python_SSD1351
Adafruit_SSD1351/SSD1351.py
Python
mit
11,355
0.026244
# Copyright (c) 2014 Adafruit Industries # Author: Tony DiCola # # 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, m...
ONTRAST = 0x81 SSD1351_DISPLAYALLON_RESUME = 0xA4 SSD1351_DISPLAYALLON = 0xA5 SSD1351_NORMALDISPLAY = 0xA6 SSD1351_INVERTDISPLAY = 0xA7 SSD1351_DISPLAYOFF = 0xAE SSD1351_DISPLAYON = 0xAF SSD1351_SETDI
SPLAYOFFSET = 0xD3 SSD1351_SETCOMPINS = 0xDA SSD1351_SETVCOMDETECT = 0xDB SSD1351_SETDISPLAYCLOCKDIV = 0xD5 SSD1351_SETPRECHARGE = 0xD9 SSD1351_SETMULTIPLEX = 0xA8 SSD1351_SETLOWCOLUMN = 0x00 SSD1351_SETHIGHCOLUMN = 0x10 SSD1351_SETSTARTLINE = 0x40 SSD1351_MEMORYMODE = 0x20 SSD1351_COLUMNADDR = 0x21 SSD1351_PAGEADDR = ...
omardroubi/Artificial-Intelligence
Projects/Project4/bayesNets/util.py
Python
apache-2.0
25,733
0.014728
# util.py # ------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attri...
02383376L, 1610239915L, 4162939394L, \ 557861574L, 3805706338L, 3832520705L, 1248934879L, 3250424034L, 892335058L, 74323433L, \ 3209751608L, 3213220797L, 3444035873L, 3743886725L, 1783837251L, 610968664L, 580745246L, \ 4041979504L, 201684874L, 2673219253L, 1377283008L, 3497299167L, 2...
808L, 3053320360L, 533627073L, 3026232514L, \ 2340271949L, 867277230L, 868513116L, 2158535651L, 2487822909L, 3428235761L, 3067196046L, \ 3435119657L, 1908441839L, 788668797L, 3367703138L, 3317763187L, 908264443L, 2252100381L, \ 764223334L, 4127108988L, 384641349L, 3377374722L, 126383...
inovtec-solutions/OpenERP
openerp/addons/hr_attendance/__openerp__.py
Python
agpl-3.0
2,163
0.001849
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
g_view.xml', ], 'demo': ['hr_attendance_demo.xml'], 'test': [ 'test/attendance_process.yml', 'test/hr_attendance_report.yml', ], 'installable': True, 'auto_install': False, #web "js": ["static/src/js/attendance.js"], 'qweb' : ["static/src/xml/attendance.xml"], ...
dent:tabstop=4:softtabstop=4:shiftwidth=4:
theetcher/fxpt
fxpt/fx_refsystem/replace_with_ref_dialog_ui2.py
Python
mit
4,622
0.004976
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'replace_with_ref_dialog_ui.ui' # # Created: Fri Nov 18 22:58:33 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Dia...
icalLayout.addLayout(self.horizontalLayout_2) self.verticalLayout.setStretch(0, 1) self.retranslateUi(Dialog) QtCore.QObject.connect(self.uiBTN_saveReplace, QtCore.SIGNAL("clicked()"), Dialog.onSaveReplaceClicked) QtCore.QObject.connect(self.uiBT
N_replace, QtCore.SIGNAL("clicked()"), Dialog.onReplaceClicked) QtCore.QObject.connect(self.uiBTN_cancel, QtCore.SIGNAL("clicked()"), Dialog.onCancelClicked) QtCore.QObject.connect(Dialog, QtCore.SIGNAL("finished(int)"), Dialog.onDialogFinished) QtCore.QMetaObject.connectSlotsByName(Dialog) ...
fluentstream/asterisk-p2p
res/pjproject/tests/pjsua/scripts-pesq/201_codec_l16_16000.py
Python
gpl-2.0
537
0.01676
# $Id: 201_codec_l16_16000.py 369517 2012-07-01 17:28:57Z file $ # from inc_cfg im
port * # Call with L16/16000/1 codec test_param = TestParam( "PESQ codec L16/16000/1 (RX side uses snd dev)", [ InstanceParam("UA1", "--max-calls=1 --add-codec L16/16000/1 --clock-rate 16000 --play-file wavs/input.16.wav --null-audio"), InstanceParam("UA2", "--max-calls=1 --add-
codec L16/16000/1 --clock-rate 16000 --rec-file wavs/tmp.16.wav --auto-answer 200") ] ) if (HAS_SND_DEV == 0): test_param.skip = True pesq_threshold = 3.5
diplomacy/research
diplomacy_research/scripts/dataset/dataset_010_redis.py
Python
mit
3,931
0.00407
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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 rest...
total = None if os.path.exists(PHASES_COUNT_DATASET_PATH): with open(PHASES_COUNT_DATASET_PATH, 'rb') as file: total = len(pickle.load(file)) progress_bar = tqdm(total=total) # Loading dataset and converting LOGGER.info('... Creating redis dataset.') with open(PROTO_DATASET_...
') as file: while True: saved_game_bytes = read_next_bytes(file) if saved_game_bytes is None: break progress_bar.update(1) saved_game_proto = bytes_to_proto(saved_game_bytes, SavedGameProto) save_expert_games(memory_buffer, [bytes_to_zl...
kxgames/kxg
demos/guess_my_number.py
Python
mit
5,672
0.001587
#!/usr/bin/env python3 # vim: tw=76 import kxg import random import pyglet LOWER_BOUND, UPPER_BOUND = 0, 5000 class World(kxg.World): """ Keep track of the secret number, the range of numbers that haven't been eliminated yet, and the winner (if there is one). """ def __init__(self): sup...
ss = random.randint(lower_bound, upper_bound) self >> GuessNumber(self.id, gue
ss) self.reset_timer() def reset_timer(self): self.timer = random.uniform(1, 3) if __name__ == '__main__': kxg.quickstart.main(World, Referee, Gui, GuiActor, AiActor)
Princessgladys/googleresourcefinder
tests/docs_test.py
Python
apache-2.0
2,824
0
from selenium_test_case import Seleniu
mTestCase class DocsTest(SeleniumTestCase): def test_links_between_pages(self): self.open_path('/help') self.assert_text_present('Frequently Asked Questions') self.click_and_wait('link=Terms of Service') self.assert_text_present('Terms of Service for Google Resource Finder') ...
) self.click_and_wait('link=Help') self.assert_text_present('Frequently Asked Questions') def test_languages(self): # English (en) self.open_path('/help?lang=en') self.assert_text_present('Frequently Asked Questions') self.click_and_wait('link=Terms of Service') ...
lisitsky/one-button-ftp
pyftp1.py
Python
mit
15,763
0.004916
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys, time, os, hashlib, atexit import ftplib import traceback from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog from PyQt5.QtWidgets import QPushButton, QHBoxLayout, QVBoxLayout, \ QScrollArea, QLineEdit, QCheckBox, QMessageBox,...
seEvent(self, event): # check and exit workers = len(album_uploaders) if workers > 0: reply = QMessageBox.question(self, 'Закрыть программу?', 'Вы уверены, что хотите выйти? \nСейчас загружается %s альбом(а,ов)' % workers, ...
Yes | QMessageBox.No, QMessageBox.No) if reply != QMessageBox.Yes: event.ignore() return event.accept() class AlbumUploader(QObject): name = '' finished = pyqtSignal() message = pyqtSignal(int) progress_message = pyqtSignal(str, float, bool) file...
hashamali/pyScss
scss/compiler.py
Python
mit
59,822
0.000953
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from __future__ import division from collections import defaultdict from enum import Enum import logging from pathlib import Path import re import sys import warnings try: from collections import O...
ock from scss.selector import Selector from scss.source import SourceFile from scss.types import Arglist from scss.types import List from scss.types import Null from scss.types import Number from scss.types import String from scss.types import Undefined from scss.types import Url from scss.util import normalize_var # ...
tation # TODO or have a little helper (or compiler setting) to turn it on log = logging.getLogger(__name__) _xcss_extends_re = re.compile(r'\s+extends\s+') class OutputStyle(Enum): nested = () compact = () compressed = () expanded = () legacy = () # ??? class SassDeprecationWarning(UserWarni...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isn/neighbors/neighbor/subTLVs/subTLVs_/adjacency_sid/sid/state/__init__.py
Python
apache-2.0
30,567
0.001374
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
lper = False self._extmethods = False self.__value = YANGDynClass( base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..4294967295"]}, int_size=32, ), is_leaf=True,
yang_name="value", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type...
auready/django
tests/admin_docs/test_views.py
Python
bsd-3-clause
14,791
0.003042
import sys import unittest from django.conf import settings from django.contrib.admindocs import utils, views from django.contrib.admindocs.views import get_return_data_type, simplify_regex from django.contrib.sites.models import Site from django.db import models from django.db.models import fields from django.test im...
r Site objects. Deleting settings is fine here as UserSettingsHolder is used. """ Site.objects.all().delete() del settings.SITE_ID response = self.client.get(reverse('django-admindocs-views-index')) self.assertContains(response, 'View documentation') @override_settings(...
ACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }, { 'NAME': 'TWO', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }]) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewWithMultipleEngines(AdminDoc...
kreatorkodi/repository.torrentbr
plugin.video.yatp/site-packages/hachoir_parser/archive/rar.py
Python
gpl-2.0
14,384
0.005284
""" RAR parser Status: can only read higher-level attructures Author: Christophe Gisquet """ from hachoir_parser import Parser from hachoir_core.field import (StaticFieldSet, FieldSet, Bit, Bits, Enum, UInt8, UInt16, UInt32, UInt64, String, TimeDateMSDOS32, NullBytes, NullBits, RawBytes) from hachoir_...
used (solid flag)"
) # The 3 following lines are what blocks more staticity yield Enum(Bits(self, "dictionary_size", 3, "Dictionary size"), DICTIONARY_SIZE) yield Bit(self, "is_large", "file64 operations needed") yield Bit(self, "is_unicode", "Filename also encoded using Unicode") yield Bit(self, "...
podhmo/komet
komet/executors.py
Python
mit
3,149
0.000318
# -*- coding:utf-8 -*- import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChec...
def validation(self, ob=None): self.params = default_validation(self, IEdit, ob) def execute(self, ob): if self.params is None: raise RuntimeError("execute after validation") for k, v in self.params.items(): setattr(ob, k, v) self.context.session.add(ob) ...
(self, IDelete, ob) def execute(self, ob): self.context.session.delete(ob) return ob def create_jsonschema_validation(context, params, ob=None): def customize_schema(schema): schema = copy.deepcopy(schema) # when creating model, id is not needed. if "id" in schema["req...
openpermissions/accounts-srv
accounts/controllers/roles_handler.py
Python
gpl-3.0
1,354
0
# -*- coding: utf-8 -*- # Copyright © 2014-2016 Digital Catapult and The Copyright Hub Foundation # (together the Open Permissions Platfor
m Coalition) # # 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
oundation, 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 ...
BdEINSALyon/resa
account/migrations/0004_auto_20170705_1003.py
Python
gpl-3.0
620
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-07-05 10:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): depende
ncies = [ ('account', '0003_auto_20170705_0958'), ] operations = [ migrations.RenameField( model_name='oauthtoken', old_name='renew_token', new_name='refresh_token', ), migrations.RenameField( model_name='oauthtoken', o...
ew_token_expiration', new_name='refresh_token_expiration', ), ]
opendatatrentino/opendata-harvester
harvester/cli.py
Python
bsd-2-clause
1,858
0
import logging import sys from cliff.app import App from cliff.commandmanager import CommandManager # from .utils import ColorLogFormatter from nicelog.formatters import ColorLineFormatter class HarvesterApp(App): logger = logging.getLogger(__name_
_) def __init__(self): super(HarvesterApp, self).__init__( description='Harvester application CLI', version='0.1', command_manager=CommandManager('harvester.commands')) def configure_logging(self): """ Create logging handlers for any log output. ...
for console """ root_logger = logging.getLogger('') root_logger.setLevel(logging.DEBUG) # Set up logging to a file if self.options.log_file: file_handler = logging.FileHandler( filename=self.options.log_file, ) formatter = log...
apoikos/servermon
hwdoc/vendor/dummy.py
Python
isc
2,909
0.005846
# -*- coding: utf-8 -*- vim:fileencoding=utf-8: # vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab # Copyright © 2010-2012 Greek Research and Technology Network (GRNET S.A.) # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that th...
entations of django management commands Idea is to be able to use it for unit tests and as a reference ''' def power_on(hostname, username, password, **kwargs): ''' Power on command ''' return True def power_off(hostname, username, password, **kwargs): ''' Power off command ''' return...
le(hostname, username, password, **kwargs): ''' Cold boot command ''' return True def power_reset(hostname, username, password, **kwargs): ''' Warm boot command ''' return True def pass_change(hostname, username, password, **kwargs): ''' Change BMC password ''' return T...
ryandoherty/RaceCapture_App
install/hooks/hook-autosportlabs.racecapture.views.configuration.rcp.scriptview.py
Python
gpl-3.0
28
0
hiddenimports
= ['de
cimal']
hollylemos/think-python
chapter-03/3.py
Python
mit
1,541
0.035042
#Problem 1: #Python provides a built-in function called len that returns the length of a string #so the value of len('allen') is 5. #Write a function named right_justify that takes a string named s as a parameter and prints #the string with enough leading spaces so that the last letter of the string is in column 70 #o...
_justify(word): print " " * (70 - len(word)) + word #right_justify(word) #Problem 2: #1. Type this example into a script and test it: #def do_twice(f): #f() #f() #2. Modify do_twice so that it takes two arguments, a
function object and a value, #and calls the function twice, passing the value as an argument. #3. Write a more general version of print_spam, called print_twice, that takes a #string as a parameter and prints it twice. #4. Use the modified version of do_twice to call print_twice twice, passing 'spam' #as an argumen...
lgiordani/punch
tests/test_vcs_configuration.py
Python
isc
7,655
0
import pytest from punch import vcs_configuration as vc @pytest.fixture def global_variables(): return { 'serializer': '{{ major }}.{{ minor }}.{{ patch }}', 'mark': 'just a mark' } @pytest.fixture def vcs_config_dict(): return { 'name': 'git', 'commit_message': "Version...
s, global_variables, special_variables ) assert vcsconf.include_files == ['HISTORY.rst'] def test_vcs_configuration_from_dict_with_include_all_files( vcs_config_dict_with_include_all_files, global_variables, special_variables): vcsconf = vc.VCSConfiguration.from_dict( ...
iguration_from_dict_without_commit_message( vcs_config_dict, global_variables, special_variables): vcs_config_dict.pop('commit_message') vcsconf = vc.VCSConfiguration.from_dict( vcs_config_dict, global_variables, special_variables ) expected_options = { 'make_rel...
fogbow/fogbow-dashboard
openstack_dashboard/dashboards/fogbow/usage/urls.py
Python
apache-2.0
404
0.00495
from django.conf.urls.defaults import patterns # noqa from django.conf.urls.defaults import url # noqa from openstack_dashboard.dashboards.fogbow.usage import views from openstack_dashboard.dashboards.fogbow.usage.views import IndexView urlpatterns = patterns('', url(r'^$', IndexView.as_view(), name='index'), ...
rUsage, name='usage'), )
asanfilippo7/osf.io
api/comments/views.py
Python
apache-2.0
12,700
0.003622
from rest_framework import generics, permissions as drf_permissions from rest_framework.exceptions import NotFound, ValidationError, PermissionDenied from modularodm import Q from modularodm.exceptions import NoResultsFound from api.base.exceptions import Gone from api.base import permissions as base_permissions from...
mments can access this endpoint, and users can only see reports that they have created. ##Links self: th
e canonical api endpoint of this comment ##Actions ###Update Method: PUT / PATCH URL: /links/self Query Params: <none> Body (JSON): { "data": { "type": "comments", # required "...
jeremiah-c-leary/vhdl-style-guide
vsg/vhdlFile/extract/get_n_token_after_tokens.py
Python
gpl-3.0
688
0.001453
from vsg.vhdlFile.extract import tokens def get_n_token_after_tokens(iToken, lTokens, lAllTokens, oTokenMap): lReturn = [] lIndexes = [] for oToken in lTokens: lTemp = oTokenMap.get_token_indexes(oToken) for iTemp in lTemp: iTokenIndex = iTemp for iCount in range(0...
get_index_of_next_non_whitespace_t
oken(iTokenIndex, bExcludeComments=True) lIndexes.append(iTokenIndex) lIndexes.sort() for iIndex in lIndexes: iLine = oTokenMap.get_line_number_of_index(iIndex) lReturn.append(tokens.New(iIndex, iLine, [lAllTokens[iIndex]])) return lReturn
pam-phy/python-notes
byte-of-python/if.py
Python
gpl-2.0
600
0.020833
#!/usr/bin/env python3 number = 23 guess = int(input('Enter an integer : ')) if guess == number: # 新块从这里开始 print('Congratulatio
ns, you guessed it.') print('(but you do not win any pizzas!)') # 新块在这里结束 elif guess < number: # 另一代码块 print('No, it is a little higher than that') # 你可以在此做任何你希望在该代码块内进行的事情 else: print('No, it is a
little lower than that') # 你必须通过猜测一个大于(>)设置数的数字来到达这里 print('Done') # 这最后一句语句将在 # if 语句执行完毕后执行。
conan-io/conan
conans/client/generators/visualstudio.py
Python
mit
5,803
0.00224
import os import re from conans.model import Generator from conans.paths import BUILD_INFO_VISUAL_STUDIO from conans.client.tools.files import VALID_LIB_EXTENSIONS class VisualStudioGenerator(Generator): template = '''<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.micro...
self.conanfile.version if self.conanfile.version else "", 'condition': condition, 'bin_dirs': "".join("%s;" % p for p in build_info.bin_paths), 'res_dirs': "".join("%s;" % p for p in build_info.res_paths), 'include_dirs': "".join("%s;" % p for p in build_info.include_path...
in build_info.lib_paths), 'libs': "".join(['%s.lib;' % lib if not has_valid_ext(lib) else '%s;' % lib for lib in build_info.libs]), 'system_libs': "".join(['%s.lib;' % sys_dep if not has_valid_ext(sys_dep) else '%s;' % sys_dep for ...
barosl/homu
homu/main.py
Python
mit
37,593
0.003937
import argparse import github3 import toml import json import re from . import utils import logging from threading import Thread, Lock import time import traceback import sqlite3 import requests from contextlib import contextmanager from itertools import chain from queue import Queue import os import subprocess from .g...
utosquash', False): msg = '''!!! Temporary commit !!! This commit is artifically made up to mark PR {} as merged. If this commit remained in the history, you can safely reset HEAD to {}. This is possibly due to protected branches, which forbids force-pushing. You are advised to turn off protected branches...
re force-pushing, such as linear history or auto-squashing. [ci skip]'''.format(self.num, self.merge_sha) def inner(): # `merge()` will return `None` if the `head_sha` commit is already part of the `base_ref` branch, which means rebasing didn't have to modify the original commit ...
flungo/python-yaml-config
lib/yamlconfig/config.py
Python
mit
821
0.002436
__author__ = 'Fabrizio Lungo<fab@lungo.co.uk>' import os import yaml from __exceptions__.FileNotFound import FileNotFound from section import ConfigurationSection class Configuration
(ConfigurationSection): def __init__(self, fn='config.yml', name=None, create=False): self._fn = fn self._create = create self.reload() if name is None: name=fn self._name = name def reload(self): if self._create and not os.path.exists(self._fn): ...
lf._config = {} elif os.path.exists(self._fn): with open(self._fn, "r") as f: self._config = yaml.load(f) else: raise FileNotFound(filename=self._fn) def save(self): with open(self._fn, "w") as f: yaml.dump(self._config, f)
daicang/Leetcode-solutions
268-missing-number.py
Python
mit
388
0.028351
class Solution(object): def missingNumber(self, nums):
""" :type nums: List[int] :rtype: int """ xor = len(nums) for i, n in enumerate(nums): xor ^= n xor ^= i return xor inputs = [ [0], [1], [3,0,1], [9,6,4,2,3,5,7,0,1] ] s = Solution(
) for i in inputs: print s.missingNumber(i)
andrebellafronte/stoq
stoqlib/gui/test/test_search.py
Python
gpl-2.0
12,901
0.001783
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2008 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## 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 Foundati...
datetime.date(2007, 1, 15), datetime.date(2007, 1, 31)]: option.get_today_d
ate = lambda: month_day next_month_day = month_day + delta(months=+1) self.assertEqual(option.get_interval(), self._get_month_interval(next_month_day)) class TestSearchEditor(GUITest): """Tests for SearchEditor""" @mock.patch('stoqlib.gui.sear...
sveetch/Sveetoy
project/githubpages_settings.py
Python
mit
428
0
# -*- coding: utf-8 -*- """ Production settings file for project 'project' """ from
project.settings import * DEBUG = False SITE_DOMAIN = 'sveetch.github.io/Sveetoy' # Directory where all stuff will be builded PUBLISH_DIR = os.path.join(PROJECT_DIR, '../docs') # Path where will be moved all the static files, usually this is a directory in # the ``PUBLISH_DIR`` STATIC_DIR =
os.path.join(PROJECT_DIR, PUBLISH_DIR, 'static')
Udzu/pudzu
dataviz/flagstriband.py
Python
mit
3,039
0.014149
from pudzu.charts import * df = pd.read_csv("datasets/flagstriband.csv") df = pd.concat([pd.DataFrame(df.colours.apply(list).tolist(), columns=list("TMB")), df], axis=1).set_index("colours") FONT, SIZE = calibri, 24 fg, bg = "black", "#EEEEEE" default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a4...
row_label=lambda row: label(data.index[row], (100, H)), col_label=lambda col: label(data.columns[col], (W,100)), corner_label=label(middle, (100,100))) return grid PAD = 100 grids = list(generate_batches([grid(c) for c in COLORS], 2)) grid = Image.from_array(grids, padding=(PAD,PAD//2), bg=bg) title = Imag...
ge.from_text_bounded("a catalog of horizontal triband flags".upper(), grid.size, 240, partial(FONT, bold=True), fg=fg, bg=bg, padding=(PAD,20)), ], padding=0) img = Image.from_column([title, grid], bg=bg, padding=(20,0)).pad(10, bg) img.place(Image.from_text("/u/Udzu", FONT(48), fg=fg, bg=bg, padding=10).pad((2,2,0...
somini/gpodder
src/gpodder/escapist_videos.py
Python
gpl-3.0
4,242
0.003772
# -*- coding: utf-8 -*- # # gPodder - A media aggregator and podcast client # Copyright (c) 2005-2014 Thomas Perl and the gPodder Team # # gPodder 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...
eceived a copy of the GNU General Public License # along with this program. If not, see <http
://www.gnu.org/licenses/>. # # # gpodder.escapist - Escapist Videos download magic # somini <somini29@yandex.com>; 2014-09-14 # import gpodder from gpodder import util import logging logger = logging.getLogger(__name__) try: # For Python < 2.6, we use the "simplejson" add-on module import simplejson as ...
ProteinDF/ProteinDF_bridge
proteindf_bridge/modeling.py
Python
gpl-3.0
24,765
0.000371
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 The ProteinDF development team. # see also AUTHORS and README if provided. # # This file is a part of the ProteinDF software package. # # The ProteinDF is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ...
e rmsd_min = 1000.0 for comformer in self._ACE_ALA_NME_comformers: ref_AAN = self._get_ACE_ALA_NME(comformer) (matched, rmsd) = self._match_NME(ref_AAN, res, next_aa) # print(comformer, rmsd) if rmsd < rmsd_min: rms
d_min = rmsd AAN = matched if rmsd_min > 1.0: logger.warn("RMSD value is too large: {}".format(rmsd)) answer = AtomGroup(AAN['3']) answer.path = '/NME' return answer def _match_NME(self, AAN, res, next_aa): '''AAN (ACE-ALA-NME) ''' ...
GeotrekCE/Geotrek-admin
geotrek/trekking/tests/test_models.py
Python
bsd-2-clause
21,282
0.001786
from django.test import TestCase from django.contrib.gis.geos import (LineString, Polygon, MultiPolygon, MultiLineString, MultiPoint, Point) from django.core.exceptions import ValidationError from django.conf import settings from django.test.utils import override_settings from unit...
= False self.trek.save() self.assertIsNone(self.trek.publication_date) def test_date_is_not_updated_when_saved
_again(self): import datetime self.test_takes_current_date_when_published_becomes_true() old_date = datetime.date(2003, 8, 6) self.trek.publication_date = old_date self.trek.save() self.assertEqual(self.trek.publication_date, old_date) class RelatedObjectsTest(Translati...
winstein27/social
social/feed/migrations/0006_post_author.py
Python
agpl-3.0
660
0.001515
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-20 23:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deleti
on class Migration(migrations.Migration): dependencies = [ ('authentication', '0003_auto_20160620_2027'), ('feed', '0005_auto_20160620_1547'), ] operations = [ migrations.AddField( model_name='post', name='author',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='authentication.Profile'), preserve_default=False, ), ]
dokterbob/python-postnl-checkout
tests/test_django.py
Python
agpl-3.0
13,320
0
import datetime import decimal from django.test import TestCase from django.core.cache import cache from httmock import HTTMock from django_dynamic_fixture import G, N from postnl_checkout.contrib.django_postnl_checkout.models import Order from .base import PostNLTestMixin class OrderTests(PostNLTestMixin, TestC...
instance.order_ext_ref, '1105_900' ) self.assertEquals( instance.order_date, self.order_datum ) # Assert JSON values self.assertEquals(instance.prepare_order_request, kwargs) self.assertEquals(instance.prepare_order_response, { 'Check
out': { 'OrderToken': '0cfb4be2-47cf-4eac-865c-d66657953d5c', 'Url': ( 'http://tpppm-test.e-id.nl/Orders/OrderCheckout' '?token=0cfb4be2-47cf-4eac-865c-d66657953d5c' ) }, 'Webshop': { 'IntRef'...
dimbyd/latextree
latextree/parser/bibliography.py
Python
mit
6,260
0.005591
# bibliography.py r''' Defines the BibItem() and Bibliography() classes (both sub-classed from Node) The Bibliography() object is initialized directly from a .bib file using the `bibtexparser` package. We use registry.ClassFactory for unlisted fields ''' import os import logging log = logging.getLogger(__name__) i...
publisher = child.content else:
pass return '%s (%s) %s. %s.' % (author, year, title, publisher) class Bibliography(Command): r''' Bibliography is block command, whose `children` is a list of BibItem objects. This is an example of a Command whicl logically encloses what follows. The data is read from a .bib file then pa...
rbarzic/arty-cm0-designstart
synt/yaml2mmi.py
Python
gpl-2.0
1,294
0.017002
import yaml header=""" <?xml version="1.0" encoding="UTF-8"?> <MemInfo Version="1" Minor="0"> <Processor Endianness="Little" InstPath="design/cortex"> <AddressSpace Name="design_1_i_microblaze_0.design_1_i_microblaze_0_local_memory_dlmb_bram_if_cntlr" Begin="0" End="8191"> <BusBloc...
<AddressRange Begin="0" End="{end_address}"/> <Parity ON="false" NumBits="0"/> </BitLane> """ remap = [3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12] bram = open("bram.yaml", "r") doc = yaml.load(bram) bit_pos = 0 bit_width = 2 output = header # for bram in doc['bram']: for i in range(len(doc['bram'])): bram = do...
dth - 1 data['end_address'] = 16383 data['type'] = 'RAMB36E1' data['placement'] = bram['SITE'].split('_')[1] # remove RAMB36_ in front of the position string bit_pos += bit_width output += bitlane.format(**data) output += footer print output
saltstack/salt
tests/pytests/unit/states/test_openvswitch_port.py
Python
apache-2.0
3,213
0.000934
import pytest import salt.states.openvswitch_port as openvswitch_port from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {openvswitch_port: {"__opts__": {"test": False}}} def test_present(): """ Test to verify that the named port exists on bridge, even...
": { "new": ( "Created GRE tunnel interface salt with remote ip 10.0.0.1" " and key 1 on bridge br-salt." ), "old": ( "No GRE
tunnel interface salt with remote ip 10.0.0.1 and" " key 1 on bridge br-salt present." ), }, }, } ) assert ( openvswitch_port.present( name, bridge, tunnel_type="gre", id=1, r...
hobson/pug
pug/setup_util.py
Python
mit
915
0.006557
# Handy for debugging setup.py """Utilities creating reusable, DRY, setup.py installation scripts Typical usage
in setup.py: >>> global_env, local_env = {}, {} >>> execfile(join('pug', 'setup_util.py'), global_env, local_env) >>> get_variable = local_env['get_variable'] """ import os def setup(*args, **kwargs): print('setup() args = {0
}'.format(args)) print('setup() kwargs = {0}'.format(kwargs)) def get_variable(relpath, keyword='__version__'): """Read __version__ or other properties from a python file without importing it from gist.github.com/technonik/406623 but with added keyward kwarg """ for line in open(os.path.join(os....
taohungyang/cloud-custodian
c7n/output.py
Python
apache-2.0
9,658
0.000207
# Copyright 2015-2017 Capital One Services, 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 agreed ...
for k in blob_outputs.keys(): if path.startswith('%s://' % k): return blob_outputs[k] # Fall back local disk return blob_outputs['file'] @staticmethod def join(*parts): return os.path.join(*parts) def __init__(self, ctx): super(FSOutput, se...
f): return logging.FileHandler( os.path.join(self.root_dir, 'custodian-run.log')) def compress(self): # Compress files individually so thats easy to walk them, without # downloading tar and extracting. for root, dirs, files in os.walk(self.root_dir): for f in...
knimon-software/ffos-meets-closure
tools/sub/download.py
Python
mit
567
0
#!/usr/bin/env python import sys urllib_urlretrieve = None try: # Python 3.x or later import urllib.request urllib_urlretrieve = urllib.request.urlretrieve except ImportError: # Python 2.x import urllib urllib_urlretrieve = urllib.urlretrieve def download(url, target_path): urllib_url
retrieve(url, target_path) if __name__ == '__main__': if len(sys.argv) != 3: print 'Usage: python %s url target_path' % sys.argv[0] sys.exit() url = sys.argv[1] target_p
ath = sys.argv[2] download(url, target_path)
schukinp/python_training
fixture/application.py
Python
apache-2.0
1,091
0.003666
from selenium import webdriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import ContactHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox(capabilities={"marionette": Fa...
f) self.base_url = base_url def is_valid(self): try: self.wd.current_url return True except: return False def open_homepage(self): wd = self.wd if not wd.curren
t_url.endswith("addressbook/"): wd.get(self.base_url) def destroy(self): self.wd.quit()
openstack/nova
nova/api/openstack/compute/keypairs.py
Python
apache-2.0
9,891
0
# Copyright 2011 OpenStack Foundation # 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...
context = req.environ['nova.context'] # handle optional user-id for admin only user_id = user_id or context.user_id context.can(kp_policies.POLICY_ROOT % 'delete',
target={'user_id': user_id}) try: self.api.delete_key_pair(context, user_id, id) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message()) def _get_user_id(self, req): if 'user_id' in req.GET.keys(): ...
dl1ksv/gr-display
python/qa_display_text_msg.py
Python
gpl-3.0
951
0.005258
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020 dl1ksv. # # SP
DX-License-Identifier: GPL-3.0-or-later # from gnuradio import gr, gr_unittest from PyQt5 import Qt import sip # from gnuradio import blocks try: from display import text_msg except ImportError: import os import sys dirname, filename = os.path.split(os.path.abspath(__file__)) sys.path.append(os.pat...
t display_text_msg class qa_display_text_msg(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_instance(self): instance = text_msg('TestString','test',80,None) b = sip.wrapinstance(instance.pyqwidget(),Qt.QWidget)...
ipa-mdl/catkin_pkg
test/test_templates.py
Python
bsd-3-clause
14,395
0.001389
import os import unittest import tempfile import shutil from mock import MagicMock, Mock from catkin_pkg.package_templates import _safe_write_files, create_package_files, \ create_cmakelists, create_package_xml, PackageTemplate, _create_include_macro, \ _create_targetlib_args from catkin_pkg.package import pa...
files(rootdir, pack, 'groovy', {file1: ''}) self.assertTrue(os.path.isfile(file1)) self.assertTrue(os.path.isfile(file2)) finally: shutil.rmtree(rootdir) def test_create_package_template(self): template = PackageTemplate._create_package_template( pack...
]) self.assertEqual('dep1', template.build_depends[0].name) self.assertEqual('dep2', template.build_depends[1].name) def test_parse_generated(self): maint = self.get_maintainer() pack = PackageTemplate(name='bar', package_format=1, ...
ciyer/opensnp-fun
run_plink_reformat.py
Python
mit
886
0.023702
#!/usr/bin/env python # encoding: utf-8 import glob import os import subprocess ''' Convert 23andMe files to PLINK format ''' def twenty3_and_me_files(): """Return the opensnp files that are 23 and me format""" all_twenty3_and_me_files= glob.glob('../opensnp_datadump.current/*.23andme.txt') fifteen_mb = 15 * 100...
ifteen_mb] return non_junk_files def run_plink_format(usable_files): """Reformat the 23andMe files into plink binary stuff""" for f in usable_files: gid = f.split("/")[-1].split("_")[1].replace("file",""
) call = "../plink_v190/plink --23file "+ f + " F" + gid + "ID" + gid + "I 1" call += " --out ../plink_binaries/" + gid print "convert gid " + gid subprocess.call(call,shell=True) usable_files = twenty3_and_me_files() run_plink_format(usable_files)
hadithhouse/hadithhouse
hadiths/initial_data.py
Python
mit
5,391
0.000518
# -*- coding: utf-8 -*- """ Contains data that initially get added to the database to bootstrap it. """ from __future__ import unicode_literals # pylint: disable=invalid-name prophet_muhammad = { 'title': u'Prophet', 'display_name': u'النبي محمد (صلى الله عليه وآله وسلم)'.strip(), 'full_name': u'محمد بن...
افات", u"ص", u"الزمر", u"غافر", u"فصلت", u"الشورى", u"الزخرف", u"الدخان", u"الجاثية", u"اﻷحقاف", u"محمد", u"الفتح", u"الحجرات", u"ق", u"الذاريات", u"الطور", u"النجم", u"القمر", u"الرحمن", u"الواقعة", u"الحديد", u"المج
ادلة", u"الحشر", u"الممتحنة", u"الصف", u"الجمعة", u"المنافقون", u"التغابن", u"الطلاق", u"التحريم", u"الملك", u"القلم", u"الحاقة", u"المعارج", u"نوح", u"الجن", u"المزمل", u"المدثر", u"القيامة", u"اﻹنسان", u"المرسلات", u"النبأ", u"النازعا...
daohu527/leetcode_learning
665. Non-decreasing Array/code.py
Python
gpl-3.0
554
0.001805
class Solution(
object): def checkPoss
ibility(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) t = 0 for i in xrange(n-1): if nums[i] > nums[i+1]: if i-1 < 0 or i+2 > n-1: t += 1 elif nums[i-1] <= nums[i+1]: ...
wisechengyi/pants
src/python/pants/rules/core/test_test.py
Python
apache-2.0
8,678
0.001498
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from abc import ABCMeta, abstractmethod from pathlib import PurePath from textwrap import dedent from typing import List, Tuple, Type from unittest.mock import Mock import pytest from pa...
n from pants.engine.rules import UnionMembership from pants.rules.core.fmt_test import FmtTest from pants.rules.core.test import ( AddressAndTestResult, CoverageDataBatch, CoverageReport, FilesystemCoverageReport, Status, Test, TestDebugRequest, TestResult, TestRunner, WrappedTes...
t import OrderedSet # TODO(#9141): replace this with a proper util to create `GoalSubsystem`s class MockOptions: def __init__(self, **values): self.values = Mock(**values) class MockTestRunner(TestRunner, metaclass=ABCMeta): @staticmethod def is_valid_target(_: TargetAdaptorWithOrigin) -> bool: ...
mfrey/baltimore
analysis/hopcountanalysis.py
Python
gpl-3.0
3,831
0.006004
#!/usr/bin/env python2.7 import logging import numpy as np from .analysis import Analysis class HopCountAnalysis(Analysis): def __init__(self, scenario, location, repetitions, csv): Analysis.__init__(self, scenario, location, "hopCount", repetitions, csv) self.logger = logging.getLogger('baltimo...
ount", node, repetition) for element in data: raw_data.append([repetition, node, float(element[0]), int(element[1])]) if node not in hop_count: hop_count[node] = [] hop_count[node].append(raw_data) raw_data = [] ...
n data for element in repetition] self.data_min[node] = np.amin(hop_count_data) self.data_max[node] = np.amax(hop_count_data) self.data_median[node] = np.median(hop_count_data) self.data_std[node] = np.std(hop_count_data) self.data_avg[node] = np.average(hop_...
KDE/twine2
kbindinggenerator/cmake.py
Python
lgpl-3.0
15,357
0.004428
#!env python # Copyright 2008 Simon Edwards <simon@simonzone.com> # # 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 2 of the License, or # (at your option) any later version. ...
opy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301 USA import re import os.path import glob import kbindinggenerator.cmakeparser as cmakeparser def ExtractInstallFiles(filename=None,input=None,variables=None): if variables is None: variables = {} else: variables = variables.copy() install_list = [] if filename is not...
alobbs/qvm
qvm/qvm-stop.py
Python
apache-2.0
171
0.017544
import os import re i
mport cmd import sys import time import util host = sys.argv[1] cmd.run ("virsh shutdown %s"%(host)) while util.vm_is_running(host): time.slee
p(1)
hryamzik/ansible
lib/ansible/modules/network/cnos/cnos_factory.py
Python
gpl-3.0
5,299
0.00434
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, 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 Licens...
URN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json impor...
llections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=F...
memsharded/conan
conans/test/unittests/util/client_conf_test.py
Python
mit
1,569
0.001275
import os import unittest from conans.client.cache.cache import CONAN_CONF from conans.client.conf import ConanClientConfigParser from conans.paths import DEFAULT_PROFILE_NAME from conans.test.utils.test_files import temp_folder from conans.util.files import save default_client_conf = '''[storage] path: ~/.conan/data...
LE"], "Path/with/quotes") def test_proxies(self): tmp_dir = temp_folder() save(os.path.join(tmp_dir, CONAN_CONF), "") config = ConanClientConfigParser(os.path.join(tmp_dir, CONAN_CONF)) self.assertEqual(None, config.proxies) save(os.path.join(tmp_dir, CONAN_CONF), "[proxies]...
r, CONAN_CONF)) self.assertNotIn("no_proxy", config.proxies) save(os.path.join(tmp_dir, CONAN_CONF), "[proxies]\nno_proxy=localhost") config = ConanClientConfigParser(os.path.join(tmp_dir, CONAN_CONF)) self.assertEqual(config.proxies["no_proxy"], "localhost")
vishdha/erpnext
erpnext/setup/doctype/sales_partner/sales_partner.py
Python
gpl-3.0
1,584
0.024621
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, f
ilter_strip_join from frappe.website.website_generator import WebsiteGenerator from frappe.contacts.address_and_contact import load_address_and_contact class SalesPartner(WebsiteGenerator): website = frappe._dict( page_title_field = "partner_name", condition_field = "show_in_website", template = "templates/gene...
def autoname(self): self.name = self.partner_name def validate(self): if not self.route: self.route = "partners/" + self.scrub(self.partner_name) super(SalesPartner, self).validate() if self.partner_website and not self.partner_website.startswith("http"): self.partner_website = "http://" + self.partne...
mame82/P4wnP1
hidtools/hidsrv9.py
Python
gpl-3.0
10,097
0.029712
#!/usr/bin/python # This file is part of P4wnP1. # # Copyright (c) 2017, Marcus Mengs. # # P4wnP1 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 ...
, as each outputstream is printed in a separate line by the powershell client # dst = 3 (stderr of client) send_datastream(qout, 3, 3, buf) # clear buffer buf = "" else: buf += byte # As we don't pipe CTRL+C intterupt from client through #
HID data stream, there has to be another option to reset the bash process if it stalls # This could easily happen, as we don't support interactive commands, waiting for input # (this non-interactive shell restriction should be a known hurdle to every pentester out there) def reset_bash(subproc): bash = subproc[0] b...
ocadotechnology/django-tastypie
tests/core/tests/fields.py
Python
bsd-3-clause
56,800
0.001268
import datetime from dateutil.tz import tzoffset from decimal import Decimal from django.db import models from django.contrib.auth.models import User from django.test import TestCase from django.http import HttpRequest from tastypie.bundle import Bundle from tastypie.exceptions import ApiFieldError, NotFound from tas...
oo.') self.assertEqual(field_1.use_in, 'all') field_3 = ApiField(use_in="list") self.assertEqual(field_3.use_in, 'list') field_4 = ApiField(use_in="detail") self.assertEqual(field_4.use_in, 'detail') def use_
in_callable(x): return True field_5 = ApiField(use_in=use_in_callable) self.assertTrue(field_5.use_in is use_in_callable) def test_dehydrated_type(self): field_1 = ApiField() self.assertEqual(field_1.dehydrated_type, 'string') def test_has_default(self): fie...
dschep/django-photomap
photomap/migrations/0004_copy_exif_data_to_model.py
Python
mit
1,128
0.003546
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.contrib.gis.geos import geometry from PIL import
Image from PIL.ExifTags import TAGS from ..util import point_from_exif class Migration(DataMigration): def forwards(self, orm): for photo in orm['photomap.Photo'].objects.all(): photo.location = point_from_exif(photo.image.path) photo.save() def backwards(self, orm):
raise NotImplementedError('Too lazy to write a method to write the' ' coordinates to the EXIF of the files') models = { u'photomap.photo': { 'Meta': {'object_name': 'Photo'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': '...
ZhangXFeng/hadoop
src/hadoop-mapreduce1-project/src/contrib/hod/hodlib/AllocationManagers/goldAllocationManager.py
Python
apache-2.0
4,244
0.013431
#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 use thi...
return True else: return False except Exception, e: self.log.error("Unable to parse GOLD responseBody XML \"(%s)\" to get responseVal" % (responseBody)) self.log.debug(get_exception_string())
return (ignoreErrors or False) else: self.log.error("Invalid HTTP statusCode %d" % statusCode) except Exception, e: self.log.error("Unable to POST message to GOLD server (%s, %d)" % (self.__goldHost, self.__goldPort)) self.log.debug(get_exception_string()) ...
noslenfa/tdjangorest
uw/lib/python2.7/site-packages/IPython/terminal/console/tests/test_console.py
Python
apache-2.0
1,726
0.006952
"""Tests for two-process terminal frontend Currently only has the most simp
le test possible, starting a console and running a single command. Authors: * Min RK """ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import sys import time import nose.tools as nt from nose i...
port decorators as dec from IPython.utils import py3compat #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- @dec.skip_win32 def test_console_starts(): """test that `ipython console` starts a termin...
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api_v3/models/work_title_v30_rc2.py
Python
mit
4,930
0.000203
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import si...
return self.to_str() def __eq__(self, ot
her): """Returns true if both objects are equal""" if not isinstance(other, WorkTitleV30Rc2): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
avanzosc/odoo-addons
event_name_code_year_id/tests/test_event_name_code_year_id.py
Python
agpl-3.0
1,353
0
# Copyright
2021 Alfredo de la Fuente - Avanzosc S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.tests import tagged @tagged("post_install", "-at_install") class TestNameCodeYearId(common.SavepointCase): @classmethod def s
etUpClass(cls): super(TestNameCodeYearId, cls).setUpClass() cls.event_obj = cls.env['event.event'] cls.skill_type_lang = cls.env.ref('hr_skills.hr_skill_type_lang') cls.skill_spanish = cls.env.ref('hr_skills.hr_skill_spanish') cls.skill_filipino = cls.env.ref('hr_skills.hr_skill_...
gradiuscypher/internet_illithid
bag_of_holding/libs/user_manager.py
Python
mit
2,633
0.001899
import traceback from sqlalchemy import Column, Boolean, Integer, String, ForeignKey, create_engine from sqlalchemy.orm import relationship, sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine('sqlite:///bag_of_holding.db') Base.metadata...
me :param trait_value :return: """ def remove_profile_trait(self, user_name, service_id, trait_id): """ Add a trait to a service profile :param user_name: :param service_id: :param trait_id :return: """ class User(Base): __tablen...
umn(String) profiles = relationship('UserProfile') def __repr__(self): return '<User(id={})>'.format(self.id) class UserProfile(Base): __tablename__ = 'userprofiles' id = Column(Integer, primary_key=True) service_name = Column(String) service_url = Column(String) profile_id = Colu...
spradeepv/dive-into-python
hackerrank/domain/algorithms/implementation/caesar_cipher/solution.py
Python
mit
1,399
0.002144
def get_encrypted_char(k, ascii_val, ascii_list, limit): diff = k % 26 rotate_val = ascii_val + diff encrypted_char = '' if rotate_val not in ascii_list: rotate_val -= limit for i in ascii_list: rotate_val -= 1 if rotate_val == 0: encrypted_char +=...
for i in range(65, 91)] lower_case_limit = 122 upper_case_limit = 90 encrypted_string = str() for c in s: ascii_val = ord(c) if ascii_val in lower_ascii_list or ascii_val in upper_ascii_list:
limit = lower_case_limit ascii_list = lower_ascii_list if ascii_val in upper_ascii_list: limit = upper_case_limit ascii_list = upper_ascii_list encrypted_string += get_encrypted_char(k, ascii_val, ascii_list, ...
CompassionCH/l10n-switzerland
l10n_ch_fds_upload_sepa/models/account_payment_order.py
Python
agpl-3.0
1,096
0
# -*- coding: utf-8 -*- # © 2015 Compassion CH (Nicolas Tran) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class AccountPaymentOrder(m
odels.Model): _inherit = 'account.payment.order' @api.multi def open2generated(self): """ Replace action to propose upload SEPA file to FDS. :return: window action """ action = super(AccountPaymentOrder, self).open2generated() if self.payment_method
_id.code == 'sepa_credit_transfer': upload_obj = self.env['payment.order.upload.sepa.wizard'] attachment_id = action['res_id'] upload_wizard = upload_obj.create({ 'attachment_id': attachment_id, 'payment_order_id': self.id, }) d...
sboily/flask-blog
flask_blog/plugins/posts/views.py
Python
gpl-3.0
1,743
0.003442
from flask import Blueprint, render_template, redirect, url_for from flask_blog.extensions import mongo fr
om flask_blog.helpers import convertToObj from flask.ext.login import login_required, current_user from forms import PostsForm posts = Blueprint('posts', __name__, template_folder='templates', static_folder='static', static_url_path='/%s' % __name__) @posts.rou
te("/posts") @login_required def list(): posts = mongo.db.posts.find() return render_template('posts_list.html', posts=posts) @posts.route("/posts/add", methods=['GET', 'POST']) @login_required def add(): form = PostsForm() if form.validate_on_submit(): mongo.db.posts.insert(_add_username(form....
esparta/logilab_common3
test/unittest_registry.py
Python
gpl-2.0
6,824
0.001465
# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of Logilab-Common. # # Logilab-Common is free software: you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as publ...
import contextmanager logging.basicConfig(level=logging.ERROR) from logilab.common.testlib
import TestCase, unittest_main from logilab.common.registry import * class _1_(Predicate): def __call__(self, *args, **kwargs): return 1 class _0_(Predicate): def __call__(self, *args, **kwargs): return 0 def _2_(*args, **kwargs): return 2 class SelectorsTC(TestCase): def test_ba...
JohnGiorgi/SRA-RNAseq-Workflow
SRA_RNAseq_Workflow/helpers.py
Python
gpl-3.0
366
0.030055
# /usr/bin/env python
import os # Context manager class cd: """ Context manager for safely changing the current working directory """ def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath)
def __exit__(self, etype, value, traceback): os.chdir(self.savedPath)
Hemisphere-Project/Telemir-DatabitMe
Telemir-EEG/pyacq/pyacq/core/devices/emotiv.py
Python
gpl-2.0
12,623
0.01323
# -*- coding: utf-8 -*- """ Emotiv acquisition : Reverse engineering and original crack code written by Cody Brocious (http://github.com/daeken) Kyle Machulis (http://github.com/qdot) Many thanks for their contribution. Need python-crypto. """ import multiprocessing as mp import numpy as np import msgpack...
annel = sub['nb_channel'], buffer_l
ength = self.buffer_length, packet_size = self.packet_size, dtype = np.float64, channel_names = sub['by_channel_params']['channel_names'], channel_index...
uranusjr/snafu
tests/test_versions.py
Python
isc
4,596
0
import json import pathlib import re import pytest import snafu.versions version_paths = list(snafu.versions.VERSIONS_DIR_PATH.iterdir()) version_names = [p.stem for p in version_paths] @pytest.mark.parametrize('path', version_paths, ids=version_names) def test_version_definitions(path): assert path.suffix ==...
ns, 'metadata', **{ 'get_install_path.return_value':
pathlib.Path(str(tmpdir)), }) version = snafu.versions.get_version('3.6', force_32=False) assert version.is_installed() mock_metadata.get_install_path.assert_called_once_with('3.6')
mozilla/normandy
contract-tests/v3_api/support/assertions.py
Python
mpl-2.0
461
0
import json from
os.path import join, dirname from jsonschema import validate SCHEMA_FILE = "normandy-schema.json" def assert_valid_schema(data): schema = _load_json_schema() return validate(data, schema) def _load_json_schema(): relative_path = join("schemas", SCHEMA_FILE) absolute_path = join(dirnam...
ds(schema_file.read())
tensorflow/addons
tensorflow_addons/seq2seq/decoder.py
Python
apache-2.0
23,035
0.000781
# 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...
rack the reshuffle across time steps. In this case, it is up to the decoder to declare that it will keep track of its own finished state by setting this property to `True`. Returns: Python bool. """ return False class BaseDecoder(tf.keras.layers.Layer): """An RNN...
cell composing the decoder, at each time step. - `state`: (structure of) Tensors and TensorArrays that is passed to the RNN cell instance as the state. - `memory`: tensor that is usually the full output of the encoder, which will be used for the attention wrapper for the RNN cell. - `finished`:...
ethiery/heat-solver
trunk/test_matgen.py
Python
mit
1,289
0.006206
# author : Etienne THIERY from matgen import * import random import numpy def test_symmetricPositiveDefinite(): for i in range(10): print(".", end="", flush=True) size = random.randint(400, 500) maxVal = random.randint(0, 1000) M = symmetricPositiveDefinite(size, maxVal) if...
(M)): return
False return True def test_symmetricSparsePositiveDefinite(): for i in range(10): print(".", end="", flush=True) size = random.randint(400, 500) maxVal = random.randint(0, 1000) nbZeros = random.randint(0, size*(size-1)) M = symmetricSparsePositiveDefinite(size, nbZeros...
fcchou/HelixMC
doc/source/conf.py
Python
gpl-3.0
8,069
0.005453
# -*- coding: utf-8 -*- # # HelixMC documentation build configuration file, created by # sphinx-quickstart on Thu Mar 21 15:51:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
use. #pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'de...
name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sideb...
cdcq/jzyzj
syzoj/update_assistant/misc.py
Python
mit
163
0
fro
m syzoj.models import JudgeState from syzoj import db db.create_all() all_judge = JudgeState.query.all() for item in all_judge: item.update_us
erac_info()
joetainment/mmmmtools
MmmmToolsMod/Dynamic/CapsDisabler.py
Python
gpl-3.0
2,060
0.019417
import subprocess as Subprocess import pymel.all as pm class CapsDisabler(object): def __init__(self, parentRef, go=False): self.parentRef = parentRef self.ini = self.parentRef.ini self.conf = self.ini.conf self.enabled = False self.autohotkeyProcess = Non...
def go(self): try: if int( self.ini.getItem("disable_capslock")
) == 1: self.enabled = True else: #print("Hotkeys not enabled.") pass except: print("\n Could not start CapsLock disabling system or could " "not find info on it's configuration, perhaps because of " "missing info ...
AragurDEV/yowsup
yowsup/layers/protocol_iq/protocolentities/iq.py
Python
gpl-3.0
2,304
0.010417
from yowsup.structs import ProtocolEntity, ProtocolTreeNode class IqProtocolEntity(ProtocolEntity): ''' <iq type="{{get | set}}" id="{{id}}" xmlns="{{xmlns}}" to="{{TO}}" from="{{FROM}}"> </iq> ''' TYPE_SET = "set" TYPE_GET = "get" TYPE_ERROR = "error" TYPE_RESULT = "result" TYPE_D...
super(IqProtocolEntity, self).__init__("iq") assert _type in self.__class__.TYPES, "Iq of type %s is not implemented, can accept only (%s)" % (_type," | ".join(self.__class__.TYPES)) assert not to or not _from, "Can't set from and to at the same time" self._id = self._generateId(True) if ...
self._from = _from self._type = _type self.xmlns = xmlns self.to = to def getId(self): return self._id def getType(self): return self._type def getXmlns(self): return self.xmlns def getFrom(self, full = True): return self._from if full else se...
domcleal/tito
test/unit/test_build_target_parser.py
Python
gpl-2.0
3,872
0.000517
import unittest from tito.buildparser import BuildTargetParser from ConfigParser import ConfigParser from tito.exception import TitoException class BuildTargetParserTests(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.valid_branches = ["branch1", "branch2"] self...
lf.assertTrue("branch1" in release_targets) self.assertEqual("project-x.y.z-candidate", release_targets["branch1"]) def test_multiple_branches_supported(self): self.releasers_config.set(self.release_target, "build_targets",
"branch1:project-x.y.z-candidate branch2:second-target") parser = BuildTargetParser(self.releasers_config, self.release_target, self.valid_branches) release_targets = parser.get_build_targets() self.assertEquals(2, len(release_t...
heraldmatias/django-payroll
src/inei/planilla/forms.py
Python
gpl-3.0
3,110
0.006431
from django.forms.formsets import BaseFormSet, formset_factory from django.forms.models import BaseModelFormSet from django.forms.models import modelformset_factory from django import forms from models import PlanillaHistoricas, ConceptosFolios, Folios, Tomos class PlanillaHistoricasForm(forms.Form): codi_empl_pe...
): kwargs['concepto'] = self.concepto return super(BasePlanillaHistoricasFormSet, self)._construct_form(i, **kwargs) def add_fields(self, form, index): super(BasePlanillaHistoricas
FormSet, self).add_fields(form, index) PlanillaHistoricasFormSet = formset_factory(#form=PlanillaHistoricasForm, form=PlanillaHistoricasForm, formset=BasePlanillaHistoricasFormSet, extra...
lmr/avocado-vt
virttest/utils_disk.py
Python
gpl-2.0
21,332
0.000281
""" Virtualization test - Virtual disk related utility functions :copyright: Red Hat Inc. """ import os import glob import shutil import stat import tempfile import logging import re try: import configparser as ConfigParser except ImportError: import ConfigParser from avocado.core import exceptions from avoca...
options.split(",") options_result = result.split()[3].split(",") for op in options:
if op not in options_result: if verbose: logging.info("%s is not mounted with given" " option %s", src, op) return False if verbose: logging.info("%s is mounted", src) ...
jacekdalkowski/bike-timer
web-api/biketimerwebapi/db/repositories/cassandra/cassandra_repositories_module.py
Python
apache-2.0
1,685
0.005935
from injector import Module from cassandra.cqlengine import connection from cassandra.cluster import Clu
ster from cassandra.cqlengine.management import create_keyspace_simple, sync_table, sync_type from cassandra.cqlengi
ne.usertype import UserType from ...entities.track_type import TrackType from cassandra_users_repository import CassandraUsersRepository from cassandra_spots_repository import CassandraSpotsRepository from runs.cassandra_runs_repository import CassandraRunsRepository from cassandra_checkpoint_passes_repository import C...
dannyp11/gossip_network
main_v2.py
Python
gpl-2.0
4,267
0.023904
import sys, math # **************** Main program ********************************************* def main(): # File IO ############################################### txt = open("in9.txt", 'r') N = int (txt.readline()) n = 2 * N a = [[0 for x in range(1)] for y in range(n)] ...
b return res def sortTwo(a, b): if (a < b): x = a y = b else: x = b y = a return x, y
main()
natecavanaugh/GitGutter
git_gutter_events.py
Python
mit
3,715
0.000538
import time import sublime import sublime_plugin ST3 = int(sublime.version()) >= 3000 if ST3: from .view_collection import ViewCollection from .git_gutter_popup import show_diff_popup else: from view_collection import ViewCollection from git_gutter_popup import show_diff_popup def async_event_listen...
ble(): return if not settings.get("enable_hover_diff_popup"): return show_diff_popup(view, point, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY) # Asynchronous def debounce(self, view, event_type, func): if self.non_blocking: key = (event_type, view.file_nam...
this_keypress = time.time() self.latest_keypresses[key] = this_keypress def callback(): latest_keypress = self.latest_keypresses.get(key, None) if this_keypress == latest_keypress: func(view) if ST3: set_timeout ...
noironetworks/aci-integration-module
aim/tools/cli/commands/config.py
Python
apache-2.0
1,450
0
# Copyright (c) 2016 Cisco Systems # 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 require...
IS, 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. import click from aim import config as aim_cfg from aim import context from aim.db import api from aim.tools.cli.groups import ...
ext def config(ctx): aim_ctx = context.AimContext(store=api.get_store(expire_on_commit=True)) ctx.obj['manager'] = aim_cfg.ConfigManager(aim_ctx, '') @config.command(name='update') @click.argument('host', required=False) @click.pass_context def update(ctx, host): """Current database version.""" host =...