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 |
|---|---|---|---|---|---|---|---|---|
kslundberg/pants | contrib/scrooge/tests/python/pants_test/contrib/scrooge/tasks/test_scrooge_gen.py | Python | apache-2.0 | 5,162 | 0.004262 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from textw... | arse(spec=spec)
Context.add_new_target.assert_called_once_with(address,
library_type,
| sources=sources,
excludes=OrderedSet(),
dependencies=OrderedSet(),
provides=None,
derived_from=tar... |
StartupsPoleEmploi/labonneboite | labonneboite/tests/scripts/test_prepare_mailing_data.py | Python | agpl-3.0 | 761 | 0.001314 | from labonneboite.scripts import prepare_mailing_data as script
from labonneboite.tests.test_base import DatabaseTest
from labonneboite.common.models import Office
class PrepareMailingDataBaseTest(DatabaseTest):
"""
Create Elasticsearch and DB content for the unit tests.
| """
def setUp(self, *args, **kwargs):
super(PrepareMailingDataBaseTest, self).s | etUp(*args, **kwargs)
# We should have 0 offices in the DB.
self.assertEqual(Office.query.count(), 0)
class MinimalisticTest(PrepareMailingDataBaseTest):
"""
Test prepare_mailing_data script.
This test is quite minimalistic as there is no office in DB (nor in ES).
"""
def test_pr... |
clusterpy/clusterpy | clusterpy/core/layer.py | Python | bsd-3-clause | 75,262 | 0.006072 | # encoding: latin2
"""Repository of clusterPy's main class "Layer"
"""
__author__ = "Juan C. Duque, Alejandro Betancourt"
__credits__ = "Copyright (c) 2009-10 Juan C. Duque"
__license__ = "New BSD License"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "[email protected]"
__all__ = ['Layer']
... | hina using the result from an aggregation algorithm. It also generates two | new variables in the dissolved map. These new variables are the regional mean and sum of attributes "Y1978" and "Y1979" ::
import clusterpy
china = clusterpy.importArcData("clusterpy/data_examples/china")
china.cluster('azpSa', ['Y1990', 'Y991'], 5)
dataOperations = {'Y1... |
xguse/spartan | src/spartan/utils/seqs.py | Python | mit | 1,664 | 0.024639 |
compl_iupacdict = {'A':'T',
'C':'G',
'G':'C',
'T':'A',
'M':'K',
'R':'Y',
'W':'W',
'S':'S',
'Y':'R',
'K':'M',
'V':'B',
... | for i in range(0,len(seq)):
letter = seq[i]
compl_seq = compl_seq + compl_iupacdict[letter]
return compl_seq
def reverse(text):
return text[::-1]
def revcomp(seq):
revCompSeq = reverse(compliment(seq, compl_iupacdict))
return revCompSeq
#==============================================... | =
def iupacList_2_regExList(motifList):
i = 0
while i < len(motifList):
motifList[i] = [motifList[i], iupac2regex(motifList[i])]
i += 1
def iupac2regex(motif):
iupacdict = {'A':'A',
'C':'C',
'G':'G',
'T':'T',
'M':'[AC]',
... |
LLNL/spack | var/spack/repos/builtin/packages/r-absseq/package.py | Python | lgpl-2.1 | 1,317 | 0.000759 | # Copyright | 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RAbsseq(RPackage):
"""ABSSeq: a new RNA-Seq analysis method based on modelling absolute
express... | n and
moderating fold-change according to heterogeneity of dispersion across
expression level."""
homepage = "https://bioconductor.org/packages/ABSSeq"
git = "https://git.bioconductor.org/packages/ABSSeq.git"
version('1.44.0', commit='c202b4a059021ed1228ccee7303c69b0aa4ca1ee')
versi... |
Sound-Colour-Space/sound-colour-space | website/apps/museum/models.py | Python | mit | 11,285 | 0.004342 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import uuid
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django.db.models import p... | class Meta:
verbose_name = _('link')
verbose_name_plural = _('links')
db_table = 'museum_link'
ordering = ('-created',)
get_latest_by = 'created'
def __unicode__(self):
return u'%s' % self.title
museum_store = DataStorage(location=settings.DIAGRAMS_ROOT, base_u... | AMS_URL)
ACCURACY_CHOICES = (
(1, _("exact")),
(2, _("month")),
(3, _("year")),
(4, _("decennium")),
(5, _("century")),
(6, _("unknown"))
)
class Entry(Base):
"""
Entry model.
"""
author = models.ManyToManyField(Author, related_name='museums_entries',blank=True)
license = m... |
bithinalangot/ecidadania-dev | src/core/spaces/views.py | Python | gpl-3.0 | 25,152 | 0.006958 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 Cidadania S. Coop. Galega
#
# This file is part of e-cidadania.
#
# e-cidadania 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 Licen... | return context
#
# User roles.
#
@user_passes_test(lambda u: u.is_superuser)
def add_role(request):
"""
This function will allow the site admin to assign roles to the users.
"""
userrole_form = UserRoleForm(request.POST or None)
if request.method == 'POST':
if userrole_form... | tted.name)
return redirect('/spaces/')
else:
return render_to_response('spaces/space_roles.html', {'form':userrole_form}, context_instance = RequestContext(request))
else:
return render_to_response('spaces/space_roles.html', {'form':userrole_form}, context_instan... |
sayar/mcj2011 | sms/settings.py | Python | apache-2.0 | 5,993 | 0.002169 | # Django settings for mcjsms project.
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
ADMINS = []
MANAGERS = ADMINS
if DEBUG:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql',... | f None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Montreal'
# Language code for this installatio | n. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format d... |
camilonova/django | django/db/backends/mysql/introspection.py | Python | bsd-3-clause | 9,426 | 0.001485 | import warnings
from collections import namedtuple
from MySQLdb.constants import FIELD_TYPE
from django.db.backends.base.introspection import (
BaseDatabaseIntrospection, FieldInfo, TableInfo,
)
from django.db.models.indexes import Index
from django.utils.datastructures import OrderedSet
from django.utils.depreca... | CharField',
FIELD_TYPE.TIME: 'TimeField',
FIELD_TYPE.TIMESTAMP: 'DateTimeField',
FIELD_TYPE.TINY: 'IntegerField',
FIELD_TYPE.TINY_BLOB: 'TextField',
FIELD_TYPE.MEDIUM_BLOB: 'TextField',
FIELD_TYPE.LONG_BLOB: 'Text | Field',
FIELD_TYPE.VAR_STRING: 'CharField',
}
def get_field_type(self, data_type, description):
field_type = super().get_field_type(data_type, description)
if 'auto_increment' in description.extra:
if field_type == 'IntegerField':
return 'AutoField'
... |
carthach/essentia | test/src/unittests/spectral/test_triangularbarkbands.py | Python | agpl-3.0 | 5,769 | 0.017334 | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... | 'numberBands': 1 })
self.assertConfigureFails(TriangularBarkBands(), { 'lowFrequencyBound': -100 })
self.assertConfigureFails(TriangularBarkBands(), { 'lowFrequencyBound': 100,
'highFrequencyBound': 50 })
self.assertConfigureFails(TriangularBarkBa... | )
def testWrongInputSize(self):
# This test makes sure that even though the inputSize given at
# configure time does not match the input spectrum, the algorithm does
# not crash and correctly resizes internal structures to avoid errors.
spec = [.1,.4,.5,.2,.1,.01,.04]*100
n... |
mkuiack/tkp | tkp/sourcefinder/image.py | Python | bsd-2-clause | 37,453 | 0.001762 | """
Some generic utility routines for number handling and
calculating (specific) variances
"""
import logging
import itertools
import numpy
from tkp.utility import containers
from tkp.utility.memoize import Memoize
from tkp.sourcefinder import utils
from tkp.sourcefinder import stats
from tkp.sourcefinder import extra... | #
# Properties are attributes managed by methods; rather than calling the #
# method directly, the attribute automatically invokes it. We can use #
# this to do cunning transparent caching ("memoizing") etc; see the | #
# Memoize class. #
# #
# clearcache() clears all the memoized data, which can get quite large. #
# It may be wise to call this, for example, in an exception handler ... |
LoLab-VU/pysb | pysb/examples/run_tutorial_a.py | Python | bsd-2-clause | 244 | 0 | from __future__ import print_function
from pysb.simulator import ScipyOdeSimulator
from tutorial_a import model
t = [0, | 10, 20, 30, 40, 50, 60]
simulator = ScipyOdeS | imulator(model, tspan=t)
simresult = simulator.run()
print(simresult.species)
|
Schamnad/cclib | src/cclib/parser/daltonparser.py | Python | bsd-3-clause | 52,550 | 0.002873 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Parser for DALTON output files"""
from __future__ import print_function
import numpy
from . import logfileparser
f... | mmetry atoms have no internal representation.
# Therefore only atoms marked as "_1" or "#1" in other places are actually
# represented in the model. The symmetry atoms (h | igher symmetry indices) are
# generated on the fly when writing the output. We will save the symmetry indices
# here for later use.
#
# Additional note: the symmetry labels are printed only for atoms that have
# symmetry images... so assume "_1" if a label is missing. For example... |
cilcoberlin/panoptes | panoptes/tracking/admin.py | Python | bsd-3-clause | 277 | 0.01444 |
from django.contrib import | admin
from panoptes.tracking.models import AccountFilter
class AccountFilterAdmin(admin.ModelAdmin):
list_display = ('location', 'include_users', 'exclude_users')
ordering | = ('location',)
admin.site.register(AccountFilter, AccountFilterAdmin)
|
absoludity/django-cumulus | cumulus/management/commands/container_create.py | Python | bsd-3-clause | 2,713 | 0.00258 | import optparse
import pyrax
import swiftclient
from django.core.management.base import BaseCommand, CommandError
from cumulus.settings import CUMULUS
def cdn_enabled_for_container(container):
"""pyrax.cf_wrapper.CFClient assumes cdn_connection.
Currently the pyrax swift client wrapper assumes that if
... | he following pull-request lands
(or is otherwise resolved):
https://github.com/rackspace/pyrax/pull/254
"""
try:
return container.cdn_enabled
except AttributeError:
return False
class Command(BaseCommand):
help = "Create a container."
args = "[container_name]"
opti... | ault=False,
dest="private", help="Make a private container."),)
def connect(self):
"""
Connects using the swiftclient api.
"""
self.conn = swiftclient.Connection(authurl=CUMULUS["AUTH_URL"],
user=CUMULUS["USERNA... |
futurice/schedule | schedulesite/middleware.py | Python | bsd-3-clause | 659 | 0.013657 | from django.contrib.auth.middleware import RemoteUserMiddleware
from django.conf import settings
import os
#This middleware adds header REMOTE_USER with current REMOTE_USER from settings to every request.
#This is required when running app with uwsgi locally (with runserver this is unneces | sary)
#In production, when FAKE_LOGIN=False, the REMOTE_USER header should be set by sso
class SetUserMiddleware():
def process_request(self, request):
if settings.FAKE_LOGIN:
req | uest.META['REMOTE_USER'] = os.getenv('REMOTE_USER')
class CustomHeaderMiddleware(RemoteUserMiddleware):
header = os.getenv('REMOTE_USER_HEADER', 'REMOTE_USER') |
xingjian-f/Leetcode-solution | 354. Russian Doll Envelopes.py | Python | mit | 123 | 0.065041 | cla | ss Solution(object):
def maxEnvelopes(self, envelopes) | :
"""
:type envelopes: List[List[int]]
:rtype: int
"""
|
jiadaizhao/LeetCode | 0101-0200/0116-Populating Next Right Pointers in Each Node/0116-Populating Next Right Pointers in Each Node.py | Python | mit | 612 | 0.003268 | # Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.righ | t = right
self.next = next
class Solution:
def connect(self, root: 'Node') -> 'Node':
curr = root
while curr:
p = curr
while p:
| if p.left:
p.left.next = p.right
if p.next:
p.right.next = p.next.left
p = p.next
curr = curr.left
return root
|
farr/LIGOHamlet | test.py | Python | gpl-3.0 | 685 | 0.008759 | import numpy as np
import numpy.random as nr
def draw_bg(size=(1,), snr_min=5.5, snr_std=2):
bgs = nr.normal(loc=snr_min, scale=snr_std, size=size)
sel = bgs < snr_min
while np.count_nonzero(sel) > 0:
bgs[ | sel] = nr.normal(loc=snr_min, scale=snr_std, size=np.count_nonzero(sel))
sel = bgs < snr_min
return bgs
def draw_fg(size=(1,), snr_min=5.5):
us = nr.uniform(size=size)
return snr_min/(1 - us)**(1.0/3.0)
def data_set(ncoinc, ffore, nbgs):
bgs = [draw_bg(size=nb) for nb in nbgs]
nf = int(r... | rray(fgs), bgs
|
simontakite/sysadmin | pythonscripts/learningPython/lambdas1.py | Python | gpl-2.0 | 587 | 0.003407 | L = [lambda x: x ** 2, # Inline function definition
lambda x: x ** 3,
lambda | x: x ** 4] # A list of 3 callable functions
for f in L:
print(f(2)) # Prints 4, 8, 16
print(L[0](3)) # Prints 9
def f1(x): return x ** 2
def f2(x): return x ** 3 # Define named functions
def | f3(x): return x ** 4
L = [f1, f2, f3] # Reference by name
for f in L:
print(f(2)) # Prints 4, 8, 16
print(L[0](3)) # Prints 9
|
longmen21/edx-platform | common/lib/xmodule/xmodule/modulestore/split_mongo/split.py | Python | agpl-3.0 | 158,905 | 0.003656 | """
Provides full versioning CRUD and representation for collections of xblocks (e.g., courses, modules, etc).
Representation:
* course_index: a dictionary:
** '_id': a unique id which cannot change,
** 'org': the org's id. Only used for searching not identity,
** 'course': the course's catalog number
... | ectId (guid),
** 'root': BlockKey (the block_type and block_id of the root block in the 'blocks' dictionary)
** 'previous_version': the structure from which this one was derived. For published courses, this
points to the previously published version of the structure not the draft published to this.
** '... | determination if 2 structures have any shared history,
** 'edited_by': user_id of the user whose change caused the creation of this structure version,
** 'edited_on': the datetime for the change causing this creation of this structure version,
** 'blocks': dictionary of xblocks in this structure:
**... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractWwwWhitesharkTk.py | Python | bsd-3-clause | 546 | 0.034799 |
def extractWwwWhitesharkTk(item):
'''
Parser for 'www.whiteshark.tk'
'''
vol, chp, | frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in... |
return False
|
claudep/pootle | pootle/core/views/translate.py | Python | gpl-3.0 | 3,056 | 0.000327 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from dj... | = "translate"
view_name = ""
@property
def check_data(self):
return self.object.data_tool.get_checks()
@property
| def checks(self):
check_data = self.check_data
checks = get_qualitychecks()
schema = {sc["code"]: sc for sc in get_qualitycheck_schema()}
_checks = {}
for check, checkid in checks.items():
if check not in check_data:
continue
_checkid = ... |
zestrada/nova-cs498cc | nova/virt/hyperv/volumeops.py | Python | apache-2.0 | 9,291 | 0.000969 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Pedro Navarro Perez
# Copyright 2013 Cloudbase Solutions Srl
# 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... | nfo['data']
target_lun = data['target_lun']
target_iqn = data['target_iqn']
#Getting the mounted disk
mounted_disk_path = self._get_mounted_disk_from_lun(target_iqn,
target_lun)
if ebs_root:
... | to the first slot
slot = 0
else:
#Find the SCSI controller for the vm
ctrller_path = self._vmutils.get_vm_scsi_controller(
instance_name)
slot = self._get_free_controller_slot(ctrller_path)
self._vmutils.attach_... |
theislab/anndata | anndata/compat/__init__.py | Python | bsd-3-clause | 10,424 | 0.001536 | from copy import deepcopy
from functools import reduce, singledispatch, wraps
from codecs import decode
from inspect import signature, Parameter
from typing import Any, Collection, Union, Mapping, MutableMapping, Optional
from warnings import warn
import h5py
from scipy.sparse import spmatrix
import numpy as np
import... | not in d[ann]:
continue
codes: np.ndarray = d[ann][name].values
# hack to maybe find the axis the categories were for
if not np.all(codes < len(cats)):
continue
d[ann][name] = pd.Categorical.from_codes(codes, cats)
k_to_delete.... | in k_to_delete:
del d["uns"][cats_name]
def _move_adj_mtx(d):
"""
Read-time fix for moving adjacency matrices from uns to obsp
"""
n = d.get("uns", {}).get("neighbors", {})
obsp = d.setdefault("obsp", {})
for k in ("distances", "connectivities"):
if (
(k in n)
... |
bharling/django-gevent-socketio | django_socketio_tests/views.py | Python | bsd-3-clause | 127 | 0.015748 | f | rom django.s | hortcuts import render
# Create your views here.
def home(request):
return render(request, 'home.djhtml', {}) |
bpiwowar/lyx | lib/scripts/clean_dvi.py | Python | gpl-2.0 | 3,211 | 0.004983 | '''
file clean_dvi.py
This file is part of LyX, the document processor.
Licence details can be found in the file COPYING
or at http://www.lyx.org/about/licence.php
author Angus Leeming
Full author contact details are available in the file CREDITS
or at http://www.lyx.org/about/credits.php
Usage:
python clean_dvi.... | lean_dvi modifies the input .dvi file so that
dvips and yap (a dvi viewer on Windows) can find
any embedded PostScript files whose names are protected
with "-quotes.
It works by:
1 translating the machine readable .dvi file to human
readable .dtl form,
2 manipulating any references to external files
3 translating th... | name):
return 'Usage: %s in.dvi out.dvi\n' \
% os.path.basename(prog_name)
def warning(message):
sys.stderr.write(message + '\n')
def error(message):
sys.stderr.write(message + '\n')
sys.exit(1)
def manipulated_dtl(data):
psfile_re = re.compile(r'(special1 +)([0-9]+)( +\'PSfile=")(.... |
heuer/segno | tests/test_svg.py | Python | bsd-3-clause | 16,883 | 0.000237 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2022 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
SVG related tests.
"""
from __future__ import absolute_import, unicode_literals
import os
import re
import io
import tempfile
import xml.etree.ElementTree as etree
import pytest
import segno
_SVG_... | ef test_viewbox():
qr = segno.make_qr('test')
out = io.BytesIO()
qr.save(out, kind='svg', omitsize=True)
| root = _parse_xml(out)
assert 'viewBox' in root.attrib
assert 'height' not in root.attrib
assert 'width' not in root.attrib
def test_svgid():
qr = segno.make_qr('test')
out = io.BytesIO()
ident = 'svgid'
qr.save(out, kind='svg', svgid=ident)
root = _parse_xml(out)
assert 'id' in ... |
opendatakosovo/kosovolunteer | ve/views/create_event.py | Python | gpl-2.0 | 583 | 0.013722 | from flask import Flask
from flask.views import View
from flask import Response, request
import urllib2
from ve import utils
class CreateEvent(View):
def dispatch_request(self):
api_base_url = utils.get_api_url()
url | = '%s/create/event'%(api_base_url)
data = request.data
r | = urllib2.Request(url, data=data, headers={"Content-Type": "application/json"})
res = urllib2.urlopen(r)
resp = Response(
response=data,
mimetype='application/json')
return resp
#TODO: return json_response
|
arcturusannamalai/open-tamil | solthiruthi/data/tamilvu_wordlist.py | Python | mit | 1,438 | 0.020862 | #!/usr/bin/python
# (C) 2015 Muthiah Annamalai, <[email protected]>
# Ezhil Language Foundation
#
from __future__ import print_function
import sys
import codecs
import tamil
import json
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
class WordList:
@staticmethod
def extract_words(filename):
... | tches = filter( match_word_length, fp.readlines())
with codecs.open('word_filter_%0 | 2d.txt'%word_size,'w','utf-8') as fp:
for word in matches:
fp.write(u'%s\n'%word.replace(' ','').strip())
print(u'we found %d words of length %d\n'%(len(matches),word_size))
return
if __name__ == u"__main__":
# WordList.pull_words_from_json()
for wlen in ran... |
andrewyoung1991/abjad | setup.py | Python | gpl-3.0 | 2,910 | 0.000688 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import setuptools
import sys
from distutils.version import StrictVersion
version_file_path = os.path.join(
os.path.dirname(__file__),
'abjad',
'_version.py'
)
with open(version_file_path, 'r') as file_pointer:
file_contents_string = file_poi... | 'Josiah Wolf Oberholtzer',
'Víctor Adán',
]
author = ', '.join(author)
author_email = [
'[email protected]',
'[email protected]',
'[email protected]',
]
author_email = ', '.join(author_email)
keywords = [
'music | composition',
'music notation',
'formalized score control',
'lilypond',
]
keywords = ', '.join(keywords)
install_requires = [
'configobj',
'ply',
'six',
]
version = '.'.join(str(x) for x in sys.version_info[:3])
if StrictVersion(version) < StrictVersion('3.4.0'):
install_requires.a... |
MarxMustermann/OfMiceAndMechs | src/itemFolder/plants/tree.py | Python | gpl-3.0 | 2,733 | 0.004025 | import src
import random
class Tree(src.items.Item):
"""
ingame item serving as an infinite food source
"""
type = "Tree"
bolted = True
walkable = False
numMaggots = 0
name = "tree"
def __init__(self):
"""
initialise internal state
"""
super().__in... |
targetFull = False
targetPos = (self.xPosition + 1, self.yPosition, self.zPosition)
items = self.container.getItemByPosition(targetPos)
if len(items) > 15:
targetFull = True
for item in items:
if item.walkable == False:
targetFull = True
... | character.addMessage("the target area is full, the machine does not work")
return
if not self.numMaggots:
character.addMessage("The tree has no maggots left")
return
# spawn new item
self.numMaggots -= 1
new = src.items.itemMap["VatMaggot"... |
cemsbr/python-openflow | pyof/v0x01/common/utils.py | Python | mit | 5,060 | 0 | """Helper python-openflow functions."""
# System imports
# Third-party imports
# Local source tree imports
# Importing asynchronous messages
from pyof.v0x01.asynchronous.error_msg import ErrorMsg
from pyof.v0x01.asynchronous.flow_removed import FlowRemoved
from pyof.v0x01.asynchronous.packet_in import PacketIn
from ... | buffer, inclu | ding header pack.
Args:
buffer (bytes): Bytes representation of a openflow message.
Returns:
object: Instance of openflow message.
"""
hdr_size = Header().get_size()
hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:]
header = Header()
header.unpack(hdr_buff)
mes... |
ychenracing/Spiders | flhhkkSpider/flhhkk/items.py | Python | apache-2.0 | 420 | 0 | # -*- coding: utf-8 -*-
# Define here | the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class FlhhkkItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
_id = scrapy.Field()
title = scrapy.Field()
content = scrapy.Field()
... | ield()
|
phate89/tvdbsimple | tvdbsimple/__init__.py | Python | gpl-3.0 | 2,681 | 0.00597 | # -*- coding: utf-8 -*-
"""
`tvdbsimple` is a wrapper, written in Python, for TheTVDb.com
API v2. By calling the functions available in `tvdbsimple` you can simplify
your code and easily access a vast amount of tv and cast data. To find
out more about TheTVDb API, check out the [official api page](https://api.thet... | port Updates
from .user import User, User_Ratings
KEYS = keys()
"""
Contains `API_KEY` and `API_TOKEN`.
To use the module you have to set at least the `API_KEY` value (THETVDb api key).
You can also provide an `API_TOKEN` if you already have a valid one stored. If the
valid token doesn't work anymore the module will... | PI_KEY` variable
"""
|
dagothar/gripperz | ext/rbfopt/doc/conf.py | Python | gpl-2.0 | 11,493 | 0.006352 | # -*- coding: utf-8 -*-
#
# RBFOpt documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 11 00:01:21 2015.
#
# 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.
#
# Al... | on info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0.2'
# The language for content a | utogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
# There are two options for replacing |today|: either, you set today to some
... |
asurve/arvind-sysml | src/main/python/systemml/project_info.py | Python | apache-2.0 | 1,177 | 0.001699 | #-------- | -----------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for addit | ional 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 the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
hackultura/siscult-migration | models/mixins.py | Python | gpl-2.0 | 593 | 0 | # -*- coding: utf-8 -*-
from sqlalchemy import Column, Integer, String
from settings import DATABASE_NAMES
class EntesMixin(object):
__table_args__ = {'schema': DATABASE_NAMES.get('entes')}
class ProfileMixin(object):
__table_args__ = {'schem | a': DATABASE_NAMES.get('perfis')}
class AdminMixin(object):
__table_args__ = {'schema': DATABASE_NAMES.get('admin')}
class UserMixin(object):
__table_args__ = {'schema': DATABASE_NAMES.get('usuarios')}
c | lass ClassificacaoArtisticaMixin(object):
id = Column(Integer, primary_key=True)
descricao = Column(String(50))
|
plotly/python-api | packages/python/plotly/plotly/validators/scattercarpet/marker/_gradient.py | Python | mit | 1,063 | 0.000941 | import _plotly_utils.basevalidators
class GradientValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name="gradient", parent_name="scattercarpet.marker", **kwargs
):
super(GradientValidator, self).__init__(
plotly_name=plotly_name,
par... | .
colorsrc
| Sets the source reference on Chart Studio Cloud
for color .
type
Sets the type of gradient used to fill the
markers
typesrc
Sets the source reference on Chart Studio Cloud
for type .
""",
),
... |
shobhitmishra/CodingProblems | LeetCode/Session3/DeleteNodeBST.py | Python | mit | 2,274 | 0.004837 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
node = parent = None
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
# search for the node and its parent
self.findNodeAndParent(root, key)
if s... | node:
| parent.left = None
else:
parent.right = None
return
# if node has only one child
if not node.left or not node.right:
child = node.left if not node.right else node.right
node.val = child.val
node.left = chi... |
pinax/pinax-likes | pinax/likes/templatetags/pinax_likes_tags.py | Python | mit | 4,981 | 0.000602 | from django import template
from django.contrib.contenttypes.models import ContentType
from django.template import loader
from django.template.loader import render_to_string
from ..conf import settings
from ..models import Like
from ..utils import _allowed, widget_context
register = template.Library()
@register.sim... | nd(
ContentType.object | s.get(app_label=app, model__iexact=model)
)
return Like.objects.filter(sender=user, receiver_content_type__in=content_types)
@register.simple_tag
@register.filter
def likes_count(obj):
"""
Usage:
{% likes_count obj %}
or
{% likes_count obj as var %}
or
{{ obj|likes... |
pymedusa/Medusa | ext/cloudscraper/captcha/__init__.py | Python | gpl-3.0 | 1,511 | 0.004633 | import abc
import logging
import sys
if sys.version_inf | o >= (3, 4):
ABC = abc.ABC # noqa
else:
ABC = abc.ABCMeta('ABC', (), {})
# ------------------------------------------------------------------------------- #
captchaSolvers = {}
# ------------------------------------------------------------------------------- #
class Captcha(ABC):
@abc.abstractmethod
... | __(self, name):
captchaSolvers[name] = self
# ------------------------------------------------------------------------------- #
@classmethod
def dynamicImport(cls, name):
if name not in captchaSolvers:
try:
__import__(f'{cls.__module__}.{name}')
... |
jpn--/larch | larch/util/data_manipulation.py | Python | gpl-3.0 | 2,789 | 0.042668 |
import pandas
import numpy
import operator
from sklearn.preprocessing import OneHotEncoder
from typing import Mapping
def one_hot_encode(vector, dtype='float32', categories=None, index=None):
if isinstance(vector, pandas.Series):
index = vector.index
vector = vector.values
encoder = OneHotEncoder(
categori... | mapping=None,
default=None,
right=True,
left=True,
**kwargs,
):
"""
Label sections of a continuous variable.
This function contrasts with `pandas.cut` in that
there can be multiple non-contiguous se | ctions of the
underlying continuous interval that obtain the same
categorical value.
Parameters
----------
values : array-like
The values to label. If given as a pandas.Series,
the returned values will also be a Series,
with a categorical dtype.
mapping : Collection or Mapping
A mapping, or a collection ... |
hebecked/DHT-displayNlog | pc/logNplot.py | Python | gpl-3.0 | 4,651 | 0.037411 | #!/usr/bin/python2.7
import numpy as numpy
import time
import serial
import os, sys
import argparse
from dynamic_plot import live_plots
class serialCOM:
"""A simple class to fetch temperature and humidity information via a arduino micro connected to a DHT22"""
def __init__(self, port, two, baud=9600, timeout=1):
... | nes the Port to connect to the arduino.')
args = parser.parse_args()
if(args.SEC):
if((args.SEC < 2 or args.SEC > args.TIME )):
print "Error! Please choose a value greater than 2 seconds and the time interval."
exit
sC=serialCOM(args.PORT ,args.TWO)
if(args.SEC):
lp = live_plots(0,args.SEC,two_plots=Tr... | time.sleep(args.TIME)
t,h=sC.returnLatest()
if(args.TWO):
t2,h2=sC.returnLatest2()
if(args.SEC):
lp.update_time(args.TIME,t,h)
lp.clean_arrays()
if(args.TWO):
lp2.update_time(args.TIME,t2,h2)
lp2.clean_arrays()
if(args.FILE):
sC.writeFile(args.FILE)
else:
time.sleep(2)
t,h... |
zachdj/ultimate-tic-tac-toe | generate_data.py | Python | mit | 4,760 | 0.001681 | """
Script to generate "labelled" data using random playouts
A lot of this can now be done with the RunExperiment scene
"""
from models.game import *
from models.data import DatabaseConnection as DB, GameDataModel
import timeit
def full_game_experiment(total_games, purge=10):
"""
Simulates many random... | (range(0, MOVE_SEQUENCE_LENGTH)):
move = game._take_step()
sequence.append(move)
move_sequences.append(sequence)
# we now have several move sequences that will take us to a fixed mid-game state - generate data for each of these
for idx, sequence in enumerate(move_sequences):
... | s" % (idx + 1))
for experiment in list(range(0, GAMES_PER_BOARD)):
game = Game(p1, p2)
for move in sequence: # bring the game to its mid-completed state
game.make_move(move)
# finish the game randomly and save
game.finish_game()
game... |
geobricks/geobricks_data_scripts | geobricks_data_scripts/dev/storage/data/delete/delete_storage_metadata.py | Python | gpl-2.0 | 217 | 0 | from geobricks_da | ta_scripts.dev.utils.data_manager_util import get_data_manager
data_manager = get_data_manager()
# TODO How to handle the | fact that is in storage?
data_manager.delete("mod13a2", True, False, False)
|
argaghulamahmad/MNK-Game | StartGame.py | Python | mit | 531 | 0.003766 | # Nama Mahasiswa | : Arga Ghulam Ahmad
# NPM Mahasiswa : 1606821601
# Mata Kuliah : Dasar Dasar Pemrograman 1
# Kelas : A
# Tugas : MNK Game
# Tanggal Deadline : 16 November 2016
# Interpreter : Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55)
from GameMNK import *
from win32api import GetSystemMetric... | 0)
height = GetSystemMetrics(1)
except:
width = 800
height = 600
GameMNK(width, height) |
adrienpacifico/openfisca-france | openfisca_france/scripts/generate_columns_tree.py | Python | agpl-3.0 | 6,397 | 0.005471 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate the columns tree from flat dictionary of columns.
When tree already exists, don't change location of columns that have already been placed in tree.
"""
import argparse
import collections
import logging
import os
import pprint
import sys
from openfisca_core... | n(column):
continue
if name | in placed_columns_name:
continue
placed_columns_name.add(name)
entity_children = columns_name_tree_by_entity.setdefault(column.entity, collections.OrderedDict()).setdefault(
'children', [])
if entity_children and entity_children[-1].get('label') == u'Autres':
... |
olavurmortensen/gensim | gensim/test/test_doc2vec.py | Python | lgpl-2.1 | 20,905 | 0.003639 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <[email protected]>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
from __future__ import with_statement
import log... | assertRaises(RuntimeError, doc2vec.Doc2Vec, [])
# input not empty, but rather completely filtered out
self.assertRaises(RuntimeError, doc2vec.Doc2Vec, list_corpus, min_count=10000)
def test_simil | arity_unseen_docs(self):
"""Test similarity of out of training sentences"""
rome_str = ['rome', 'italy']
car_str = ['car']
corpus = list(DocsLeeCorpus(True))
model = doc2vec.Doc2Vec(min_count=1)
model.build_vocab(corpus)
self.assertTrue(model.docvecs.similarity_u... |
noirbizarre/django-absolute | absolute/context_processors.py | Python | lgpl-3.0 | 703 | 0.004267 | # -*- coding: utf-8 -*-
from django.contrib.sites.models import Site
from django.conf import settings
def get_site_url(request, slash=False):
domain = Site.objects.get_current().domain
protocol = 'https' if request.is_secure() else 'http'
root = "%s://%s" % (protocol, domain)
if slash:
root +=... | : request.build_absolute_uri('/')[:-1],
'ABSOLUTE_ROOT_URL': request.build_absolute_uri('/'),
}
if 'django.contrib.sites' in settings.INSTALLED_APPS:
| urls['SITE_ROOT'] = get_site_url(request)
urls['SITE_ROOT_URL'] = get_site_url(request, True)
return urls |
FederatedAI/FATE | python/federatedml/statistic/statics.py | Python | apache-2.0 | 24,470 | 0.002248 | #
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | .fabs(x) >= consts.FLOAT_ZERO else 0.0 for x in variance])
return variance
@property
def coefficient_of_variance(self):
mean = np.array([consts.FLOAT_ZERO if math.fabs(x) < consts.FLOAT_ZERO else x
for x in self.mean])
return np.fabs(self.stddev / mean)
@pr... | :
return np.sqrt(self.variance)
@property
def moment_3(self):
"""
In mathematics, a moment is a specific quantitative measure of the shape of a function.
where the k-th central moment of a data sample is:
.. math::
m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - \ba... |
vasily-v-ryabov/pywinauto | examples/notepad_slow.py | Python | bsd-3-clause | 9,099 | 0.003737 | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/cont | ributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice... | distributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promot... |
snlab/alto-server | plugins/autoird/basicird.py | Python | apache-2.0 | 542 | 0.00369 | #!/usr/bin/env python3
class SimpleIRD():
"""
"""
def __init__(self, get_meta = None, **kargs):
self.get_meta = get_meta
for name, method in kargs.items():
setattr(self, name, method)
def get_capabilities(self):
return self.get_meta().get('capabilities', {})
... | eturn self.get_meta().get('uses', [])
def get_resource_id(self):
return self.get_meta().get(' | resource-id')
def get_service(self):
return self.get_meta().get('output')
|
ahmad88me/PyGithub | tests/Deployment.py | Python | lgpl-3.0 | 3,609 | 0.007204 | ############################ Copyrights and license ############################
# #
# Copyright 2020 Steve Kowalik <[email protected]> #
# Copyright 2020 Pascal Hofmann <[email protected]> ... | any later version. #
# #
# PyGithub 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 Lesser General Public License for more #
# details. #
# ... |
PullRequestFive/CmdrData | cmdrdata/cmdrdata.py | Python | mit | 1,690 | 0.012426 | import logging
import message
import os
import random
import datetime
import time
import collections
from google.appengine.ext.webapp import template
try: import simplejson as json
except ImportError: import json
from abstract_app import AbstractApp
class CmdrData(AbstractApp):
# A user who has authorized your a... | categories']
categ | ory_name = find_primary_category(categories)
now = datetime.datetime.now()
tsd = datetime.timedelta(days=7)
t = now - tsd
epoch_seconds = int(time.mktime(t.timetuple()))
limit = 100
parameters = {'limit': limit,
'afterTimestamp': epoch_seconds}
week_checkins = client.users... |
OCA/bank-payment | account_payment_order_vendor_email/__manifest__.py | Python | agpl-3.0 | 634 | 0 | # Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http: | //www.gnu.org/licenses/agpl).
{
"name": "Account Payment Order Email",
"version": "14.0.1.0.0",
"license": "AGPL-3",
"author": "Open Source Integrators, Odoo Community Association (OCA)",
"maintainers": [],
"website": "https://github.com/OCA/bank-payment",
"category": "Accounting",
"dep... | "views/account_payment_mode_view.xml",
"views/account_payment_order_view.xml",
],
"installable": True,
}
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.6/Lib/lib2to3/fixes/fix_import.py | Python | mit | 1,817 | 0.001101 | """Fixer for import statements.
If spam is being imported from the local directory, this import:
from spam import eggs
Becomes:
from .spam import eggs
And this import:
import spam
Becomes:
from . import spam
"""
# Local imports
from .. import fixer_base
from os.path import dirname, join, exists, paths... | rt' any >
|
import_name< type='import' imp=any >
"""
def transform(self, node, results):
imp = results['imp']
if unicode(imp).startswith('.'):
# Already a new-style import
return
if not probably_a_local_import(unicode(imp), self.filename):
#... | alue == 'from':
# Some imps are top-level (eg: 'import ham')
# some are first level (eg: 'import ham.eggs')
# some are third level (eg: 'import ham.eggs as spam')
# Hence, the loop
while not hasattr(imp, 'value'):
imp = imp.children[0]
... |
termie/nova-migration-demo | nova/api/openstack/extensions.py | Python | apache-2.0 | 15,632 | 0.001215 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# Copyright 2011 Justin Santa Barbara
# 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... | raise NotImplementedError()
def get_namespace(self):
"""The XML namespace for the extension.
e.g. 'http://www.fox.in.socks/api/ext/pie/v1.0'
"""
raise NotImplementedError()
def get_updated(self):
"""The timestamp when the extension was last updated.
e.... | raise NotImplementedError()
def get_resources(self):
"""List of extensions.ResourceExtension extension objects.
Resources define new nouns, and are accessible through URLs.
"""
resources = []
return resources
def get_actions(self):
"""List of extensions.A... |
alanjw/GreenOpenERP-Win-X86 | python/Lib/site-packages/_xmlplus/dom/html/HTMLDListElement.py | Python | agpl-3.0 | 1,396 | 0.007163 | ########################################################################
#
# File Name: HTMLDListElement
#
#
### This file is automatically generated by GenerateHtml.py.
### DO NOT EDIT!
"""
WWW: http://4suite.com/4DOM e-mail: [email protected]
Copyright (c) 2000 Fourthought Inc, USA. All Right... | m import Node
from xml.dom.html.HTMLElement import HTMLElement
class HTMLDListElement(HTMLElement):
def __init__(self, ownerDocument, nodeName="DL"):
HTMLElement.__init__(self, ownerDocument, nodeN | ame)
### Attribute Methods ###
def _get_compact(self):
return self.hasAttribute("COMPACT")
def _set_compact(self, value):
if value:
self.setAttribute("COMPACT", "COMPACT")
else:
self.removeAttribute("COMPACT")
### Attribute Access Mappings ###
_re... |
artfwo/aiosc | aiosc.py | Python | mit | 6,724 | 0.00238 | # aiosc - a minimalistic OSC communication module using asyncio
#
# Copyright (c) 2014 Artem Popov <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... | , tail[:len])[0], tail[len:]
elif t == 's':
value | , tail = read_string(tail)
elif t == 'b':
value, tail = read_blob(tail)
elif t == 'T':
value = True
elif t == 'F':
value = False
elif t == 'N':
value = None
elif t == 'I':
value = Impulse
else:
raise ... |
joaormatos/anaconda | tools/hfatiler/setup.py | Python | gpl-3.0 | 349 | 0.002865 | import sys
sys.path.append('../../../')
from cx_Freeze import setup, Executable
build_options = {'packages': ['PIL', 'mmfparser'],
'excludes': ['tcl', 'tk', 'Tkinter']}
executables = [
Executable('hfatiler.py', base='Console', targetName='hfatiler.e | xe')
]
s | etup(options={'build_exe': build_options}, executables=executables)
|
pythonanywhere/helper_scripts | tests/test_api_base.py | Python | mit | 1,981 | 0.003534 | from unittest.mock import patch
import pytest
import responses
from pythonanywhere.api.base import AuthenticationError, call_api, get_api_endpoint
class TestGetAPIEndpoint:
def test_defaults_to_pythonanywhere_dot_com_if_no_environment_variables(self):
assert get_api_endpoint() == "https://www.pythonany... | raises_on_401(self, api_token, api_responses):
url = "https://foo.com/"
api_responses.add(responses.POST, url, status=401, body="nope")
with pytest.raises(AuthenticationError) as e:
call_api(url, "post")
assert str(e.value) == "Authentication error 401 calling API: nope"
... | (self, api_token, monkeypatch):
monkeypatch.setenv("PYTHONANYWHERE_INSECURE_API", "true")
with patch("pythonanywhere.api.base.requests") as mock_requests:
call_api("url", "post", foo="bar")
args, kwargs = mock_requests.request.call_args
assert kwargs["verify"] is False
d... |
mehta-raghav/fred-pygtav | screengrab.py | Python | gpl-3.0 | 1,245 | 0.009639 | import cv2
import time
import numpy as np
import win32gui, win32ui, win32con, win32api
hwin = win32gui.FindWindow(None,'Grand Theft Auto V')#it gets the process ID or as microsoft calls it 'window handle'
rect = win32gui.GetWindowRect(hwin)
def grab_screen():
while(True):
x = rect[0]
| y = rect[1]
left = 0
top = 40
height = rect[3] - y - top
width = rect[2] - x
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCom... | tibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
signedIntsArray = bmp.GetBitmapBits(True)
img = np.fromstring(signedIntsArray, dtype='uint8')
img.shape = (height,width,4)
srcdc.De... |
techtonik/pip | tests/lib/test_lib.py | Python | mit | 1,893 | 0 | """Test the test support."""
from __future__ import absolute_import
import filecmp
import re
from os.path import isdir, join
from tests.lib import SRC_DIR
def test_tmp_dir_exists_in_env(script):
"""
Test that $TMPDIR == env.temp_path and path exists and env.assert_no_temp()
passes (in fast env)
"""
... | temp() # this fails if env.tmp_path doesn't exist
assert script.environ['TMPDIR'] == script.temp_path
assert isdir(script.temp_path)
def test_correct_pip_version(script):
"""
Check we are running proper version of pip in run_pip.
"""
# output is like:
| # pip PIPVERSION from PIPDIRECTORY (python PYVERSION)
result = script.pip('--version')
# compare the directory tree of the invoked pip with that of this source
# distribution
pip_folder_outputed = re.match(
r'pip \d+(\.[\d]+)+(\.?(b|rc|dev|pre|post)\d+)? from (.*) '
r'\(python \d(.[\d]... |
sqlalchemy/alembic | alembic/ddl/sqlite.py | Python | mit | 6,734 | 0 | import re
from typing import Any
from typing import Dict
from typing import Optional
from typing import TYPE_CHECKING
from typing import Union
from sqlalchemy import cast
from sqlalchemy import JSON
from sqlalchemy import schema
from sqlalchemy import sql
from .impl import DefaultImpl
from .. import util
if TYPE_CHE... | nt(self, const: "Constraint"):
if const._create_rule is None: # type:ignore[attr-defined]
raise NotImplementedError(
"No support for ALTER of constraints in SQLite dialect. "
"Please refer to the batch mode feature which allows for "
"SQLite migration... | rendered_metadata_default: Optional[str],
rendered_inspector_default: Optional[str],
) -> bool:
if rendered_metadata_default is not None:
rendered_metadata_default = re.sub(
r"^\((.+)\)$", r"\1", rendered_metadata_default
)
rendered_metadata_def... |
vileopratama/vitech | src/openerp/addons/base/tests/test_view_validation.py | Python | mit | 3,424 | 0.000876 | # This test can be run stand-alone with something like:
# > PYTHONPATH=. python2 openerp/tests/test_view_validation.py
from lxml import etree
from StringIO import StringIO
import unittest
from openerp.tools.view_validation import (valid_page_in_book, valid_att_in_form, valid_type_in_colspan,
... | ss test_view_validation(unitte | st.TestCase):
""" Test the view validation code (but not the views themselves). """
def test_page_validation(self):
assert not valid_page_in_book(invalid_form)
assert valid_page_in_book(valid_form)
def test_all_field_validation(self):
assert not valid_att_in_field(invalid_form)
... |
stonebig/bokeh | examples/reference/models/Cross.py | Python | bsd-3-clause | 775 | 0.00129 | import numpy as np
from bokeh.models import ColumnData | Source, Plot, LinearAxis, Grid
from bokeh.models.markers import Cross
from bokeh.io import curdoc, show
N = 9
x = np.linspace(-2, 2, N)
y = x**2
sizes = np.linspace(10, 20, N)
source = ColumnDataSource(dict(x=x, y=y, sizes=sizes))
plot = Plot(
title=None, plot_width=300, plot_height=300,
min_border=0, toolba... | inearAxis()
plot.add_layout(xaxis, 'below')
yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
curdoc().add_root(plot)
show(plot)
|
nickmckay/LiPD-utilities | Python/lipd/bag.py | Python | gpl-2.0 | 2,447 | 0.001635 | import bagit
from .loggers import create_logger
logger_bagit = create_logger('bag')
def create_bag(dir_bag):
"""
Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag
"""
logger_bagit.info("enter create_bag")
# if ... | }".format(e))
return None
def validate_md5(bag):
"""
Check if Bag is valid
:param obj bag: Bag
:return None:
"""
logger_bagit.info("validate_md5")
if bag.is_valid():
print("Valid md5")
# for path, fixity in bag.entries.items():
# print("path:{}\nmd5:{}\n".fo... |
else:
print("Invalid md5")
logger_bagit.debug("invalid bag")
return
def resolved_flag(bag):
"""
Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag
"""
if 'DOI-Resolved' in bag.info:
logger_bagit.info... |
alexholehouse/SBMLIntegrator | libsbml-5.0.0/src/bindings/python/test/sbml/TestSpecies.py | Python | gpl-3.0 | 8,165 | 0.030496 | #
# @file TestSpecies.py
# @brief Species unit tests
#
# @author Akiya Jouraku (Python conversion)
# @author Ben Bornstein
#
# $Id$
# $HeadURL$
#
# ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ======
#
# DO NOT EDIT THIS FILE.
#
# This file was generated automatically by converting the... | el _dummyList
pass
def test_Species_setSubstanceUnits(self):
units = "item";
self | .S.setSubstanceUnits(units)
self.assert_(( units == self.S.getSubstanceUnits() ))
self.assertEqual( True, self.S.isSetSubstanceUnits() )
if (self.S.getSubstanceUnits() == units):
pass
self.S.setSubstanceUnits(self.S.getSubstanceUnits())
self.assert_(( units == self.S.getSubstanceUnits() ))... |
andrei4ka/fuel-web-redhat | fuel_agent_ci/fuel_agent_ci/tests/test_configdrive.py | Python | apache-2.0 | 6,888 | 0.000726 | # Copyright 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ))
self.ssh.put_content(json.dumps(data), '/tmp/provision.json')
admin_interface = filter(
lambda x: (x['mac_address'] ==
data['kernel_options']['netcfg/choose_interface']),
[dict(name=name, **spec) for name, spec |
in data['interfaces'].iteritems()])[0]
with open('/tmp/boothook.txt', 'wb') as f:
f.write(self.render_template(
template_name='boothook_%s.jinja2' % profile.split('_')[0],
template_data={
'MASTER_IP': data['ks_meta']['master_ip'],
... |
aleasoluciones/gosnmpquerier | tools/data.py | Python | mit | 397 | 0.002519 | commands = (
('walk', '1.3.6 | .1.2.1.2.2.1.2'),
('walk', '1.3.6.1.2.1.2.2.1.10'),
('get', '1.3.6.1.2.1.2.2.1.2.1'),
)
destinations = (
'ada-xem1', 'ona-xem1', 'alo-xem1', 'otm-xem1',
'c2k-xem1', 'vtr-xem1', 'tom-xem1',
'onr-xem1', 'vco-xem1', 'inm-xem1', 'gtr-xem1',
'ram-xem1', 'vir-x | em1', 'tge-xem1', 'ola-xem1',
'pip-xem1', 'vmc-xem1', 'pra-xem1', 'arm-xem1',
)
|
vesellov/callfeed.net | mainapp/migrations/0034_auto_20150614_2007.py | Python | mit | 9,969 | 0.001906 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0033_auto_20150613_2110'),
]
operations = [
migrations.RemoveField(
model... | ield=models.Integ | erField(default=0, verbose_name=b'\xd0\xa1\xd0\xbf\xd0\xb8\xd1\x81\xd0\xb0\xd0\xbd\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xb4\xd0\xbb\xd0\xb8\xd0\xbd\xd0\xb0 \xd1\x80\xd0\xb0\xd0\xb7\xd0\xb3\xd0\xbe\xd0\xb2\xd0\xbe\xd1\x80\xd0\xb0 \xd0\xbd\xd0\xb0 \xd1\x81\xd1\x82\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbd\xd0\xb5 \xd0\xba\xd0\xbb\xd0\xb8\... |
jakeret/abcpmc | abcpmc/sampler.py | Python | gpl-3.0 | 11,199 | 0.008661 | # abcpmc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# abcpmc is distributed in the hope that it will be useful,
# but WITHOUT A... | # setting seed to prevent problem with multiprocessing
self._random.seed(i)
cnt = 1
while True:
idx = self._random.choice(r | ange(self.N), 1, p= self.pool.ws/np.sum(self.pool.ws))[0]
theta = self.pool.thetas[idx]
sigma = self._get_sigma(theta, **self.kwargs)
sigma = np.atleast_2d(sigma)
thetap = self._random.multivariate_normal(theta, sigma)
X = self.postfn(thetap)
p = n... |
dj80hd/certs | certs.py | Python | mit | 7,739 | 0.006719 | import sys
import os
import pexpect
def log(s):
print ">>>" + s
def error_exit(s):
print("ERROR: " + s)
sys.exit(99)
def check_file(fname):
if os.path.isfile(fname) and os.stat(fname).st_size > 0:
pass
else:
error_exit(fname + ' FAILED check.')
def remove_file_if_it_exists(f):
... | endline("") |
p.expect_exact('Organization Name (eg, company) [Internet Widgits Pty Ltd]:')
p.sendline(ORG_NAME)
p.expect_exact('Organizational Unit Name (eg, section) []:')
p.sendline(ORG_UNIT_NAME)
p.expect_exact('Common Name (e.g. server FQDN or YOUR name) []:')
p.sendline(domain)
p.expect_exact('Email Address []:')
p.sendline("... |
Degreane/PsySys | Clients/dealersRouting.py | Python | gpl-3.0 | 9,487 | 0.046063 | from channels.auth import channel_session_user,channel_session_user_from_http,http_session
from channels.routing import route, route_class
from channels.sessions import channel_and_http_session,channel_session
import datetime
import json
import copy
import pprint as pp
from django.http import HttpResponse
from django.... | ge="/"
redirectParam="InvalidSession=true"
encryptedRedirectParam=b64encode(encrypt(redirectParam,encKey))
message.reply_channel.send({
'text':json.dumps({'verdict':encryptedRedirectParam,'redirect':redirectPage})
})
if messageJSON['target'] == 'CNTS':
QAll=Q(isDealer=True)
QEnabled=Q(isDeal... | (QEnabled).count()
DeletedCount=user.objects(QDeleted).count()
DisabledCount=user.objects(QDisabled).count()
CountsObj={
'All':AllCount,
'Ena':EnabledCount,
'Dis':DisabledCount,
'Del':DeletedCount
}
encryptedMSG=b64encode(encrypt(json.dumps(CountsObj),encKey))
message... |
nathanlynch/atx-permit-scraper | src/session.py | Python | agpl-3.0 | 582 | 0.003436 | #!/usr/bin/python | 3
import requests
# url = "http://192.168.1.254"
landing_url = "https://www.austintexas.gov/devreview/a_queryfolder_permits.jsp?myWhere="
res_url = "https://www.austintexas.gov/devreview/d_showpropertyfolderlist.jsp?clicked=searchByOther"
parms = {'Lid': 'ReadOnlyaustin',
'zip': '78722',
'property... | te': 'Apr 24, 2014'}
# print(parms)
s = requests.Session()
landing = s.get(landing_url)
results = s.post(res_url, data=parms)
# print(r.headers)
# print(r.request.headers)
print(results.text)
|
IfcOpenShell/IfcOpenShell | src/blenderbim/blenderbim/bim/module/drawing/gizmos.py | Python | lgpl-3.0 | 18,534 | 0.001133 | # BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2020, 2021 Maxim Vasilyev <[email protected]>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on 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 Softwar... | 254037844384, 0),
(0.0, 0.0, 0.0),
(-0.5000000000000004, -0.8660254037844384, 0),
(-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0),
(-1.8369701987210297e-16, -1.0, 0),
(0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0),
(0.49999999999999933, -0.866025403784439, 0),
(0.8... | 0.0, 0.0, 0.0),
(1.0, 0.0, 0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0),
(0.5000000000000001, 0.8660254037844386, 0),
(6.123233995736766e-17, 1.0, 0),
(0.0... |
alfasin/st2 | st2client/st2client/client.py | Python | apache-2.0 | 6,290 | 0.003816 | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... | self):
| return self.managers['Rule']
@property
def runners(self):
return self.managers['RunnerType']
@property
def sensors(self):
return self.managers['Sensor']
@property
def tokens(self):
return self.managers['Token']
@property
def triggertypes(self):
return ... |
freerangerouting/frr | tests/topotests/static_routing_with_ibgp/test_static_routes_topo3_ibgp.py | Python | gpl-2.0 | 28,602 | 0.001923 | #!/usr/bin/python
#
# Copyright (c) 2020 by VMware, Inc. ("VMware")
# Used Copyright (c) 2018 by Network Device Education Foundation,
# Inc. ("NetDEF") in this file.
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the above c... | ,
stop_router,
start_router,
)
from lib.topolog import logger
from lib.bgp import verify_bgp_convergence, create_router_bgp, | verify_bgp_rib
from lib.topojson import build_config_from_json
pytestmark = [pytest.mark.bgpd, pytest.mark.staticd]
# Global variables
BGP_CONVERGENCE = False
ADDR_TYPES = check_address_types()
NETWORK = {
"ipv4": [
"11.0.20.1/32",
"11.0.20.2/32",
"11.0.20.3/32",
"11.0.20.4/32",
... |
CiscoSystems/avos | openstack_dashboard/dashboards/project/stacks/forms.py | Python | apache-2.0 | 15,580 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | file',
_('Environment File'))
environment_upload = forms.FileField(
label=_('Environment File') | ,
help_text=_('A local environment to upload.'),
widget=forms.FileInput(attrs=attributes),
required=False)
attributes = create_upload_form_attributes(
'env',
'raw',
_('Environment Data'))
environment_data = forms.CharField(
label=_('Environment Data'),
... |
nirs/vdsm | lib/vdsm/storage/operation.py | Python | gpl-2.0 | 6,412 | 0 | #
# Copyright 2018 Red Hat, Inc.
#
# 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.
#
# This program is distributed in th... | h Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
import errno
import logging
import threading
from vdsm import utils
from vdsm.common import cmdutils
from vdsm.common import commands
from vdsm.common.compat import su... | e operation has terminated
TERMINATED = "terminated"
# Abort was called when the operation was running.
ABORTING = "aborting"
# The operation was aborted and is not running.
ABORTED = "aborted"
log = logging.getLogger("storage.operation")
class Command(object):
"""
Simple storage command that does not supp... |
jeanparpaillon/kerrighed-tools | libs/kerrighed.py | Python | gpl-2.0 | 9,679 | 0.005992 | #
# kerrighed.py - A Python interface to libkerrighed
#
# Copyright (c) 2009 Kerlabs
# Author: Jean Parpaillon <[email protected]>
#
LIBKERRIGHED_VERSION = 2
import os
import ctypes
from ctypes import *
libkerrighed_soname = "libkerrighed.so.%i" % LIBKERRIGHED_VERSION
try:
if 'get_errno' in dir(ctypes):
... | os.strerror(libkerrighed.krg_get_status)))
return krg_node_set(ret)
def get_present(self):
ret = libkerrighed.krg_nodes_get_present(self.c)
if ret is None:
raise kerrighed_error("error in %s: %s" % (self.get_present.__name__,
... | tatus)))
return krg_node_set(ret)
def get_online(self):
ret = libkerrighed.krg_nodes_get_online(self.c)
if ret is None:
raise kerrighed_error("error in %s: %s" % (self.get_online.__name__,
os.strerror(libkerrighed.krg_get_st... |
Turgon37/SMSShell | tests/test_cmdline_parser.py | Python | gpl-3.0 | 2,168 | 0.004613 | # -*- coding: utf8 -*-
import json
import os
import shlex
import subprocess
# command line test
def test_cmdline_help():
"""Must produce an error is no url was given"""
result = subprocess.Popen(shlex.split('./bin/sms-shell-parser --help'), stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
... | )
# Load env
for key in | env:
os.environ[key] = env[key]
result = subprocess.Popen(shlex.split('./bin/sms-shell-parser --input env'), stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
if isinstance(stdout, bytes):
stdout = stdout.decode()
obj = json.loads(stdout)
assert result.returncode == 0
... |
gangadhar-kadam/mtn-erpnext | accounts/report/item_wise_sales_register/item_wise_sales_register.py | Python | agpl-3.0 | 2,744 | 0.030977 | # ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at yo... | k/Sales Invoice:120", "Postin | g Date:Date:80", "Customer:Link/Customer:120",
"Customer Account:Link/Account:120", "Territory:Link/Territory:80",
"Project:Link/Project:80", "Company:Link/Company:100", "Sales Order:Link/Sales Order:100",
"Delivery Note:Link/Delivery Note:100", "Income Account:Link/Account:140",
"Qty:Float:120", "Rate:Curre... |
planlos/pl-mediaservice | mediaservice/api/media.py | Python | gpl-3.0 | 1,051 | 0.015224 | from flask.ext.restful import Resource
from flask import make_response, jsonify
class Media_Api( | Resource):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def get(self, cmd = None):
if cmd == "_s | tatus":
response = dict(
msg = "mediaservice status",
documents = 1
)
else:
response = dict(
msg = "Hello, this is mediaservice"
)
return make_response(jsonify(response))
def post(self):
pass
c... |
avikdatta/python_scripts | lib/eHive_files/Runnable/Ftp_bed_file_factory.py | Python | apache-2.0 | 1,990 | 0.025126 | import eHive, os
import pandas as pd
from collections import defaultdict
from urllib.parse import urlsplit, urlunparse
def read_index_data(index, ftp_url, dir_prefix):
'''
This function accept an index file and prepare a list of seeds
containing the experiment id and file url
'''
# define empty list of ... | loc[exp_id]['FILE']
else:
file_uri=data_chunk.loc[exp_id][data_chunk.loc[exp_id]['FILE'].str.contains('bed.gz')]['FILE'][exp_id]
if not file_uri:
raise Exception('No file uri found for exp id: {0}'.format(exp_id))
if file_uri.endswith('bed.gz'):
# Process only bed... | i,'','',''))
seed_list.append({'experiment_id':exp_id, 'file_uri':file_uri})
except Exception as e:
sys.exit('Got error: {0}'.format(e))
return seed_list
class Ftp_bed_file_factory(eHive.BaseRunnable):
def param_defaults(self):
return {
'ftp_url':'ftp.ebi.ac.uk',
'dir_prefi... |
kaarolch/ansible | lib/ansible/modules/cloud/amazon/rds_subnet_group.py | Python | gpl-3.0 | 5,396 | 0.007969 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | error_code != 'DBSubnetGroupNotFoundFault':
module.fail_json(msg = e.error_message)
if state == 'absent':
if exists:
conn.delete_db_subnet_group(group_name)
changed = True
else:
if not exists:
new_group = co... | up_subnets)
changed = True
else:
# Sort the subnet groups before we compare them
matching_groups[0].subnet_ids.sort()
group_subnets.sort()
if ( (matching_groups[0].name != group_name) or (matching_groups[0].description != group_... |
vgrem/Office365-REST-Python-Client | tests/graph_case.py | Python | mit | 1,515 | 0.00396 | from unittest import TestCase
import msal
from office365.graph_client import GraphClient
from tests import load_settings
def acquire_token_by_username_password():
settings = load_settings()
authority_url = 'https://login.microsoftonline.com/{0}'.format(settings.get('default', 'tenant'))
app = msal.Publi... | scopes=["https://graph.microsoft.com/.def | ault"])
return result
def acquire_token_by_client_credentials():
settings = load_settings()
authority_url = 'https://login.microsoftonline.com/{0}'.format(settings.get('default', 'tenant'))
app = msal.ConfidentialClientApplication(
authority=authority_url,
client_id=settings.get('clien... |
whinedo/sdnlb | sdnlb/heartbeat/heartbeat.py | Python | gpl-3.0 | 4,347 | 0.047389 | from multiprocessing import Process
import time
import commands
from socketconnection import SocketConnection
from json_message import *
from subprocess import Popen, PIPE, STDOUT
import sdnlb_conf
class HeartBeat (object):
def __init__(self,ip,services,sendEvent=False):
self.services = services
self.sendEvent =... | = JsonMessage.genCmdReqMessage(cmd,args)
socket.send(msg)
msg = socket.receive()
#DEBUG
print "HB msg recv:",msg
#FINDEBUG
if msg != '':
(msgtype, data) = JsonMessage.parse_json(msg)
if (msgtype == msgTypes['cmd_ans']):
if (data['cmd... | t))
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
json_msg = JsonMessage.parse_iperf_json(output)
if (json_msg['end']['cpu_utilization_percent']['remote_system'] != No... |
alexander-yu/nycodex | scripts/socrata_raw.py | Python | apache-2.0 | 1,584 | 0 | from nycodex import db
from nycodex.logging import get_logger
from nycodex.scrape import scrape_dataset, scrape_geojson
from nycodex.scrape.exceptions import SocrataError
BASE = "https://data.cityofnewyork.us/api"
logger = get_logger(__name__)
def main():
session = db.Session()
while True:
try:
... | fields, types)
elif dataset_type == db.AssetType.MAP:
scrape_geojson(trans, dataset_id)
else:
log.warning("Illegal dataset_ | type")
except SocrataError as e:
log.error("Failed to import dataset", exc_info=e)
except Exception as e:
log.critical(
"Failed to import datset with unknown exception", exc_info=e)
if __name__ == "__main__":
main()
|
patricklaw/pants | src/python/pants/backend/project_info/dependees.py | Python | apache-2.0 | 6,668 | 0.00225 | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
from collections import defaultdict
from dataclasses import dataclass
from enum import Enum
from typing import Iterable, Set, cast
from pants.base.specs import AddressSpecs, D... | esult = (
dependents | set(request.addresses)
if request.include_roots
else dependents - set(request.addresses)
)
return Dependees(result)
known_dependents = dependents
class DependeesOutputFormat(Enum):
text = "text | "
json = "json"
class DependeesSubsystem(LineOriented, GoalSubsystem):
name = "dependees"
help = "List all targets that depend on any of the input files/targets."
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--transiti... |
abhishekshanbhag/emotion_based_spotify | spotifyAPITest/python/test.py | Python | gpl-3.0 | 75 | 0.04 | import sys
def main():
print | (1)
if __name__ == '__main__':
ma | in() |
nycholas/ask-undrgz | src/ask-undrgz/django/contrib/localflavor/ro/forms.py | Python | bsd-3-clause | 6,464 | 0.003868 | # -*- coding: utf-8 -*-
"""
Romanian specific form helpers.
"""
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError, Field, RegexField, Select
from django.utils.translation import ugettext_lazy as _
class ROCIFField(RegexField):
"""
A Romanian fiscal identity co... | or_messages = {
'invalid': _("Enter a valid CNP."),
}
def __init__(self, *args, **kwargs):
super(ROCNPField, self).__init__(r'^[1-9][0-9]{12}', max_length=13,
min_length=13, *args, **kwargs)
def clean(self, value):
"""
CNP validations
"""
value =... | etime.date(int(value[1:3]),int(value[3:5]),int(value[5:7]))
except:
raise ValidationError(self.error_messages['invalid'])
# checksum
key = '279146358279'
checksum = 0
value_iter = iter(value)
for digit in key:
checksum += int(digit) * int(value_ite... |
chrivers/pyjaco | tests/list/subclass.py | Python | mit | 147 | 0.006803 | class A(list):
def m | y_append(self, a):
self.append(a)
a = A()
print a
a.appe | nd(5)
print a
a.my_append(6)
print a
a.remove(5)
print a
|
spikeekips/source-over-ssh | src/tests/__init__.py | Python | gpl-3.0 | 344 | 0.011628 | # -*- coding: utf-8 -*-
__all__ = [
"test_config_db",
"test_grid",
"test | _shell",
"test_svn",
]
|
if __name__ == "__main__" :
import doctest
for i in __all__ :
print ("%%-%ds: %%s" % (max(map(len, __all__)) + 1)) % (
i,
doctest.testmod(__import__(i, None, None, [i, ], ), ),
)
|
hbldh/flask-pybankid | tests/test_config.py | Python | mit | 1,775 | 0.001127 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`test_config`
==================
Created by hbldh <[email protected]>
Created on 2016-02-04
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import ... | self.context = self.app.test_request_context("/")
self.context.push()
def tearDown(self):
self.context.pop()
try:
os.remove(self.certificate_file)
os.remove(self.key_file)
except:
pass
def test_default_config_prefix(self):
self.app... | ificate_file
self.app.config["PYBANKID_KEY_PATH"] = self.key_file
self.app.config["PYBANKID_TEST_SERVER"] = True
fbid = PyBankID(self.app)
assert fbid.client.certs == (self.certificate_file, self.key_file)
assert fbid.client.api_url == "https://appapi2.test.bankid.com/rp/v4"
... |
CospanDesign/python | site/test_site_utils.py | Python | mit | 415 | 0.009639 | import os
import sys
import site
import site_utils
def test_site_dir_exists():
result = site_utils.site_dir_exists("test")
def test_ | create_site_dir():
site_utils.create_site_dir("test")
tdir = os.path.join(site.getuserbase(), "test")
#print "tdir: %s" % | str(tdir)
assert os.path.exists(tdir)
site_utils._remove_site_dir("test")
assert not site_utils.site_dir_exists("test")
|
wangheda/youtube-8m | youtube-8m-wangheda/all_frame_models/distillchain_lstm_cnn_deep_combine_chain_model.py | Python | apache-2.0 | 7,770 | 0.012098 | import math
import models
import tensorflow as tf
import numpy as np
import utils
from tensorflow import flags
import tensorflow.contrib.slim as slim
FLAGS = flags.FLAGS
class DistillchainLstmCnnDeepCombineChainModel(models.BaseModel):
"""A softmax over a mixture of logistic models (with L2 regularization)."""
de... | _scope="", **unused_params):
num_mixtures = num_mixtures or FLAGS.moe_num_mixtures
gate_activations = slim.fully_connected(
model_input,
vocab_size * (num_mixtures + 1),
activation_fn=None,
biases_initializer=None,
weights_regularizer=slim.l2_regularizer(l2_penalty),
... | _scope)
expert_activations = slim.fully_connected(
model_input,
vocab_size * num_mixtures,
activation_fn=None,
weights_regularizer=slim.l2_regularizer(l2_penalty),
scope="experts-"+sub_scope)
gating_distribution = tf.nn.softmax(tf.reshape(
gate_activations,
... |
hjorturlarsen/Kapall | menu.py | Python | mit | 5,750 | 0.009913 | #!/usr/bin/env python
# encoding: utf-8
'''
Created on Apr 8, 2013
@author: redw0lf
'''
import pygame, sys, os, random
fro | m pygame.locals import *
class MenuItem (pygame.font.Font):
'''
The Menu Item should be derived from the pygame Font class
'''
def __init__(self, text, position, fontSize=55, antialias=1, color=(255, 255, 255), background=None):
pygame.font.Font.__init__(self, 'data/menu_font.ttf', fontSize)
... | t
if background == None:
self.textSurface = self.render(self.text, antialias, (255, 255, 255))
else:
self.textSurface = self.render(self.text, antialias, (255, 255, 255), background)
self.position = self.textSurface.get_rect(centerx=position[0], centery=position[1])
... |
tanutarou/OptBoard | optboard/urls.py | Python | mit | 838 | 0 | """optboard URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='h | ome')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
| Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.