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
Mitali-Sodhi/CodeLingo
Dataset/python/add_api.py
Python
mit
517
0.005803
from time import str
ftime import MySQLdb api_name = raw_input('API Name: ') api_url = raw_input('API URL: ') crawl_frequency = raw_input('API Crawl Frequency(in mins): ') last_crawl = strftime("%H:%M:%S") db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="dataweave") cursor = db.cursor() cursor.execute('''INSERT...
\n'
hongquan/saleor
saleor/dashboard/product/forms.py
Python
bsd-3-clause
1,964
0.000509
from __future__ import unicode_literals from django import forms from django.forms.models import inlineformset_factory from django.fo
rms.widgets import ClearableFileInput from ...product.models import (ProductImage, Product, ShirtVariant, BagVariant, Shirt, Bag) PRODUCT_CLASSES = { 'shirt': Shirt, 'bag': Bag} class ProductClassForm(forms.Form): cls_nam
e = forms.ChoiceField( choices=[(name, name.capitalize()) for name in PRODUCT_CLASSES.keys()]) class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'collection'] class ShirtForm(ProductForm): class Meta: model = Shirt exclud...
34383c/pyNeuroML
pyneuroml/lems/__init__.py
Python
lgpl-3.0
7,440
0.017473
import os.path from pyneuroml.lems.LEMSSimulation import LEMSSimulation import shutil import os from pyneuroml.pynml import read_neuroml2_file, get_next_hex_color, print_comment_v, print_comment import random def generate_lems_file_for_neuroml(sim_id, neuroml_file, ...
save_all_segments = False, gen_saves_for_only = [], # List of populations gen_saves_for_quantities = {},
# Dict with file names vs lists of quantity paths copy_neuroml = True, seed=None): if seed: random.seed(seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for...
cvng/django-geocoder
tests/test_app/tests/test_commands.py
Python
mit
460
0
from unittest import TestCase from django.core.management import call_command from test_app.models import Place class BatchGeoco
deTestCase(TestCase): def setUp(self): self.place = Place() def test_batch_geocode(self): self.place.address = "14 Rue de Rivoli, 75004 Paris, France" self.place.save() call_command(
'batch_geocode') self.place.refresh_from_db() self.assertIsNotNone(self.place.locality)
ayshrimali/Appium-UIAutomation
automation/mobile/uicomponents.py
Python
apache-2.0
2,002
0.004995
#!/usr/bin/env python # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
om enum import Enum from collections import namedtuple class UIComponents: # named tuple to hold two xPath values for each platform Component = namedtuple('Component', ['iOS', 'Android']) LABEL = Component(iOS='//XCUIElementTypeStaticText[{}]', Android='//android.widget.TextView[{
}]') BUTTON = Component(iOS='//XCUIElementTypeButton[{}]', Android='//android.widget.Button[{}]') TEXTFIELD = Component(iOS='//XCUIElementTypeTextField[{}]', Android='//android.widget.EditText[{}]') PWDFIELD = Component(iOS='//XCUIElementTypeSecureTextField[{}]', Android='//android.widget.EditText[{}]') ...
janick/libsoc
bindings/python/spi.py
Python
lgpl-2.1
4,256
0
import sys from ctypes import create_string_buffer from ._libsoc import ( BITS_8, BITS_16, BPW_ERROR, MODE_0, MODE_1, MODE_2, MODE_3, MODE_ERROR, api ) PY3 = sys.version_info >= (3, 0) class SPI(object): def __init__(self, spidev_device, chip_select, mode, speed, bpw): if not isin...
e not recognized') return m def set_speed(self, speed): if not isinstance(speed, int): raise TypeError('Invalid speed must be an "int"') self.speed = speed api.libsoc_spi_set_speed(self._spi, self.speed) def get_speed(self): s = api.libsoc_spi_get_...
buff = create_string_buffer(num_bytes) if api.libsoc_spi_read(self._spi, buff, num_bytes) == -1: raise IOError('Error reading spi device') return buff.raw def write(self, byte_array): assert len(byte_array) > 0 if PY3: buff = bytes(byte_array) ...
vakaras/nmadb-students
src/nmadb_students/models.py
Python
lgpl-3.0
10,676
0.001873
import datetime from django.db import models from django.core import validators from django.utils.translation import ugettext_lazy as _ from nmadb_contacts.models import Municipality, Human class School(models.Model): """ Information about school. School types retrieved from `AIKOS <http://www.aikos.sm...
class Meta(object): ordering = [u'student', u'entered',] verbose_name=_(u'study relation') verbose_name_plural=_(u'study relations') def __unicode__(self): return u'{0.school} ({0.entered}; {0.finished})'.format(self) # FIXME: Diploma should belong to academic, not student. ...
DIPLOMA_TYPE = ( (u'N', _(u'nothing')), (u'P', _(u'certificate')), (u'D', _(u'diploma')), (u'DP', _(u'diploma with honour')), ) student = models.OneToOneField( Student, verbose_name=_(u'student'), ) tasks_solved...
shockflash/medialibrary
medialibrary/models.py
Python
bsd-3-clause
18,049
0.007757
# ------------------------------------------------------------------------ # coding=utf-8 # ------------------------------------------------------------------------ from datetime import datetime from django.contrib import admin, messages from django.contrib.auth.decorators import permission_required from django.conf ...
= _('media file') verbose_name_plural = _('media files') objects = TranslatedObjectManager()
filetypes = [ ] filetypes_dict = { } def formatted_file_size(self): return filesizeformat(self.file_size) formatted_file_size.short_description = _("file size") formatted_file_size.admin_order_field = 'file_size' def formatted_created(self): return self.created.strftime("%Y-%m-%...
zbikowa/python_training
fixture/db.py
Python
apache-2.0
1,332
0.006006
import pymysql.cursors from mod
el.group import Group from model.contact import Contact class DbFixture(): def __init__(self, host, name, user, password): self.host = host self.name = name self.user = user self.password = password
self.connection = pymysql.connect(host=host, database=name, user=user, password=password, autocommit=True) def get_group_list(self): list =[] cursor = self.connection.cursor() try: cursor.execute("select group_id, group_name, group_header, group_footer from group_list")...
nklose/Steganography
gui_main.py
Python
gpl-2.0
15,883
0.002707
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'c:/steganography/main.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _...
t AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(
self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1024, 576) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.group_image = QtGui.QGroupBox(self.centralwidget) self.group_...
PierreBdR/point_tracker
point_tracker/path.py
Python
gpl-2.0
49,237
0.000142
# # Copyright (c) 2010 Mikhail Gusarov # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, d...
_name__ + '_' + module.__name__ bases = (cls,) ns = {'module': module} retur
n type(subclass_name, bases, ns) @ClassProperty @classmethod def _next_class(cls): """ What class should be used to construct new instances from this class """ return cls # --- Special Python methods. def __repr__(self): return '%s(%s)' % (type(self).__name...
g-fleischer/wtfy
trackingserver/thirdparty/pydns/DNS/Opcode.py
Python
gpl-3.0
1,174
0.005963
""" $Id: Opcode.py,v 1.6.2.1 2011/03/16 20:06:39 customdesigned Exp $ This file is part of the pydns project. Homepage: http://pydns.sourceforge.net This code is covered by the standard Python License. See LICENSE for details. Opcode values in message header. RFC 1035, 1996, 2136. """ QUERY = 0 IQUERY = 1 ST...
opcodemap.has_key(opcode): return opcodemap[opcode] else: return `opcode` # # $Log: Opcode.py,v $ # Revision 1.6.2.1 2011/03/16 20:06:39 customdesigned # Refer to explicit LICENSE file. # # Revision 1.6 2002/04/23 10:51:43 anthonybaxter # Added UPDATE, NOTIFY. # # Revision 1.5 2002/03/
19 12:41:33 anthonybaxter # tabnannied and reindented everything. 4 space indent, no tabs. # yay. # # Revision 1.4 2002/03/19 12:26:13 anthonybaxter # death to leading tabs. # # Revision 1.3 2001/08/09 09:08:55 anthonybaxter # added identifying header to top of each file # # Revision 1.2 2001/07/19 06:57:07 anth...
racker/pod-manager
pod_manager/db.py
Python
apache-2.0
603
0.004975
import pickle import redis from pod_manager.settings im
port REDIS_HOST, REDIS_PORT, REDIS_DB __all__ = [ 'get_client', 'cache_object', 'get_object' ] def get_client(): client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) return client def cache_object(client, key, obj, ttl=60): pipe = client.pipeline() data = pickle.dumps(obj) ...
pipe.execute() def get_object(client, key): data = client.get(key) if not data: return None obj = pickle.loads(data) return obj
eroicaleo/LearningPython
PythonForDA/ch04/basic_indexing.py
Python
mit
469
0
import numpy as np arr = np.arange(10) arr arr[5] arr[5:8] arr[5:8] = 12 arr arr_slic
e = arr[5:8] arr_slice arr_slice[1] = 12345 arr arr_slice[:] = 64 arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) arr2d[2] arr2d[0, 2] arr2d[0][2] arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) old_vals = arr3d[0].copy() arr3d[0] = 42 arr3d[1, 0] arr[1:6] arr2d[:2] arr2d[:2, 1:] arr2d[2, ...
] = 0 arr2d
NVIDIAGameWorks/Falcor
Tests/image_tests/renderpasses/test_Skinning.py
Python
bsd-3-clause
276
0.018116
import sys sys.path.append('..') from helpers import render_fr
ames from graphs.ForwardRendering import ForwardRendering as g from falcor import * m.addGraph(g) m.loadScene('Cerberus/Standard/Cerberus.pyscene') # default render_frames(m, 'default', frame
s=[1,16,64]) exit()
kimlaborg/NGSKit
ngskit/utils/codons_info.py
Python
mit
6,184
0.0511
# Codon Usage probability for each scpecie' USAGE_FREQ = {'E.coli':{'GGG': 0.15,'GGA': 0.11,'GGT': 0.34,'GGC': 0.4,\ 'GAG': 0.31,'GAA': 0.69,'GAT': 0.63,'GAC': 0.37,\ 'GTG': 0.37,'GTA': 0.15,'GTT': 0.26,'GTC': 0.22,\ 'GCG': 0.36,...
u'GAA':'E', u'GAG':'E', u'GAT':'D', u'GAC':'D', u'AAA':'K', u'AAG':'K', u'CGT':'R', u'CGC':'R', u'CGA':'R', u'CGG':'R', u'AGA':'R', u'AGG':'R', u'TAA':'*', u'TAG':'*', u'TGA':'*'} # Stop codons dict STOP_DICT = {u'TAA': '*', u'TAG': '*', u'TGA': '*'} STOP_C
ODONS = [u'TAA', u'TAG', u'TGA']
ssarangi/spiderjit
src/ir/irbuilder.py
Python
mit
9,699
0.003197
__author__ = 'sarangis' from src.ir.function import * from src.ir.module import * from src.ir.instructions import * BINARY_OPERATORS = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '**': lambda x, y: x ** y, '/': lambda x, y: x / y, '//': lambda x, y: ...
s, rhs, name=None): folded_inst = self.const_fold_binary_op(lhs, rhs, '-') if folded_inst is not None: return folded_inst sub_inst = SubInst
ruction(lhs, rhs, self.__current_bb, name) self.__add_instruction(sub_inst) return sub_inst def create_mul(self, lhs, rhs, name=None): folded_inst = self.const_fold_binary_op(lhs, rhs, '*') if folded_inst is not None: return folded_inst mul_inst = MulInstruction...
alex-eri/aiohttp-1
aiohttp/client_reqrep.py
Python
apache-2.0
22,547
0.000089
import asyncio import io import json import sys import traceback import warnings from http.cookies import CookieError, Morsel from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy from yarl import URL import aiohttp from . import hdrs, helpers, http, payload from .formdata import FormData fr...
host, port and connection type (ssl).""" # get host/port if not url.host: raise ValueError('Host could not be detected.') # basic auth info username, p
assword = url.user, url.password if username: self.auth = helpers.BasicAuth(username, password or '') # Record entire netloc for usage in host header scheme = url.scheme self.ssl = scheme in ('https', 'wss') def update_version(self, version): """Convert request...
noplay/gns3-gui
scripts/ssh_to_server.py
Python
gpl-3.0
3,813
0.000787
""" This script can be used to ssh to a cloud server started by GNS3. It copies the ssh keys for a server to a temp file on disk and starts ssh using the keys. Right now it only connects to the first cloud server listed in the config file. """ import getopt import os import sys from PyQt4 import QtCore, QtGui SCR...
cmd = 'chmod 0600 {}'.format
(private_key_path) os.system(cmd) print('Per-instance ssh keys written to {}'.format(private_key_path)) cmd = 'ssh -i /tmp/id_rsa root@{}'.format(host) print(cmd) os.system(cmd) elif options['action'] == 'list': print('ID Name IP UID') for idx, info in ...
coddingtonbear/bugwarrior
bugwarrior/services/gitlab.py
Python
gpl-3.0
11,278
0.000621
import re import requests import six from jinja2 import Template from twiggy import log from bugwarrior.config import asbool, die, get_service_password from bugwarrior.services import IssueService, Issue class GitlabIssue(Issue): TITLE = 'gitlabtitle' DESCRIPTION = 'gitlabdescription' CREATED_AT = 'gitl...
context.update({ 'label': self._normalize_label_to_tag(label) }) tags.append( label_template.render(context) )
return tags def get_default_description(self): return self.build_default_description( title=self.record['title'], url=self.get_processed_url(self.extra['issue_url']), number=self.record['iid'], cls=self.extra['type'], ) class GitlabService(IssueSer...
blacked/py-zabbix
zabbix/sender.py
Python
gpl-2.0
198
0
import warnings from pyzabbix import ZabbixMetric, Z
abbixSender warnings.warn("Module '{name}' was deprecated, use 'pyzabbix' instead." "".format(name=__name_
_), DeprecationWarning)
memnonila/taskbuster
taskbuster/apps/taskmanager/migrations/0002_auto_20150708_1158.py
Python
mit
1,290
0.003101
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('taskmanager', '0001_initial'), ] operations = [ migrations.CreateModel( name='Proj...
fields=[ ('id', models.AutoField(verbose_name='ID', auto_creat
ed=True, serialize=False, primary_key=True)), ('name', models.CharField(verbose_name='name', max_length=100, help_text='Enter the project name')), ('color', models.CharField(verbose_name='color', validators=[django.core.validators.RegexValidator('(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)')...
Automattic/trac-code-comments-plugin
code_comments/comment.py
Python
gpl-2.0
6,221
0
# -*- coding: utf-8 -*- import hashlib import json import locale import re import trac.wiki.formatter from trac.mimeview.api import Context from time import strftime, localtime from code_comments import db from trac.util import Markup from trac.web.href import Href from trac.test import Mock, MockPerm def md5_hexdi...
sion-only) # and attachments (path-only), we must always have them both assert self.path and self.revision link_text = self.path + '@' + str(self.re
vision) if self.line: link_text += '#L' + str(self.line) return link_text def changeset_link_text(self): if 0 != self.line: return 'Changeset @%s#L%d (in %s)' % (self.revision, self.line, self.path) else: ...
bukun/bkcase
DevOps/aliyun2_su.py
Python
mit
454
0
#!/usr/bin/env python # encoding: utf-8 from fabric.api import run, env from cfg import aliyun2_cfg from
helper import update_sys env.hosts = ['root@{host}'.format(host=aliyun2_cfg['host'])] env.password = aliyun2_cfg['root_pass'] def restart(): # run('supervisorctl restart drr1') # run('supervisorctl restart drr2') run('supervisorctl restart yunsuan1') run('superv
isorctl restart yunsuan2') run('supervisorctl restart gislab')
flohorovicic/pynoddy
pynoddy/__init__.py
Python
gpl-2.0
7,504
0.002932
"""Package initialization file for pynoddy""" import os.path import sys import subprocess # save this module path for relative paths package_directory = os.path.dirname(os.path.abspath(__file__)) # paths to noddy & topology executables # noddyPath = os.path.join(package_directory,'../noddy/noddy') # topologyPath = os...
h = tp1 elif tp2 is not None: topology_path = tp2 else: raise OSError # convert to string if dvol: dvol = "1" else: dvol = "0" out = "Running topology executable at %s(.exe)\n" % topology_path try: # try running .exe file (windows only) ...
shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE).stdout.read() except OSError: # obviously not running windows - try just the binary out = subprocess.Popen([topology_path, rootname, dvol, str(nvt)], shell=False, ...
MDAnalysis/mdanalysis
testsuite/MDAnalysisTests/lib/test_nsgrid.py
Python
gpl-2.0
15,204
0.001579
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2018 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) #...
tions[ref_id] if searchcoords.shape == (3, ): searchcoords = searchcoords[None, :] # Run grid search searcher = nsgrid.FastNS(cutoff, coords, box=u.dimensions) return searcher.search(searchcoords) @pytest.mark.parametrize('box', [ np.zeros(3), # Bad shape np.zeros((3, 3)), # Collapse...
, [0, 0, 1]], dtype=np.float64), # Box provided as array of double ]) def test_pbc_box(box): """Check that PBC box accepts only well-formated boxes""" coords = np.array([[1.0, 1.0, 1.0]], dtype=np.float32) with pytest.raises(ValueError): nsgrid.FastNS(4.0, coords, box=box) @pytest.mark.parametri...
CloudBoltSoftware/cloudbolt-forge
blueprints/azure_mysql/create.py
Python
apache-2.0
6,543
0.002445
""" Creates an MySql in Azure. """ import settings from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.rdbms import mysql from msrestazure.azure_exceptions import CloudError from common.methods import is_version_newer, set_progress from common.mixins import get_global_id_chars from infras...
id ) mysql_client = mysql.MySQLManagementClient(credentials, handler.serviceaccount) set_progress("Connection to Azure established") return mysql_client def generate_options_for_env_id(server=None, **kwargs): envs = Environment.objects.filter( resource_handler__resource_technolog...
ate options for resource group form field based on the user's selection for Environment. This method requires the user to set the resource_group parameter as dependent on environment. """ if control_value is None: return [] env = Environment.objects.get(id=control_value) if CB_VERSION...
enthought/pyside
tests/QtGui/qimage_test.py
Python
lgpl-2.1
7,077
0.000707
'''Test cases for QImage''' import unittest import py3kcompat as py3k from PySide.QtGui import * from helper import UsesQApplication, adjust_filename xpm = [ "27 22 206 2", " c None", ". c #FEFEFE", "+ c #FFFFFF", "@ c #F9F9F9", "# c #ECECEC", "$ c #D5D5D5", "% c #A0A0A0", ...
2121", "M c #B7B7B7", "N c #F4F4F4", "O c #737373", "P c #828282", "Q c #4D4D4D", "R c #000000", "S c #151515", "T c #B2B2B2", "U c #D6D6D6", "V c #D3D3D3", "W c #2F2F2F", "X c #636363", "Y c #A1A1A1", "Z c #BFBFBF", "` c #E0E0E0", " . c #6A...
C7C7", "&. c #D0D0D0", "*. c #3E3E3E", "=. c #666666", "-. c #DBDBDB", ";. c #424242", ">. c #C2C2C2", ",. c #1A1A1A", "'. c #2C2C2C", "). c #F6F6F6", "!. c #AAAAAA", "~. c #DCDCDC", "{. c #2D2D2D", "]. c #2E2E2E", "^. c #A7A7A7", "/. c #656565", "(. c #33...
akaariai/django-reverse-unique
reverse_unique_tests/settings.py
Python
bsd-3-clause
277
0
SECRET_KEY = 'not-anymore' LANGUAGE_CODE = 'en-u
s' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } INSTALLED_APPS = [ 'reverse_unique', 'revers
e_unique_tests', ]
wakatime/wakatime
wakatime/packages/py27/pygments/styles/manni.py
Python
bsd-3-clause
2,374
0
# -*- coding: ut
f-8 -*- """ pygments.styles.manni ~~~~~~~~~~~~~~~~~~~~~ A colorful style, inspired by the terminal highlighting style. This is a port of the style used in the `php port`_ of pygments by Manni. The style is called 'default' there. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHO...
details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class ManniStyle(Style): """ A colorful style, inspired by the terminal highlighting style. """ background_color = '#f0f3f3' styles = { ...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/application_gateway_web_application_firewall_configuration.py
Python
mit
2,579
0.000775
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ewallDisabledRuleGroup]'}, } def __init__(self, **kwargs): super(ApplicationGat
ewayWebApplicationFirewallConfiguration, self).__init__(**kwargs) self.enabled = kwargs.get('enabled', None) self.firewall_mode = kwargs.get('firewall_mode', None) self.rule_set_type = kwargs.get('rule_set_type', None) self.rule_set_version = kwargs.get('rule_set_version', None) ...
dennereed/paleoanthro
meetings/tests.py
Python
gpl-3.0
31,299
0.005146
# This Python file uses the following encoding: utf-8 from django.test import TestCase, RequestFactory from models import Meeting, Abstract, Author from django.core.urlresolvers import reverse from fiber.models import Page from views import AbstractCreateView from home.models import Announcement from datetime import d...
ate_meeti
ng(year=2020, title='Jamaica 2020', location='Jamaica', associated_with='AAPA'): # """ # Creates a Meeting with default values for year, title, location and associated_with. # """ # return Meeting.object.create(title, year, location=location, associated_with=associated_with) # Factory method to create...
ikoz/mitmproxy
test/netlib/http/http1/test_read.py
Python
mit
10,045
0.000996
from __future__ import absolute_import, print_function, division from io import BytesIO import textwrap from mock import Mock from netlib.exceptions import HttpException, HttpSyntaxException, HttpReadDisconnect, TcpDisconnect from netlib.http import Headers from netlib.http.http1.read import ( read_request, read_re...
sert expected_http_body_size( treq(method=b"HEAD"), tresp(headers=Headers(content_length="42")) ) == 0 assert expected_http_body_size( treq(method=b"CONNECT"), tresp() ) == 0 for code in (100, 204, 304): assert expected_http_body_size( treq(), ...
_code=code) ) == 0 # chunked assert expected_http_body_size( treq(headers=Headers(transfer_encoding="chunked")), ) is None # explicit length for val in (b"foo", b"-7"): with raises(HttpSyntaxException): expected_http_body_size( treq(headers=Heade...
surekap/fabric-recipes
fabfile/config.py
Python
gpl-3.0
725
0.002759
""" Set the configuration variables for fabric recipes. """ from fabric.api import env from fabric.colors import yellow import os env.warn_only = True try: import ConfigParser as cp except ImportError: import configparser as cp # Python 3.0 config = {} _config = cp.SafeConfigParser() if not os.path.isfil...
"): print yellow("warning: No config file specified") _config.read("fabric-recipes.conf") for section in _config.sections(): opt = _config.items(section) if section == "global": env.update(opt) elif section == "roledefs": opt = [(k, v.split(",")) for k, v in
opt] env['roledefs'].update(opt) else: config[section] = dict(opt)
github-borat/cinder
cinder/tests/test_glusterfs.py
Python
apache-2.0
87,804
0
# Copyright (c) 2013 Red Hat, 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 require...
= '/etc/cinder/test-shares.conf' VOLUME_UUID = 'abcdefab-cdef-abcd-efab-
cdefabcdefab' SNAP_UUID = 'bacadaca-baca-daca-baca-dacadacadaca' SNAP_UUID_2 = 'bebedede-bebe-dede-bebe-dedebebedede' def setUp(self): super(GlusterFsDriverTestCase, self).setUp() self._mox = mox_lib.Mox() self._configuration = mox_lib.MockObject(conf.Configuration) self._co...
chiubaka/serenity
server/api/migrations/0004_task_due_date.py
Python
mit
433
0
# -*- coding: utf-8 -*- # Generated by Django 1
.11.6 on 2017-12-09 02:15 from __future__ import unicode_literals from django.db import migrations, models class Mi
gration(migrations.Migration): dependencies = [ ('api', '0003_task_inbox'), ] operations = [ migrations.AddField( model_name='task', name='due_date', field=models.DateField(null=True), ), ]
soneddy/pyrubiks
python/__init__.py
Python
apache-2.0
179
0.01676
#!/usr/bin/env python """ N x N x N Rubik's Cube """ __author__ = "Edwin J. Son <edwin.son@ligo.org>" __version__ = "0.0.
1a" __date__ = "May 27 2017" f
rom cube import cube
AntonSax/plantcv
plantcv/analyze_color.py
Python
mit
11,048
0.003711
# Analyze Color of Object import os import cv2 import numpy as np from . import print_image from . import plot_image from . import fatal_error from . import plot_colorbar def _pseudocolored_image(device, histogram, bins, img, mask, background, channel, filename, resolution, analysis_images, ...
[bins], [0, (bins - 1)])}, "l": {"label": "lightness", "graph_color": "dimgray", "hist": cv2.calcHist([norm_channels["l"]], [0], mask, [bins], [0, (bins - 1)])}, "m": {"label": "green-magenta", "graph_color": "magenta", "hist": cv2.calcHist([norm_channels["m"]], [0], mask, [...
flopezag/fiware-backlog
app/coordination/views.py
Python
apache-2.0
6,105
0.002948
from flask import render_template, flash, request, redirect, url_for from flask_login import login_required from kernel import agileCalendar from kernel.DataBoard import Data from kernel.NM_Aggregates import WorkBacklog, DevBacklog, RiskBacklog from kconfig import coordinationBookByName from . import coordination __a...
agileCalendar) @coordination.route("/docs") @login_required def docs(): cmp = coordinationBookByName['Documentation'] backlog = WorkBacklog(*Data.getGlobalComponent(cmp.key)) if backlog.source == 'store': flash('Data from local storage obtained at {}'.format(backlog.timestamp)) sortedby = requ...
comp=cmp, reporter=backlog, sortedby=sortedby, calendar=agileCalendar) @coordination.route("/agile") @login_required def agile(): cmp = coordinationBookByName['Agile'] backlog = WorkBacklog(*Data.getGlobalComponent(c...
Spiderlover/Toontown
toontown/pets/PetChase.py
Python
mit
2,267
0.003529
from pandac.PandaModules import * from direct.showbase.PythonUtil import reduceAngle from otp.movement import Impulse import math class PetChase(Impulse.Impulse): def __init__(self, target = None, minDist = None, moveAngle = None): Impulse.Impulse.__init__(self) self.target = target if min...
ward = self.mover.getFwdSpeed() else: vForward = 0 distanceLeft = distance - self.minDist if distance > self.minDist and vForward * dt > distanceLeft: vForward = distanceLeft / dt if vForward: self.vel.setY(vForward) self.mover.addShove(sel...
H: self.rotVel.setX(vH) self.mover.addRotShove(self.rotVel) def setMinDist(self, minDist): self.minDist = minDist
davelab6/fontbakery
tools/fontbakery-fix-opentype-names.py
Python
apache-2.0
1,293
0.000773
#!/usr/bin/env python # coding: utf-8 # Copyright 2013 The Font Bakery 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/LIC...
License. # # See AUTHORS.txt for the list of Authors and LICENSE.txt for the License import argparse import os import os.path from bakery_cli.fixers import FamilyAndStyleNameFixer description = 'Fixes TTF NAME table naming values to work w
ith Windows GDI' parser = argparse.ArgumentParser(description=description) parser.add_argument('ttf_font', nargs='+', help='Font in OpenType (TTF/OTF) format') parser.add_argument('--autofix', action='store_true', help='Apply autofix') args = parser.parse_args() for path in args.ttf_font: if ...
moschlar/SAUCE
migration/versions/425be68ff414_event_enroll.py
Python
agpl-3.0
1,427
0.002803
"""event_enroll Revision ID: 425be68ff414 Revises: 3be6a175f769 Create Date: 2013-10-28 11:22:00.036581 """ # # # SAUCE - System for AUtomated Code Evaluation # # Copyright (C) 2013 Moritz Schlarb # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero Gen...
have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # revision identifiers, used by Alembic. revision = '425be68ff414' down_revision = '3be6a175f769' from alembic import op #from alembic.operations import Operations as op import sq...
lchemy as sa event_enroll = sa.Enum('event', 'lesson', 'lesson_team', 'team', 'team_new', name='event_enroll') def upgrade(): event_enroll.create(op.get_bind(), checkfirst=False) op.add_column('events', sa.Column('enroll', event_enroll, nullable=True)) def downgrade(): event_enroll.drop(op.get_bind(), ...
Lana-B/Pheno4T
madanalysis/layout/plotflow.py
Python
gpl-3.0
19,086
0.009693
################################################################################ # # Copyright (C) 2012-2013 Eric Conte, Benjamin Fuks # The MadAnalysis development team, email: <ma5team@iphc.cnrs.fr> # # This file is part of MadAnalysis 5. # Official website: <https://launchpad.net/madanalysis5> # # MadAnal...
self.Initi
alizeHistoFrequency(ihisto) # Creating plots for i in range(0,len(self.detail)): self.detail[i].FinalizeReading() self.detail[i].ComputeScale() self.detail[i].CreateHistogram() def InitializeHistoFrequency(self,ihisto): import numpy #...
biddyweb/phaul
phaul/p_haul_vz.py
Python
lgpl-2.1
4,747
0.030335
# # Virtuozzo containers hauler module # import os import shlex import p_haul_cgroup import util import fs_haul_shared import fs_haul_subtree name = "vz" vz_dir = "/vz" vzpriv_dir = "%s/private" % vz_dir vzroot_dir = "%s/root" % vz_dir vz_conf_dir = "/etc/vz/conf/" vz_pidfiles = "/var/lib/vzctl/vepid/" cg_image_name ...
h_to_fs(self.__ct_priv()) if not rootfs: print "CT is on unknown FS" return None print "CT is on %s" % rootfs if rootfs == "nfs": return fs_haul_shared.p_haul_fs() if rootfs == "ext3" or rootfs == "ext4": return fs_haul_subtree.p_haul_fs(self.__ct_priv()) print "Unknown CT FS" return None d...
pidfile = open(os.path.join(vz_pidfiles, self._ctid), 'w') pidfile.write("%d" % pid) pidfile.close() self.__apply_cg_config() def net_lock(self): for veth in self._veths: util.ifdown(veth.pair) def net_unlock(self): for veth in self._veths: util.ifup(veth.pair) if veth.link and not self._bridge...
cwoodall/doppler-gestures-py
tests/test.py
Python
mit
116
0.008621
import nose def tes
t_nose_working():
""" Test that the nose runner is working. """ assert True
futuresimple/triggear
tests/hook_details/test_hook_details.py
Python
mit
911
0
import pytest from mockito import mock from app.hook_details.hook_details import HookDetails pytestmark = pytest.mark.asyncio @pytest.mark.usefixtures('unstub') class TestHookDetails: async def test__hook_details__is_pure_interface(self): with pytest.raises(NotImplementedError): f"{HookDetai...
) with pytest.raises(NotImplementedError): HookDetails().get_ref() with pytest.raises(NotImplementedError): HookDetails().setup_final_param_values(mock()) with pytest.raises(NotImplementedError): await HookDetails().should_trigger(mock(), mock()) with ...
s().get_event_type()
blooparksystems/website
website_seo/controllers/main.py
Python
agpl-3.0
4,887
0.000614
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, an open source suite of business apps # This module copyright (C) 2015 bloopark systems (<http://bloopark.de>). # # This program is free software: you can redistribute it and/or modify # it under the terms o...
l, # 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. If not, see <http://www.gnu.org...
s from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.controllers.main import Website class Website(Website): @http.route(['/<path:seo_url>'], type='http', auth="public", website=True) def path_page(self, seo_url, **kwargs): """Handle SEO urls ...
JulienPeloton/LaFabrique
LaFabrique/covariance.py
Python
gpl-3.0
3,857
0.001815
from . import util_CMB import healpy as hp import numpy as np import os import glob def generate_covariances(m1, inst): """ Create a weight map using the smaller eigenvalue of the polarization matrix The resulting covariances are saved on the disk. Parameters ---------- * m1: object, conta...
'name', 'SO weight maps'), ('sigma_p', m1.sigma_p, 'uK.arcmin')]) def inverse_noise_weighted_coaddition( m1, inst, folder_of_covs=None, list_of_covs=None, temp_only=False, save_on_disk=True): """ Combine covariances into one single on
e. Particularly useful to mimick post-component separation analysis. Parameters ---------- * inst: object, contain the input parameters from the ini file * folder_of_covs: string, folder on disk containing the covariances that you want to combine. The code assumes that the files...
owlabs/incubator-airflow
airflow/example_dags/example_nested_branch_dag.py
Python
apache-2.0
2,028
0.003945
# # Licensed to the Apache Software Foundatio
n (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 this file except in compliance # with th...
re 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 limitations # under the License. """ Example DAG demonstrating a workflow with nested branching. The j...
patrick91/pycon
backend/api/conferences/helpers/days.py
Python
mit
227
0
import typing from datetime import dat
e, timedelta def daterange(start_date: date, end_date: date) -> typing.Iterator[date]: for n in range(int((end_date - start_date).days)): yield start_dat
e + timedelta(days=n)
sameeptandon/sail-car-log
car_tracking/doRPC.py
Python
bsd-2-clause
19,670
0.045399
#!/usr/bin/python import os, sys from AnnotationLib import * from optparse import OptionParser import copy import math # BASED ON WIKIPEDIA VERSION # n - number of nodes # C - capacity matrix # F - flow matrix # s - source # t - sink # sumC - sum over rows of C (too speed up computation) def edmonds_karp(n, C, s, t,...
ositives(self): ret = copy.copy(self.anno) ret.rects = [] #iterate over GT for i in xrange(self.n + 1, self.a - 1): #Flow to sink > 0 if(self.F[i][
self.a - 1] > 0 and self.ignore[i - self.n - 1] == 0): #Find associated det for j in xrange(1, self.n + 1): if(self.F[j][i] > 0): ret.rects.append(self.det[j - 1]) break return ret def getIgnoredTruePositives(self): ret = copy.copy(self.anno) ret.rects = [] #iterate over GT for i ...
Calvinxc1/neural_nets
Processors/Combiners.py
Python
gpl-3.0
2,965
0.020911
#%% Libraries: Built-In import numpy as np #% Libraries: Custom #%% class Combiner(object): def forward(self, input_arr
ay, weights, const): ## Define in child pass def backprop(self, error_array, backprop_array, learn_weight = 1e-0): ## Define in child pass #%% class Linear(Combiner): def forward(self, input_array, weights, const): cross_vals = input_array * weights summed_va...
ined_array = summed_vals + const return combined_array def backprop(self, input_array, error_array, backprop_array, weights, prior_coefs, learn_weight): #print(input_array.shape, error_array.shape, backprop_array.shape, weights.shape) gradient_weights, gradient_const = self.gra...
clickbeetle/portage-cb
pym/portage/util/lafilefixer.py
Python
gpl-2.0
6,442
0.028252
# Copyright 2010 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import os as _os import re from portage import _unicode_decode from portage.exception import InvalidData ######################################################### # This an re-implementaion of dev-util/lafilefixer-0...
these precede all other entries. # * Remove duplicated entries from dependency_libs # * Takes care that no entry to inherited_linker_flags is added that is # already there. ######################################################### #These regexes are used to parse the interesting entries in the la file dep_li
bs_re = re.compile(b"dependency_libs='(?P<value>[^']*)'$") inh_link_flags_re = re.compile(b"inherited_linker_flags='(?P<value>[^']*)'$") #regexes for replacing stuff in -L entries. #replace 'X11R6/lib' and 'local/lib' with 'lib', no idea what's this about. X11_local_sub = re.compile(b"X11R6/lib|local/lib") #get rid o...
64studio/smart
smart/backends/deb/pm.py
Python
gpl-2.0
15,617
0.001537
# # Copyright (c) 2004 Conectiva, Inc. # # Written by Gustavo Niemeyer <niemeyer@conectiva.com> # # This file is part of Smart Package Manager. # # Smart Package Manager 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 Fou...
else: req_type_priority = LOW relations = [] def add_relation(pred, succ, priority=MEDIUM): relations.append((pred, succ, priority)) for prv in req.providedby: for prvpkg in prv.packages: ...
# ------------------------------ # When the package requiring a dependency and # the package providing a dependency are both # being installed, the unpack of the dependency # must nec...
NicoSantangelo/package-boilerplate
tests/test_basepath.py
Python
mit
725
0.006897
import sublime import unittest from PackageBoilerplate import package_boilerplate # Remember: # Install AAAPT package to run the tests # Save package_boilerplate to reload the tests class Test_BasePath(u
nittest.TestCase): def test_join_combines_the_packages_path_with_the_supplied_one(self): result = package_boilerplate.BasePath.join("some/new/path") self.assertEquals(result, sublime.packages_path() + "/PackageBoilerplate/some/new/path") def test_join_combines_the_packages_path_with_all_the_sup...
ilerplate.BasePath.join("some", "new", "path") self.assertEquals(result, sublime.packages_path() + "/PackageBoilerplate/some/new/path")
job/rtrsub
setup.py
Python
bsd-2-clause
3,054
0.002292
#!/usr/bin/env python3 # Cop
yright (C) 2016 Job Snijders <job@instituut.net> # # This file is part of rtrsub # # 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, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provide...
ljwolf/pysal
pysal/contrib/glm/utils.py
Python
bsd-3-clause
15,120
0.002116
from __future__ import absolute_import, print_function import numpy as np import warnings def _bit_length_26(x): if x == 0: return 0 elif x == 1: return 1 else: return len(bin(x)) - 2 try: from scipy.lib._version import NumpyVersion except ImportError: import re stri...
on(np.__version__) < '1.7.0': ... print('skip') skip >>> Nu
mpyVersion('1.7') # raises ValueError, add ".0" """ def __init__(self, vstring): self.vstring = vstring ver_main = re.match(r'\d[.]\d+[.]\d+', vstring) if not ver_main: raise ValueError("Not a valid numpy version string") self.version = ...
JudoWill/glue
glue/clients/tests/test_image_client.py
Python
bsd-3-clause
18,765
0.00032
# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103 from __future__ import absolute_import, division, print_function import pytest from mock import MagicMock import numpy as np from ...tests import example_data from ... import core from ...core.exceptions import IncompatibleAttribute from ..layer_artist import RG...
lient.apply_roi(roi) roi2 = self.im.edit_subset.subset_state.roi state = self.im.edit_subset.subset_state assert roi2.to_polygon()[0] == roi.to_polygon()[0] assert roi2.to_polygon()[1] == roi.to_polygon()[1] assert
state.xatt is self.im.get_pixel_component_id(1) assert state.yatt is self.im.get_pixel_component_id(0) def test_apply_roi_3d(self): client = self.create_client_with_cube() self.cube.coords = DummyCoords() roi = core.roi.PolygonalROI(vx=[10, 20, 20, 10], ...
libsh-archive/sh
test/regress/exp.cpp.py
Python
lgpl-2.1
1,880
0.002128
#!/usr/bin/python from math import exp import shtest, sys def exp_test(p, base, types=[], epsilon=0): if base > 0: result = [pow(base, a) for a in p] else: result = [exp(a) for a in p] return shtest.make_test(result, [p], types, epsilon) def insert_into(test, base=0): test.add_test(e...
shtest.Call(shtest.Call.call, 'exp', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test exp2 in stream programs test = shtest.StreamTest('exp2', 1) test.add_
call(shtest.Call(shtest.Call.call, 'exp2', 1)) insert_into(test, 2) test.output(sys.stdout, False) # Test exp10 in stream programs test = shtest.StreamTest('exp10', 1) test.add_call(shtest.Call(shtest.Call.call, 'exp10', 1)) insert_into(test, 10) test.output(sys.stdout, False) # Test exp in immediate mode test = shte...
iogf/steinitz
steinitz/fics.py
Python
gpl-2.0
1,786
0.017917
from untwisted.network import spawn from untwisted.event import get_event from untwisted.splits import Terminator from re import * GENERAL_STR = '[^ ]+' GENERAL_REG = compile(GENERAL_STR) SESSION_STR = '\*\*\*\* Starting FICS session as (?P<username>.+) \*\*\*\*' SESSION_REG = compile(SESSION_STR) TELL_STR = '(?P<...
' % nick, mode, msg) m = match(SAY_REG, data) try: nick = m.group('nick') msg = m.group('msg') mode = m.group('mode') except: pass else: spawn(spin, SAY, nick, mode, msg) spawn(spin, '%s says:' % nick, mode, msg) m = match(SHOUT_REG, data) try: ...
spawn(spin, SHOUT, nick, mode, msg)
snakeleon/YouCompleteMe-x64
third_party/ycmd/third_party/jedi_deps/jedi/test/test_inference/test_representation.py
Python
gpl-3.0
1,014
0
from textwrap import dedent def get_definition_and_inference_state(Script, source): first, = Script(dedent(source)).infer() return first._name._value, first._inference_state def test_function_execution(Script): """ We've been having an issue of a mutable list that was changed inside the function...
func.execute_with_values()) == 1 assert len(func.exe
cute_with_values()) == 1 def test_class_mro(Script): s = """ class X(object): pass X""" cls, inference_state = get_definition_and_inference_state(Script, s) mro = cls.py__mro__() assert [c.name.string_name for c in mro] == ['X', 'object']
dbreen/connectfo
game/scenes/menu.py
Python
mit
3,374
0.001778
import pygame import sys from game import constants, gamestate from game.ai.easy import EasyAI from game.media import media from game.scene import Scene # List of menu options (text, acti
on_method, condition) where condition is None or a callable. # If it is a callable that returns False, the option is not shown. CONTINUE = 0 NEW_GAME = 1 QUIT = 2 OPTIONS = [ ('Continue', 'opt_continue', lambda scene: scene.game_running), ('2 Play
er', 'start_2_player', None), ('Vs CPU', 'start_vs_cpu', None), ('Computer Battle!', 'start_cpu_vs_cpu', None), ('Quit', 'opt_quit', None), ] class MenuScene(Scene): def load(self): self.font = pygame.font.Font(constants.MENU_FONT, constants.MENU_FONT_SIZE) self.active_font = p...
perkinslr/pypyjs
addedLibraries/twisted/internet/fdesc.py
Python
mit
3,297
0.000303
# -*- test-case-name: twisted.test.test_fdesc -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Utility functions for dealing with POSIX file descriptors. """ import os import errno try: import fcntl except ImportError: fcntl = None # twisted imports from twisted.internet.main ...
urn: number of bytes written, or CONNECTION_LOST. """ try: return os.write(fd, data) except (OSError, IOError) as io: if io.errno in (errno.EAGAIN, errno.EINTR): return 0 return CONNECTION_LOST __all__ = ["setNonBlocking", "setBlocking", "readFromFD", "writeToFD"]
mapillary/OpenSfM
opensfm/test/test_robust.py
Python
bsd-2-clause
11,385
0.002108
import copy from typing import Tuple import numpy as np from opensfm import pyrobust, pygeometry def line_data() -> Tuple[int, int, np.ndarray, int]: a, b = 2, 3 samples = 100 x = np.linspace(0, 100, samples) return a, b, x, samples def similarity_data() -> Tuple[np.ndarray, np.ndarray, int, np.nda...
arams, pyrobust.RansacType.RANSAC ) expected = pose.get_world_to_cam()[:3] expected[:, 3] /= np.lina
lg.norm(expected[:, 3]) tolerance = 0.15 inliers_count = (1 - ratio_outliers) * len(points) assert np.isclose(len(result.inliers_indices), inliers_count, rtol=tolerance) assert np.linalg.norm(expected - result.lo_model, ord="fro") < 16e-2 def test_
gengstrand/clojure-news-feed
server/feed5/swagger_server/services/caching_service.py
Python
epl-1.0
640
0.003125
import redis import json from flask import current_app class CachingService: rc = None def cache(self): if self.rc is None: self.rc = redis.StrictRedis(host=current_app.config['CACHE_HOST'], port=current_app.config['CACHE_PORT'], db=0) return self.rc def get(self, key: str) ->...
) retVal = None if
v is not None: retVal = json.loads(v.decode("utf-8")) return retVal def set(self, key: str, value: dict): self.cache().set(key, json.dumps(value)) def remove(self, key: str): self.cache().delete(key)
fjruizruano/ngs-protocols
bg_count.py
Python
gpl-3.0
764
0.005236
#!/usr/bin/python import sys from subprocess import call print "Usage: bg_count.py ListO
fBamFiles Reference" try: li = sys.argv[1] except: li = raw_input("Introduce List of indexed BAM files: ") try: ref = sys.argv[2] except: ref = raw_input("Introduce Reference in FASTA format: ") files = open(li).readlines() li_bg = [] li_names = [] for file in files: file = file[:-1] li_bg....
der -i %s -names %s -g %s -empty > samples1and2.txt" % (" ".join(li_bg), " ".join(li_names), ref+".fai"), shell=True) call("coverage_seq_bed.py samples1and2.txt", shell=True)
jaivasanth-google/deploymentmanager-samples
examples/v2/project_creation/test_project.py
Python
apache-2.0
9,168
0.002182
"""Unit tests for `project.py`""" import copy import unittest import project as p class Context: def __init__(self, env, properties): self.env = env self.properties = properties class ProjectTestCase(unittest.TestCase): """Tests for `project.py`.""" default_env = {'name': 'my-project', 'project_number'...
mbers': [('serviceAccount:123@cloudservices' '.gserviceaccount.com')] } ] } actual_iam_policies = ( p.MergeCallingServiceAccountWithOwnerPermissinsIntoBindings( env, properties)) self.assertEqual(expected, actual_iam_policies) def test_...
ge_with_different_owner_policy_and_other_key(self): """Test output of the function when there is an existing but different owner IAM policy in the properties and some unknown key that exists""" env = {'project_number': '123'} properties = { 'iam-policy': { 'foobar': { ...
ESSolutions/ESSArch_Core
ESSArch_Core/tags/migrations/0014_auto_20181122_1211.py
Python
gpl-3.0
859
0.002328
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-22 11:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('WorkflowEngine', '0001_initial'), ('tags', '0013_auto_20180925_1142'), ] operation...
on_delete=django.db.models.deletion.PROTECT, to='tags.StructureUnit'),
), ]
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/test/test_importlib/import_/test_caching.py
Python
gpl-3.0
3,599
0.000556
"""Test that sys.modules is used properly by import.""" from .. import util import sys from types import MethodType import unittest class UseCache: """When it comes to sys.modules, import prefers it over anything else. Once a name has been resolved, sys.modules is checked to see if it contains the modul...
g., not what a loader returns) [from cache on return]. This also applies to imports of things contain
ed within a package and thus get assigned as an attribute [from cache to attribute] or pulled in thanks to a fromlist import [from cache for fromlist]. But if sys.modules contains None then ImportError is raised [None in cache]. """ def test_using_cache(self): # [use cache] module_...
otherlab/tridiagonal
__init__.py
Python
bsd-3-clause
71
0
from __f
uture__ import absolute_import from tridiagonal_core impor
t *
aronsky/home-assistant
tests/components/mqtt/test_switch.py
Python
apache-2.0
15,084
0.000331
"""The tests for the MQTT switch platform.""" import copy from unittest.mock import patch import pytest from homeassistant.components import switch from homeassistant.components.mqtt.switch import MQTT_SWITCH_ATTRIBUTES_BLOCKED from homeassistant.const import ATTR_ASSUMED_STATE, STATE_OFF, STATE_ON import homeassista...
_payload( hass, mqtt_mock, switch.DOMAIN, config, True, "state-topic", "1" ) async def test_custom_availability_payload(hass, mqtt_mock): """Test availability by custom payload with defined topic.""" config = { switch.DOMAIN: {
"platform": "mqtt", "name": "test", "state_topic": "state-topic", "command_topic": "command-topic", "payload_on": 1, "payload_off": 0, } } await help_test_custom_availability_payload( hass, mqtt_mock, switch.DOMAIN, config,...
ganxueliang88/idracserver
jasset/views.py
Python
gpl-2.0
23,160
0.00298
# coding:utf-8 from django.db.models import Q from jasset.asset_api import * from jumpserver.api import * from jumpserver.models import Setting from jasset.forms import AssetForm, IdcForm from jasset.models import Asset, IDC, AssetGroup, ASSET_TYPE, ASSET_STATUS from jperm.perm_api import get_group_asset_perm, get_gro...
ave(commit=False) if use_de
fault_auth: af_save.username = '' af_save.password = '' af_save.port = None else: if password: password_encode = CRYPTOR.encrypt(password) af_save.password = password_encode ...
pooler/electrum-ltc
electrum_ltc/scripts/update_default_servers.py
Python
mit
2,380
0.003361
#!/usr/bin/env python3 # This script prints a new "servers.json" to stdout. # It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions), # and adds new servers from provided file(s) of candidate servers. # A file of new candidate servers can be created via e.g.: # $ ./electrum_ltc/...
on hostmaps for new servers to be added") print(" - if two files are provided, their intersection is used (peers found in both).\n" " file1 should have the newer data.") sys.exit(1) def get_newly_added_servers(fname1, fname2=None): with open(fname1) as f: res_hostmap = json...
common_set = set.intersection(set(res_hostmap), set(dict2)) res_hostmap = {k: v for k, v in res_hostmap.items() if k in common_set} return res_hostmap # testnet? #constants.set_testnet() config = SimpleConfig({'testnet': False}) loop, stopping_fut, loop_thread = create_and_start_event_loop() netwo...
brbsix/github-download-count
gdc/__init__.py
Python
gpl-3.0
198
0
# -*- coding: utf-8 -*- """Display download counts of GitHub releases.""" __program__ = 'github-download-count' __versi
on__ = '0.0.1' __description__ = 'Display download counts of G
itHub releases'
sufhani/suf-webapp
manage.py
Python
mit
253
0
#!/usr
/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sufwebapp1.settings") from django.core.management imp
ort execute_from_command_line execute_from_command_line(sys.argv)
cloudpassage/cloudpassage-halo-python-sdk
cloudpassage/halo_endpoint.py
Python
bsd-3-clause
3,416
0
"""HaloEndpoint class""" import cloudpassage.sanity as sanity from .utility import Utility as utility from .http_helper import HttpHelper class HaloEndpoint(object): """Base class inherited by other specific HaloEndpoint classes.""" default_endpoint_version = 1 def __init__(self, session, **kwargs): ...
nt_version" in kwargs: version = kwargs["endpoint_version"] if isinstance(version, int): self.endpoint_version = version
else: raise TypeError("Bad endpoint version {}".format(version)) else: self.endpoint_version = self.default_endpoint_version @classmethod def endpoint(cls): """Not implemented at this level. Raises exception.""" raise NotImplementedError @classmethod...
echevemaster/fudcon
fudcon/ui/backend/__init__.py
Python
mit
107
0
# -*
- coding: utf-8
-*- """ fudcon.ui.backend ------ fudcon ui backend application package """
kakaroto/amsn2
amsn2/ui/front_ends/qt4/splash.py
Python
gpl-2.0
1,624
0.000616
# -*- coding: utf-8 -*- # # amsn - a python client for the WLM Network # # Copyright (C) 2008 Dario Freddi <drf54321@gmail.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...
, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from amsn2.ui import base from PyQt4 import Qt from PyQt4 import QtCore from PyQt4 import QtGui from fadingwidget import FadingWidget from image import Image class aMSNSplashScreen(QtGui.QSplashScreen, base.aMSN...
def __init__(self, amsn_core, parent): QtGui.QSplashScreen.__init__(self, parent) self._theme_manager = amsn_core._theme_manager def show(self): self.setVisible(True) QtGui.qApp.processEvents() def hide(self): self.setVisible(False) QtGui.qApp.processEvents() ...
seecr/weightless-core
test/lib/seecr-test-2.0/seecr/test/io.py
Python
gpl-2.0
2,438
0.003692
## begin license ## # # "Weightless" is a High Performance Asynchronous Networking Library. See http://weightless.io # # Copyright (C) 2012-2013, 2017, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl # # This file is part of "Weightless" # # "Weightless" is free software; you can redistribute it and/or modify # it...
sion 2 of the License, or # (at your option)
any later version. # # "Weightless" 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 Pu...
codendev/rapidwsgi
src/mako/__init__.py
Python
gpl-3.0
256
0.007813
# __init__.py # Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer mike_mp@zzzcomputing.com # # This module is part of Mako and is released under # the MIT Lice
nse: http://www.opensource.org/licenses/mit-license.php __
version__ = '0.3.4'
h4ck3rm1k3/FEC-Field-Documentation
fec/version/v3/F57.py
Python
unlicense
1,916
0.001044
import fechbase class Records(fechbase.RecordsBase): def __init__(self): fechbase.RecordsBase.__init__(
self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FILER FEC CMTE ID', 'number': '2'}, {'name': 'ENTITY TYPE', 'number': '3'}, {'name': 'NAME (Payee)', 'number': '4'}, {'name': 'STREET 1', 'number': '5'}, {'name': 'STREET...
{'name': 'ZIP', 'number': '9'}, {'name': 'TRANSDESC', 'number': '10'}, {'name': 'Of Expenditure', 'number': '11-'}, {'name': 'AMOUNT', 'number': '12'}, {'name': 'SUPPORT/OPPOSE', 'number': '13'}, {'name': 'S/O FEC CAN ID NUMBER', 'number': '14'}, ...
eternnoir/pyTelegramBotAPI
examples/asynchronous_telebot/middleware/i18n_middleware_example/i18n_base_midddleware.py
Python
gpl-2.0
3,751
0.001866
import contextvars import gettext import os from telebot.asyncio_handler_backends import BaseMiddleware try: from babel.support import LazyProxy babel_imported = True except ImportError: babel_imported = False class I18N(BaseMiddleware): """ This middleware provides high-level tool for internat...
eturn list(self.translations) def gettext(self, text: str, lang: str = None): """ Singular translations """ if lang is None: lang = self.context_lang.get()
if lang not in self.translations: return text translator = self.translations[lang] return translator.gettext(text) def ngettext(self, singular: str, plural: str, lang: str = None, n=1): """ Plural translations """ if lang is None: lang = se...
3Jade/Sprawl
make.py
Python
mit
9,814
0.02364
#!/usr/bin/python import subprocess import os import time import platform import glob import shutil import csbuild from csbuild import log csbuild.Toolchain("gcc").Compiler().SetCppStandard("c++11") csbuild.Toolchain("gcc").SetCxxCommand("clang++") csbuild.Toolchain("gcc").Compiler().AddWarnFlags("all", "extra", "c...
("msvc").AddExclud
eFiles("filesystem/*_linux.cpp") csbuild.EnableOutputInstall() csbuild.EnableHeaderInstall() @csbuild.project("threading", "threading") def threading(): csbuild.SetOutput("libsprawl_threading", csbuild.ProjectType.StaticLibrary) if platform.system() != "Darwin": @csbuild.scope(csbuild.ScopeDef.Final) def f...
joyxu/kernelci-backend
app/handlers/version.py
Python
agpl-3.0
1,607
0
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 o
f 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 Affero General Public License for more details. # # You shoul...
"" import handlers import handlers.base as hbase import handlers.response as hresponse import models # pylint: disable=too-many-public-methods class VersionHandler(hbase.BaseHandler): """Handle request to the /version URL. Provide the backend version number in use. """ def __init__(self, applicatio...
topic2k/EventGhost
eg/Init.py
Python
gpl-2.0
6,124
0.002286
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2019 EventGhost Project <http://www.eventghost.org/> # # EventGhost 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 versio...
Startup: eg.mainFrame.Iconize(True) eg.actionThread.Start() eg.eventThread.startupEvent = eg.startupArguments.startupEvent config = eg.config startupFile = eg.startupArguments.startupFile if startupFile is None: startupFile = config.autoloadFilePath if startupFile and not...
eg.text.Error.FileNotFound % startupFile) startupFile = None eg.eventThread.Start() wx.CallAfter( eg.eventThread.Call, eg.eventThread.StartSession, startupFile ) if config.checkUpdate: # avoid more than one check per day today = gmtime()[:3] if c...
NewAcropolis/api
migrations/versions/0038.py
Python
mit
686
0.002915
"""empty message Revision ID: 0038 ad
d topics to magazines Revises: 0037 add magazine_id to emails Create Date: 2020-02-05 01:29:38.265454 """ # revision identifiers, used by Alembic. revision = '0038 add topics to magazines' down_revision = '0037 add magazine_id to emails' from alembic import op import sqlalchemy as sa def upgrade(): # ### comma...
adjust! ### op.add_column('magazines', sa.Column('topics', sa.String(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('magazines', 'topics') # ### end Alembic commands ###
chaosct/GestureAgents
Apps/DemoApp/apps/Shadows/__init__.py
Python
mit
5,202
0.000769
# -*- coding: utf-8 -*- from GestureAgentsTUIO.Tuio import TuioCursorEvents from GestureAgentsDemo.Geometry import Ring, Circle from GestureAgentsDemo.Render import drawBatch from GestureAgents.Recognizer import Recognizer import pyglet.clock from pyglet.sprite import Sprite from pyglet.resource import Loader from Ges...
self.ring = None def finishAgent(self, a): self.dead = True self.agent.newCursor.unregister(self) self.agent.updateCursor.unregister(self)
self.agent.removeCursor.unregister(self) self.agent.finishAgent.unregister(self) def update(self, dt=0): actuals = set(apprecognizers_subscribed(self.agent)) anteriors = set(self.recognizersymbols) pending = actuals - anteriors for r in pending: name = r.ori...
miti0/mosquito
core/constants.py
Python
gpl-3.0
24
0
SECONDS
_IN_DAY = 8
6400
Si-elegans/Web-based_GUI_Tools
behaviouralExperimentDefinition/models.py
Python
apache-2.0
36,673
0.017724
from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.conf import settings from datetime import datetime import uuid User = settings.AUTH_USER_MODEL def generate_new_uuid(): return str(uuid.uuid4()) class behaviourExperimentType_model(models.Model): #...
r = models.ForeignKey("CylinderType_model",null=True, blank=True) Cube = models.ForeignKey("CubeType_model",null=True, blank=True) Hexagon = models.ForeignKey("HexagonType_model",null=True, blank=True) #class Meta: #unique_together = ("shape","xCoordFromPlateCentre","yCoorDFromPlateCentre","angleRel...
(self.uuid,) class plateConfigurationType_model(models.Model): uuid = models.CharField(('Unique Identifier'), max_length=36, primary_key=True, default=generate_new_uuid) WATER = 'W' GELATIN = 'G' AGAR = 'A' BOTTOMMATERIALTYPE = ( (WATER,"water"), (GELATIN,"gelatin"),...
JoaoFelipe/snowballing
snowballing/operations.py
Python
mit
33,262
0.002375
"""This module contains functions to :meth:`~reload` the database, load work and citations from there, and operate BibTeX""" import importlib import re import textwrap import warnings import subprocess from copy import copy from collections import OrderedDict from bibtexparser.bwriter import BibTexWriter from bibtex...
17, 'name': 'a', 'authors': 'Pim, J', 'note': 'in press', 'display': 'pim', 'pyref': 'pim2017a'} >>> bibtex_to_info({'title': 'a', 'author': 'Pim, J', 'pages
': '1--5'}) {'place1': '', 'year': 0, 'name': 'a', 'authors': 'Pim, J', 'pp': '1--5', 'display': 'pim', 'pyref': 'pim0a'} >>> bibtex_to_info({'title': 'a', 'author': 'Pim, J', 'journal': 'CiSE'}) {'place1': 'CiSE', 'year': 0, 'name': 'a', 'authors': 'Pim, J', 'place': 'CiSE', 'display': 'pim', '...
SimonSapin/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/base.py
Python
mpl-2.0
1,789
0.001118
import os import sys from os.path import dirname, join import pytest sys.path.insert(0, join(dirname(__file__), "..", "..")) from wptrunner import browsers _products = browsers.product_list _active_products = set() if "CURRENT_TOX_ENV" in os.environ: current_tox_env_split = os.environ["CURRENT_TOX_ENV"].spli...
r"}, "edge": {"edge_webdriver"}, "safari": {"safari_webdriver"}, "servo": {"servodriver"}, } _active_products = set(_products) & set(current_t
ox_env_split) for product in frozenset(_active_products): _active_products |= tox_env_extra_browsers.get(product, set()) else: _active_products = set(_products) class all_products(object): def __init__(self, arg, marks={}): self.arg = arg self.marks = marks def __call__(self, ...
brenton/cobbler
tests/tests.py
Python
gpl-2.0
37,355
0.007924
# Test cases for Cobbler # # Michael DeHaan <mdehaan@redhat.com> import sys import unittest import os import subprocess import tempfile import shutil import traceback from cobbler.cexceptions import * from cobbler import settings from cobbler import collection_distros from cobbler import collection_profiles from c...
system3 = self.api.new_system() self.assertTrue(system3.set_name("unused_name")) self.assertTrue(system3.set_profile("testprofile0")) # MAC is initially accepted self.assertTrue(system3.set_mac_address("BB:EE:EE:EE:EE:FF","intf3")) # can't add as this MAC already exists!...
cate_names=True,check_for_duplicate_netinfo=True) try: self.api.add_system(system3,check_for_duplicate_names=True,check_for_duplicate_netinfo=True) except CobblerException: pass except: traceback.print_exc() self.assertTrue(1==2,"wrong exception type"...
mitodl/odl-video-service
ui/migrations/0004_add_videothumbnail.py
Python
bsd-3-clause
1,453
0.001376
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-03 18:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("ui", "0003_add_videofile"), ] operations = [ ...
, models.IntegerField(blank=True, null=True)), ( "video", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="ui.Video" ),
), ], options={ "abstract": False, }, ), ]
jasongrout/pythreejs
pythreejs/enums.py
Python
bsd-3-clause
2,549
0.000392
r""" Three.js Enums These correspond to the enum property names in the THREE js object """ # Custom Blending Equation Constants # http://threejs.org/docs/index.html#Reference/Constants/CustomBlendingEquation Equations = [ 'AddEquation', 'SubtractEquation', 'ReverseSubtractEquation', 'MinEquation', ...
nts # http://threejs.org/docs/index.html#Reference/Constants/Textures Operations = [ 'MultiplyOperation',
'MixOperation', 'AddOperation' ] MappingModes = [ 'UVMapping', 'CubeReflectionMapping', 'CubeRefractionMapping', 'EquirectangularReflectionMapping', 'EquirectangularRefractionMapping', 'SphericalReflectionMapping' ] WrappingModes = [ 'RepeatWrapping', 'ClampToEdgeWrapping', ...
websocket-client/websocket-client
websocket/tests/test_websocket.py
Python
apache-2.0
18,069
0.00261
# -*- coding: utf-8 -*- # import os import os.path import socket import websocket as ws import unittest from websocket._handshake import _create_sec_websocket_key, \ _validate as _validate_header from websocket._http import read_headers from websocket._utils import validate_utf8 from base64 import decodebytes as ba...
key, ["sub2", "sub3"]), (False, None)) header = required_header.copy() header["sec-websocket-protocol"] = "sUb1" self.assertEqual(_validate_header(header, key, ["Sub1", "suB2"]), (True, "sub1")) header = required_header.copy() # This case will print out a logging error using th...
tus, header, status_message = read_headers(HeaderSockMock("data/header01.txt")) self.assertEqual(status, 101) self.assertEqual(header["connection"], "Upgrade") status, header, status_message = read_headers(HeaderSockMock("data/header03.txt")) self.assertEqual(status, 101) self.a...
light-swarm/blob_detector
scripts/blob_detector_.py
Python
mit
1,685
0.005935
#!/usr/bin/env python from blob import Blob from foreground_processor import ForegroundProcessor import cv2 import operator import rospy from blob_detector.msg import Blob as BlobMsg from blob_detector.msg import Blobs as BlobsMsg import numpy as np class BlobDetector(ForegroundProcessor): def __init__(self, nod...
blob in blobs: blob.draw(rgbd.depth_color_sm) self.sh
ow_depth_color(rgbd) def process_blobs(self, blobs, rgbd): self.publish_blobs(blobs) self.show_blobs(self, blobs, rgbd) if __name__ == '__main__': bd = BlobDetector('fg') bd.run()
jhotta/documentation
code_snippets/results/result.api-screenboard-share.py
Python
bsd-3-clause
74
0
{'boar
d_id': 812, 'public_url': 'https://p.datadoghq.com/sb/20756e0c
d4'}
lizardsystem/flooding
flooding_lib/tools/exporttool/migrations/0001_initial.py
Python
gpl-3.0
4,116
0.005831
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('flooding_lib', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] o...
)), ('name', models.CharField(max_length=200)), ('file_basename', models.CharField(max_length=100)),
('area', models.IntegerField(choices=[(10, 'Diked area'), (20, 'Province'), (30, 'Country')])), ('export_run', models.ForeignKey(to='exporttool.ExportRun')), ], options={ 'verbose_name': 'Result', 'verbose_name_plural': 'Results', ...
thousandparsec/daneel-ai
picklegamestate.py
Python
gpl-2.0
689
0.05225
import cPickle class GameState: # g = GameState(11,22,3,4,5) init # g.pickle('test.gamestate') save # x = GameState().unpickle('test.gamestate
') load def __init__(self,rulesfile=None,turns=None,connection=None, cache=None,verbosity=None, pickle_location=None): if pickle_location is None: self.rulesfile = rulesfile self.turns = turns self.connection = connection self.cache = cache self.verbosity = verbosity def pickle(self, file_name...
load(file) file.close() return old
jacopodl/TbotPy
src/Object/Location.py
Python
gpl-3.0
1,452
0
""" <This library provides a Python interface for the Telegram Bot API> Copyright (C) <2015> <Jacopo De Luca> 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 t...
e along with this program. If not, see <ht
tp://www.gnu.org/licenses/>. """ class Location(object): """ This object represents a point on the map. """ def __init__(self, longitude, latitude): """ :param longitude: Longitude as defined by sender :type longitude: float :param latitude: Latitude as defined by sen...