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 |
|---|---|---|---|---|---|---|---|---|
goerz/texpreview | Texpreview/TexpreviewPrinter.py | Python | gpl-3.0 | 7,524 | 0.007443 | # -*- coding: utf-8 -*-
############################################################################
# Copyright (C) 2008 by Michael Goerz #
# http://www.physik.fu-berlin.de/~goerz #
# ... | oftware; 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. #
# ... | is program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# ... |
Lehych/iktomi | examples/filefield/app.py | Python | mit | 657 | 0.004566 | # -*- coding: utf-8 -*-
from iktomi import web
from iktomi.web.filters import *
from iktomi.templates import jinja2, Template
from environment import Environment
import cfg
import handlers | as h
static = static_files(cfg.STATIC)
media = static_files(cfg.MEDIA, '/media/')
template = Template(cfg.TEMPLATES, jinja2.TEMPLATE_DIR, engines={'html': jinja2.TemplateEngine})
app = web.cases(
static, media,
match('/', 'files') | web.cases(
# Playing REST ;)
method('GET') | h.list_files,
... |
wsgi_app = web.Application(app, env_class=Environment)
|
kohn/HttpProxyMiddleware | HttpProxyMiddleware.py | Python | mit | 11,893 | 0.0038 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import logging
from datetime import datetime, timedelta
from twisted.web._newclient import ResponseNeverReceived
from twisted.internet.error import TimeoutError, ConnectionRefusedError, ConnectError
from crawler import fetch_free_proxyes
logger = logging.getLogger(__... | xy_time + timedelta(minutes=self.recover_interval)):
logger.info("After | %d minutes later, recover from using proxy" % self.recover_interval)
self.last_no_proxy_time = datetime.now()
self.proxy_index = 0
request.meta["dont_redirect"] = True # 有些代理会把请求重定向到一个莫名其妙的地址
# spider发现parse error, 要求更换代理
if "change_proxy" in request.meta.keys() and req... |
triump0870/movie_task | src/mdb/urls.py | Python | mit | 812 | 0.002463 | from django.conf.urls import include, url
from django.contrib import admin
from django.con | f import settings
from django.conf.urls.static import static
import profiles.urls
import accounts.urls
from . import views
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^about/$', views.AboutPage.as_view(), name='about'),
url(r'^users/', include(profiles.urls, namespace='profiles... | urls', namespace='api')),
]
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
444thLiao/VarappX-flask | varappx/samples/samples_service.py | Python | mit | 1,401 | 0.004283 | import logging
import re
from varapp.samples.samples_factory import *
def samples_selection_from_request(request, db, from_ped=True):
"" | "Parse a GET request to make the samples groups and return a SamplesSelection.
:param from_ped | : read groups info based on 'phenotype' attribute in the Samples table.
"""
groups = {}
sample_requests = request.GET.getlist('samples',[])
samples = samples_selection_factory(db).sort('sample_id') # a SamplesCollection
if not sample_requests:
if from_ped:
groups = fetch_ped_inf... |
netllama/tastipy | tastiapp.py | Python | gpl-3.0 | 2,172 | 0.009669 | from bottle import route, template, error, request, static_file, get, post
from index import get_index
from bmarks import get_bmarks
from tags import get_tags
from add import add_tags
from bmarklet import get_bmarklet
from account import get_account
from edit_tags import get_edit_tags
from importbm import get_import_bm... | s(filename):
return static_file(filename, root='js')
# serve images
@get('<filename:re:.*\.png>')
def send_img(filename):
return static_file(filename, root='images')
# serve fonts
@get('<filename:re:.*\.(woff|woff2)>')
def send_font(filename):
return static_file(filename, root='fonts')
@error(404)
def ha... | 0)
def handle500(error):
return '<H1>Oops, its broken: {}<BR>'.format(error)
|
librato/librato-python-web | librato_python_web/statsd/server/daemon.py | Python | bsd-3-clause | 4,981 | 0.000402 | # Based on https://github.com/sivy/pystatsd
#
# Copyright (c) 2014, Steve Ivy
# All rights reserved.
#
# Copyright (c) 2015. Librato, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * R... | sys.stderr.write(msg % self.pidfile)
sys.exit(1)
self.daemonize()
self.run(*args, **kw)
def stop(self):
"""Stop the daemon."""
pid = None
if os.path.exists(self.pidfile):
with open(self.pidfile, 'r') as fp:
pid = int(fp.read().s... | self.pidfile)
return
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError as e:
e = str(e)
if e.find('No such process') > 0:
if os.path.exists(self.pidfile):
os.remove(self.... |
joshzarrabi/e-mission-server | emission/tests/analysisTests/result_precompute/TestPrecomputeResults.py | Python | bsd-3-clause | 3,850 | 0.007013 | # Standard imports
import unittest
import json
import logging
from datetime import datetime, timedelta
# Our imports
from emission.core.get_database import get_db, get_mode_db, get_section_db
from emission.analysis.result.precompute import precompute_results
from emission.core.wrapper.user import User
from emission.co... | ), 0)
self.SectionsColl = get_section_db()
self.assertEquals(self.SectionsColl.find().count(), 0)
emission.tests.common.loadTable(self.serverName, "Stage_M | odes", "emission/tests/data/modes.json")
emission.tests.common.loadTable(self.serverName, "Stage_Sections", "emission/tests/data/testModeInferFile")
# Let's make sure that the users are registered so that they have profiles
for userEmail in self.testUsers:
User.register(userEmail)
... |
kxz/stenographer | stenographer/test/test_agent.py | Python | mit | 4,201 | 0.000714 | """Agent tests."""
# pylint: disable=missing-docstring,too-few-public-methods
import sys
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.python.failure import Failure
from twisted.trial.unittest import TestCase
from twisted.web.client import Headers, Response, ResponseDone, readBody
from... | rt CassetteAgent
from .helpers im | port cassette_path
class CassetteAgentTestCase(FakeReactorAndConnectMixin, TestCase):
def setUp(self):
self.reactor = self.Reactor()
self.agent = self.buildAgentForWrapperTest(self.reactor)
self.connect(None)
def test_saved(self):
agent = CassetteAgent(self.agent, cassette_pat... |
schroeder-dewitt/polyomino-self-assembly | test/SinglePolyomino/main.py | Python | apache-2.0 | 18,944 | 0.023438 | #-------------------------------------------------------------------------------
# Name: GA test module (template hopefully)
# Purpose:
#
# Author: Christian Schroeder, University of Oxford
#
# Created: 31/01/2012
# Copyright: (c) CHRIS 2012
# Licence: GPL
#-------------------------------... | idDimX),
"SubgridDimY": int(SubgridDimY),
"ThreadDimX": int(ThreadDimX),
"ThreadDimY": int(ThreadDimY),
"NrSubgridsPerBank": int(NrSubgridsPerBank),
"NrFourPermutations": int(NrFourPermutations),
" | NrAssemblyRedundancy": int(NrAssemblyRedundancy),
"LengthMovelist":LengthMovelist
}
#Sorting Kernel Params
#GA Simulation Params
GAParamsDict = {
"RateMutation": RateMutation, # This is Mu * L, expectation value of number of flipped bits
"ProbabilityUniformCrossover": ProbabilityUniformCrosso... |
Jacobious52/PythonLab | hash.py | Python | gpl-2.0 | 445 | 0.035955 | import hashlib
import sys
def sha1hash(s):
return hashlib.sha1(s.encode('utf-8')).hexdigest()
def md5hash(s):
return hash | lib.md5(s.encode('utf-8')).hexdigest()
def main():
args = sys.argv
if len(args) == 3:
switch = args[1]
string = args[2]
if switc | h == "md5":
print("{0} : {1}".format(string, md5hash(string)))
elif switch == "sha1":
print("{0} : {1}".format(string, sha1hash(string)))
if __name__ == '__main__':
main() |
pymonger/prov-0.5.4 | prov/model/test/examples.py | Python | mit | 17,487 | 0.00246 | # coding: utf8
from prov.model import ProvBundle, Namespace, Literal, PROV, XSD, Identifier
import datetime
def primer_example():
# https://github.com/lucmoreau/ProvToolbox/blob/master/prov-n/src/test/resources/prov/primer.pn
#===========================================================================
# d... | e('ex', 'http://example.org/')
g.add_namespace('w3', 'http://www.w3.org/')
g.add_namespace('tr', 'http://www.w3.org/TR/2011/')
g.add_namespace('process', 'http://www.w3.org/2005/10/Process-20051014/tr.html#')
g.add_namespace('email', 'https://lists.w3.org/Archives/Member/w3c-archive/')
g.add_namespa... | c54', 'http://www.w3.org/2001/02pd/rec54#')
g.entity('tr:WD-prov-dm-20111018', {'prov:type': 'rec54:WD'})
g.entity('tr:WD-prov-dm-20111215', {'prov:type': 'rec54:WD'})
g.entity('process:rec-advance', {'prov:type': 'prov:Plan'})
g.entity('chairs:2011OctDec/0004', {'prov:type': 'trans:transreq'})
g.... |
depet/scikit-learn | sklearn/utils/tests/test_shortest_path.py | Python | bsd-3-clause | 2,892 | 0.002075 | from collections import defaultdict
import numpy as np
from numpy.testing import assert_array_almost_equal
from sklearn.utils.graph import (graph_shortest_path,
single_source_shortest_path_length)
def floyd_warshall_slow(graph, directed=False):
N = graph.shape[0]
#set nonzer... | _array_almost_equal(graph_D, graph_py)
def test_shortest_path():
dist_matrix = generate_graph(20)
# We compare path length and not costs (-> set distances to 0 or 1)
dist_matrix[dist_matrix != 0] = 1
| for directed in (True, False):
if not directed:
dist_matrix = np.minimum(dist_matrix, dist_matrix.T)
graph_py = floyd_warshall_slow(dist_matrix.copy(), directed)
for i in range(dist_matrix.shape[0]):
# Non-reachable nodes have distance 0 in graph_py
dist_di... |
guillaume-boutin/learning-builderengine | themes/user_dashboard/assets/plugins/jquery-file-upload/server/gae-python/main.py | Python | mit | 6,014 | 0.000831 | # -*- coding: utf-8 -*-
#
# jQuery File Upload Plugin GAE Python Example 2.1.1
# https://github.com/blueimp/jQuery-File-Upload
#
# Copyright 2011, Sebastian Tschan
# https://blueimp.net
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
from __future__ import with_statement
fro... | (
result['name'].encode('utf-8'), '')
results.append(result)
deferred.defer(
cleanup,
blob_keys,
_countdown=EXPIRATION_TIME
)
return results
def options(self):
pass
def he | ad(self):
pass
def get(self):
self.redirect(WEBSITE)
def post(self):
if (self.request.get('_method') == 'DELETE'):
return self.delete()
result = {'files': self.handle_upload()}
s = json.dumps(result, separators=(',', ':'))
redirect = self.... |
wazo-pbx/xivo-tools | pjsip/sync-username-and-names.py | Python | gpl-3.0 | 2,588 | 0.000773 | #!/usr/bin/env python3
# Copyright 2020 The Wazo Authors (see the AUTHORS file)
# SPDX-License-Identifier: GPL-3.0+
import sys
from | wazo_auth_client import Client as AuthClient
from wazo_confd_client import Client as ConfdClient
from xivo.chain_map import ChainMap
from xivo.config_helper import read_config_file_hierarchy, parse_config_file
_DEFAULT_CONFIG = {
'config_file': '/etc/wazo-upgrade/config.yml',
'auth': {
'key_file': '/... | = read_config_file_hierarchy(_DEFAULT_CONFIG)
key_config = _load_key_file(ChainMap(file_config, _DEFAULT_CONFIG))
return ChainMap(key_config, file_config, _DEFAULT_CONFIG)
def _load_key_file(config):
key_file = parse_config_file(config['auth']['key_file'])
return {'auth': {'username': key_file['servi... |
scheunemann/robotActionController | robotActionController/Processor/SensorInterface/humanSensors.py | Python | mit | 5,068 | 0.001973 | import math
from robotActionController.Data.Model import User
from robotActionController.Data.storage import StorageFactory
from robotActionController.Robot.RosInterface import rosHelper
from rosSensors import RobotLocationSensor
class HumanLocationSensor(object):
sensorType = 'HumanLocation'
def __init__(s... | ds.query(User.id).filter(User.name == self._userName).first()
if user:
self._userId, = user
else:
print "User '%s' not found" % self._userName
self._userId = None
def getCurrentValue(self, allVals=False):
if self._userId == None:
return None
... | e
pos = [round(locX, 3), round(locY, 3), round(locTheta, 3)]
if allVals:
return pos
elif self._locPart and self._locPart.lower() == 'x':
return pos[0]
elif self._locPart and self._locPart.lower() == 'y':
return pos[1]
... |
j-griffith/cinder | cinder/api/views/versions.py | Python | apache-2.0 | 2,771 | 0 | # Copyright 2010-2011 OpenStack Foundation
# Copyright 2015 Clinton Knight
# 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/li... | eturn ViewBuilder(base_url)
class ViewBuilder(object):
def __init__(self, base_url):
"""Initialize ViewBuilder.
:param base_url: url of the root wsgi application
"""
self.base_url = base_url
def build_versions(self, versions):
views = [self._build_version(versions[key... | view = copy.deepcopy(version)
view['links'] = self._build_links(version)
return view
def _build_links(self, version_data):
"""Generate a container of links that refer to the provided version."""
links = copy.deepcopy(version_data.get('links', {}))
version_num = versio... |
blu3f1r3/sMail-Checker | xml_parser.py | Python | gpl-3.0 | 2,892 | 0.008299 | #!/usr/bin/python
import xml.sax
import glob
from xml.etree import ElementTree
import os
debug = 0
currentPath = os.path.dirname(os.path.abspath(__file__))
def printl(st | ring):
if debug:
print "[xml_parser: | Debug] "+ str(string)
def main ():
p = getProviders()
print p[2].getIncomingServers()
def getProviderFromFilenames():
provs = []
printl("Current Path "+currentPath)
provs = os.listdir(currentPath+"/xml")
printl (provs)
return provs
class ProviderXMLHandler:
fullFilePath = None
... |
ezequielpereira/Time-Line | libs64/wx/py/shell.py | Python | gpl-3.0 | 57,165 | 0.005021 | """Shell is an interactive text control in which a user types in
commands to be sent to the interpreter. This particular shell is
based on wxPython's wxStyledTextCtrl.
Sponsored by Orbtech - Your source for Python programming expertise."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id: she... | :
"""Display some useful information about how to use the shell."""
self.write(self.helpText)
def __getattr__(self, name):
if hasattr(self.other, name):
| return getattr(self.other, name)
else:
raise AttributeError, name
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
self.__dict__[name] = value
elif hasattr(self.other, name):
setattr(self.other, name, value)
else:
... |
5StevenWu/Coursepy | L06/ATMFF/core/main.py | Python | apache-2.0 | 205 | 0.019512 | #!/usr/bin/env python |
# -*- coding:utf-8 -*-
#Author:xp
#blog_url: http://blog.csdn.net/wuxingpu5/article/details/7120 | 9731
def run():
print('from main run')
if __name__ == '__main__':
run() |
Nirvedh/CoarseCoherence | configs/tutorial/simple.py | Python | bsd-3-clause | 3,883 | 0.00309 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# 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, this list of con... | y bus, a coherent crossbar, in this cas | e
system.membus = SystemXBar()
# Hook the CPU ports up to the membus
for i in xrange(2):
system.cpu[i].icache_port = system.membus.slave
system.cpu[i].dcache_port = system.membus.slave
# create the interrupt controller for the CPU and connect to the membus
for i in xrange(2):
system.cpu[i].createInterrupt... |
ririw/libpgm | libpgm/dyndiscbayesiannetwork.py | Python | bsd-3-clause | 9,472 | 0.00549 | # Copyright (c) 2012, CyberPoint International, LLC
# 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, this lis... | TICULAR P | URPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL CYBERPOINT INTERNATIONAL, LLC BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED... |
marco-lancini/Showcase | app_auth/urls.py | Python | mit | 1,930 | 0.007254 | from django.conf.urls.defaults import *
from django.contrib.auth import views as auth_views
from app_auth.views import *
from app_auth.views import login as custom_login, logout as custom_logout
urlpatterns = patterns('',
# Home
url(r'^$', home, name="app_auth.home"),
# Login / logout
url(r'^login/... | end>[^/]+)/$', associate, name='app_auth.associate'),
#== | =======================================================================
# Registration links
(r'^accounts/', include('registration.urls')),
# Social login
(r'', include('social_auth.urls')),
# Default django login module
(r'', include('registration.auth_urls')),
)
# Password Reset
# url(r'^... |
ptroja/spark2014 | testsuite/gnatprove/tests/N804-036__bad_prover/test.py | Python | gpl-3.0 | 296 | 0 | from test_support import *
# this test c | alls a prover which is correctly configured but whose execution
# gives an error (here: the prover executable doesn't exist). The intent is to
# test the output of gnatprove in this specific case
prove_all(prover=["plop"], | opt=["--why3-conf=test.conf"])
|
cortesi/qtile | libqtile/widget/launchbar.py | Python | mit | 9,180 | 0.000545 | # Copyright (c) 2014 Tycho Andersen
# Copyright (c) 2014 dequis
# Copyright (c) 2014-2015 Joseph Razik
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2015 reus
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
... | dth / sp)
imgpat = cairocffi.SurfacePattern(img)
scaler = cairocffi.Matrix()
scaler.scale(sp, sp)
scaler.translate(self.padding * -1, -2)
imgpat.set_matrix(scaler)
imgpat.set_filter(cairocffi.FILTER_BEST) |
self.surfaces[img_name] = imgpat
self.icons_widths[img_name] = width
def _lookup_icon(self, name):
""" Search for the icon corresponding to one command. """
self.icons_files[name] = None
# if the software_name is directly an absolute path icon file
if os.pat... |
axinging/chromium-crosswalk | tools/android/loading/common_util_unittest.py | Python | bsd-3-clause | 2,005 | 0.004988 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import common_util
class SerializeAttributesTestCase(unittest.TestCase):
class Foo(object):
def __init__(self, foo_fighters, whisky_... | {'baz': 42}, foo_fighters, ['whisky_bar'])
self.assertDictEqual({'baz': 42, 'whisky_bar': 2}, json | _dict)
# Non-existing attribute.
with self.assertRaises(AttributeError):
json_dict = common_util.SerializeAttributesToJsonDict(
{}, foo_fighters, ['foo_fighters', 'whisky_bar', 'baz'])
def testDeserialization(self):
foo_fighters = self.Foo('hello', 'world')
json_dict = {'foo_fighters'... |
matrumz/RPi_Custom_Files | Printing/hplip-3.15.2/fax/fax.py | Python | gpl-2.0 | 32,217 | 0.004439 | # -*- coding: utf-8 -*-
#
# (c) Copyright 2010 Hewlett-Packard Development Company, L.P.
#
# 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) ... | ......#
# # Thumbnail data (if present) #
# #================================= | =============#
#
RESOLUTION_STD = 1
RESOLUTION_FINE = 2
RESOLUTION_300DPI = 3
FILE_HEADER_SIZE = 28
PAGE_HEADER_SIZE = 24
# **************************************************************************** #
##skip_dn = ["uid=foo,ou=People,dc=example,dc=com",
## "uid=bar,ou=People,dc=example,dc=com", "dc=example,dc=co... |
10sr/tbar | tbar/__init__.py | Python | unlicense | 557 | 0.001795 | #!/usr/bin/env python3
"""tba | r - Terminal Bar
Number to bar in terminal.
"""
__version__ = "0.1"
import sys
from tbar.tbar import TBar
from tbar.reader import Reader
def main(infile, comment, sep, field, regexp,
max, length, vertical):
infile = infile or sys.stdin
r = Reader(infile=infile, comment=comment, sep=sep, field=fiel... | xp=regexp)
b = TBar(_max=max, length=length, vertical=vertical)
b.add_data_itr(r.data)
s = str(b)
if s:
print(s)
else:
print("No data.")
return
|
UMONS-GFA/ardas | ardas/logger.py | Python | gpl-3.0 | 2,773 | 0.002524 | from threading import Thread, Event
from time import sleep
from ardas.sampler import W1Sampler
from ardas.sensor_tools import TempSensor, generate_w1temp_sensors
from ardas.samples_conditioners import generate_w1temp_sensor_samples_conditioners
from ardas.records_loggers import generate_w1temp_sensor_records_loggers
fr... | self.record_queue = record_queue
self.msg_logger = msg_logger
@property
def records_loggers(self):
""" Gets and sets channels loggers
"""
return | self.__records_loggers
@records_loggers.setter
def records_loggers(self, val):
self.__records_loggers = val
def run(self):
while not self.stop_event.isSet():
try:
record = self.record_queue.get(timeout=1.0)
if record is not None:
... |
sixninetynine/pex | pex/pex_bootstrapper.py | Python | apache-2.0 | 2,560 | 0.014453 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import sys
from .common import open_zip
__all__ = ('bootstrap_pex',)
def pex_info_name(entry_point):
"""Return the PEX-INFO for an entry_point"""
return os.path.join(entr... | rrent runtime environment using a given pex."""
from .environment import PEXEnvironment
from .finders | import register_finders
from .pex_info import PexInfo
register_finders()
PEXEnvironment(entry_point, PexInfo.from_pex(entry_point)).activate()
|
toni-heittola/js-datatable | minification.py | Python | mit | 4,998 | 0.003201 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JS and CSS minification
============================
Author: Toni Heittola (toni.heittola@gmail.com)
This plugin will create dynamic datatable with charting features from given yaml-datafile.
"""
import os
import sys
import io
import argparse
import textwrap
from IPy... | current_file_path, "r")
bundle_data += js_file.readlines()
js_file.close()
bundle_filename = os.path.join(target, 'datatable.bundle.min.js')
bundle_file = open(bundle_filename, 'w+')
bundle_file.write(''.join(bundle_data))
bundle_file.close()
... | t(e) |
Zlash65/erpnext | erpnext/demo/setup/education.py | Python | gpl-3.0 | 6,413 | 0.02916 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.utils.make_random import get_random
from datetime import datetime
from erpnext.demo.setup.setup_data import import_json
... | name').title())
if d.get('gender') == "Female":
female_names.append(d.get('first_name').title())
for idx, d in enumerate(random_student_data):
student_applicant = frappe.new_doc("Student Applicant")
student_applicant.first_name = d.get('first_name').title()
student_applicant.last_name = d.get('last_... | Program")
student_applicant.blood_group = random.choice(blood_group)
year = random.randint(1990, 1998)
month = random.randint(1, 12)
day = random.randint(1, 28)
student_applicant.date_of_birth = datetime(year, month, day)
student_applicant.mother_name = random.choice(female_names) + " " + d.get('last_... |
miltonlab/researchman | manager/models.py | Python | agpl-3.0 | 1,045 | 0.006705 | from django.db import models
# Create your models here.
class Career(models.Model):
name = models.CharField(max_length=80)
faculty = models.CharField(max_length=80)
def __str__(self):
return self.name
class AcademicTitle(models.Model):
LEVELS = (
('3', 'Tercer Nivel'),
('4E... | last_name = models.CharField(max_length=80)
work_email = models.EmailField()
personal_email = models.EmailField()
titles = models.ManyToManyField(AcademicTitle)
career = models.ForeignKey | (Career)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Researcher(models.Model):
teacher = models.OneToOneField(Teacher, primary_key=True)
def __str__(self):
return self.teacher
|
senden9/django-xmpp-server-test | xmpp_server_test/server_test/models.py | Python | gpl-3.0 | 7,152 | 0.002657 | # -*- coding: utf-8 -*-
#
# This file is part of django-xmpp-server-test
# (https://github.com/mathiasertl/django-xmpp-server-test).
#
# django-xmpp-server-test is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software Foundation, ei... | s.Model):
| server = models.ForeignKey(Server, related_name='tests')
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
finished = models.BooleanField(default=False)
data = JSONField(default={}, blank=True)
def get_absolute_url(self):
return reverse('server... |
francois-berder/PyLetMeCreate | letmecreate/core/uart.py | Python | bsd-3-clause | 2,730 | 0.000733 | #!/usr/bin/env python3
"""Python binding of UART wrapper of LetMeCreate library."""
import ctypes
_LIB = ctypes.CDLL('libletmecreate_core.so')
# Baudrates
UART_BD_1200 = 1200
UART_BD_2400 = 2400
UART_BD_4800 = 4800
UART_BD_9600 = 9600
UART_BD_19200 = 19200
UART_BD_38400 = 38400
UART_BD_57600 = 57600
def init():
... | ikrobus_index: must be 0 (MIKROBUS_1) or 1 (MIKROBUS_2)
Note: If the mikrobus index is invalid, then this function does not nothing.
"""
_LIB.uart_select_bus(mikrobus_index)
def get_current_bus():
"""Returns the current UART bus: 0 (MIKROBUS_1) or 1 (MIKROBUS_2)."""
return _LIB.uart_get_current_... | ):
""""Set the baudrate of the current UART bus.
baudrate: Must be one of the predefined baudrates.
Note: An exception is thrown, if it fails to set the baudrate.
"""
ret = _LIB.uart_set_baudrate(baudrate)
if ret < 0:
raise Exception("uart set baudrate failed")
def get_baudrate():
... |
zzz0072/Python_Exercises | 07_RSI/ch01/logic_gate.py | Python | bsd-2-clause | 4,604 | 0.005647 | #!/usr/bin/env python3
class LogicGate:
def __init__(self, label):
self.name = label
self.output = None
def getName(self):
return self.name
def getOutput(self):
self.output = self.calcLogicOutput()
return self.output
class BinaryGate(LogicGate):
def __init__(s... | == 1))
class XorGate(BinaryGate):
def __init__(self, label):
BinaryGate.__init__(self, label)
def calcLogicOutput(self):
pinA = self.getPinA( | )
pinB = self.getPinB()
return int(pinA != pinB)
class UnaryGate(LogicGate):
def __init__(self, label):
LogicGate.__init__(self, label)
self.pin = None
def getPin(self):
if self.pin == None:
UsrPin = input("Enter Pin value for " + self.name + ": ")
... |
babsey/nest-webapp | tryouts/django/nest_webapp/urls.py | Python | mit | 1,044 | 0.001916 | """nest_webapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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='home')
Class... | n import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf import settings
from django... | ture.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG is False: #if DEBUG is True it will be served automatically
urlpatterns += [url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT})]
|
timothycrosley/frosted | frosted/checker.py | Python | mit | 36,119 | 0.001993 | """frosted/checker.py.
The core functionality of frosted lives here. Implements the core checking capability models Bindings and Scopes
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 res... | )))
filledKwOnlySlots.update(range(len(self.kw_only_argument_names) - self.kw_only_default_count,
| len(self.kw_only_argument_names)))
if (len(filledSlots) < len(self.argument_names) and not call_node.starargs and not call_node.kwargs):
return reporter.report(m |
Reagankm/KnockKnock | venv/lib/python3.4/site-packages/numpy/core/tests/test_blasdot.py | Python | gpl-2.0 | 8,880 | 0.002815 | from __future__ import division, absolute_import, print_function
import sys
from itertools import product
import numpy as np
from numpy.core import zeros, float64
from numpy.testing import dec, TestCase, assert_almost_equal, assert_, \
assert_raises, assert_array_equal, assert_allclose, assert_equal
from numpy.c... | p.random.random_sample((1024, 16))
v = np.random.random_sample((16, 32))
r = np.empty((1024, 32))
for i in range(12):
np.dot(f, v, r)
assert_equal(sys.getrefcount(r), 2)
r2 = np.dot(f, v, out=None)
assert_array_equal(r2, r)
assert_(r is np.dot(f, v, out=r))
v = v[:, 0].copy() #... | .shape == (16,)
r = r[:, 0].copy() # r.shape == (1024,)
r2 = np.dot(f, v)
assert_(r is np.dot(f, v, r))
assert_array_equal(r2, r)
def test_dot_3args_errors():
np.random.seed(22)
f = np.random.random_sample((1024, 16))
v = np.random.random_sample((16, 32))
r = np.empty((1024, 31))
a... |
ahmeier/jhbuild | jhbuild/commands/snapshot.py | Python | gpl-2.0 | 2,259 | 0.002213 | # jhbuild - a tool to ease building collections of source packages
# Copyright (C) 2001-2004 James Henstridge
# Copyright (C) 2008 Andy Wingo
#
# snapshot.py: output a moduleset corresponding to the exact versions
# that are checked out
#
# This program is free software; you can redistribute it and/o... | if getattr(m, 'branch', None) and m.branch.tree_id()]
checked_out_repos = []
for mod in checked_out_mods:
if mod.branch.repository not in checked_out_repos:
checked_out_repos.append(mod.branch.repository)
x = ([sxml.mod | uleset]
+ [r.to_sxml() for r in checked_out_repos]
+ [m.to_sxml() for m in checked_out_mods]
+ [m.to_sxml() for m in meta])
print '<?xml version="1.0"?>\n'
print sxml_to_string(x)
register_command(cmd_snapshot)
|
Ghost-script/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/conglomerators/copr/copr.py | Python | lgpl-2.1 | 2,510 | 0 | import fedmsg.meta.base
from fedmsg_meta_fedora_infrastructure.fasshim import avatar_url
class AbstractCoprConglomerator(fedmsg.meta.base.BaseConglomerator):
def can_handle(self, msg, **config):
return '.copr.' in msg['topic']
def merge(self, constituents, **config):
ms = constituents # shor... | '{agents} kicked off {starts} {rebuild_predicate} ' + \
'of the {coprs} {copr_predicate}'
tmpl = self.produce_template(constituents, **config)
tmpl['subtitle'] = subtitle.format(
agents=agents, starts=starts, coprs=coprs,
copr_predicate=copr_predicate, rebuild_predic... | ault)
tmpl['link'] = self.get_link(constituents)
return tmpl
class ByCopr(AbstractCoprConglomerator):
def matches(self, a, b, **config):
a, b = a['msg'], b['msg']
if a['copr'] != b['copr']:
return False
return True
def get_secondary_icon(self, constituents... |
huggingface/transformers | src/transformers/models/vilt/feature_extraction_vilt.py | Python | apache-2.0 | 12,433 | 0.003459 | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. 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 r... | rue}>
NumPy arrays and PyTorch tensors are converted to PIL images | when resizing, so the most efficient is to pass
PIL images.
</Tip>
Args:
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[ |
nathanielvarona/airflow | airflow/sensors/sql_sensor.py | Python | apache-2.0 | 1,078 | 0.000928 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | apache.org/licenses/LICENSE-2.0
#
# Unless required by applic | able law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module is deprecated... |
hanase/synthpop | synthpop/synthesizer.py | Python | bsd-3-clause | 5,123 | 0 | import logging
import sys
from col | lections import namedtuple
import numpy as np
import pandas as pd
from scipy.stats import chisquare
from . import categorizer as cat
from . import draw
from .ipf.ipf import calculate_constraints
from .ipu.ipu import household_weights
logger = logging.getLogger("synthpop")
FitQuality = namedtuple(
'FitQuality',
... | ck_group'))
def enable_logging():
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
def synthesize(h_marg, p_marg, h_jd, p_jd, h_pums, p_pums,
marginal_zero_sub=.01, jd_zero_sub=.001, hh_index_start=0):
# this is the zero mar... |
huddler/pgbarman | tests/test_compressor.py | Python | gpl-3.0 | 6,125 | 0.002122 | # Copyright (C) 2013-2014 2ndQuadrant Italia (Devise.IT S.r.L.)
#
# This file is part of Barman.
#
# Barman 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... | def test_check_with_compression(self):
#prepare mock obj
config_mock = mock.Mock()
comp_manager = Compression | Manager(config_mock)
assert comp_manager.check('test_compression') is False
def test_get_compressor_custom(self):
#prepare mock obj
config_mock = mock.Mock()
config_mock.compression = "custom"
config_mock.custom_compression_filter = "test_custom_compression_filter"
c... |
mcbor/adventofcode | 2016/day19/day19-pt2.py | Python | mit | 400 | 0.0075 | #!/usr/bin/env python3
# Advent of Code 2016 - Day 19, Part One
i | mport sys
from math import log
def main(argv):
if len(argv) < 2:
elves = 3005290
else:
elves = int(argv[2])
t = 3**int(log(elves, 3))
if elves == t:
n = elves
else:
n = max(elves - t, 2*elves - 3*t)
print(n)
return 0
if __name__ == '__main__':
sys.ex | it(main(sys.argv)) |
kennedyshead/home-assistant | homeassistant/components/minecraft_server/sensor.py | Python | apache-2.0 | 5,431 | 0.000552 | """The Minecraft Server sensor platform."""
from __future__ import annotations
from typing import Any
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import TIME_MILLISECONDS
from homeassistant.core import HomeAssistant
from . imp... |
class MinecraftServerPlayersOnlineSensor(MinecraftServerSensorEntity):
"""Representation of a Minecraft Server online players sensor."""
def __init__(self, server: MinecraftServer) -> None:
"""Initialize online players sensor."""
super().__init__(
server=server,
type_... | ERS_ONLINE,
unit=UNIT_PLAYERS_ONLINE,
)
async def async_update(self) -> None:
"""Update online players state and device state attributes."""
self._state = self._server.players_online
extra_state_attributes = None
players_list = self._server.players_list
... |
veltri/DLV2 | tests/parser/aggregates.max.assignment.2.test.py | Python | apache-2.0 | 245 | 0 | input = """
r(W) :- W | = #max{X: a(X,Y)}, c(Y).
a(1,2).
a(3,2).
a(2,1).
a(5,1).
c(1) :- not c(2).
c(2) :- not c(1).
"""
output = """
r(W) :- W = #max{X: a(X,Y)}, c(Y).
a(1,2).
a(3,2).
a(2,1).
a(5,1).
c(1) : | - not c(2).
c(2) :- not c(1).
"""
|
scs/uclinux | user/python/python-2.4.4/Doc/tools/refcounts.py | Python | gpl-2.0 | 2,310 | 0 | """Support functions for loading the reference count data file."""
__version__ = '$Revision$'
import os
import sys
# Determine the expected location of the reference count file:
try:
p = os.path.dirname(__file__)
except NameError:
p = os.path.dirname(sys.argv[0])
p = os.path.normpath(os.path.join(os.getcwd()... | # blank lines and comments
continue
parts = line.split(":", 4)
if len(parts) != 5:
| raise ValueError("Not enough fields in %r" % line)
function, type, arg, refcount, comment = parts
if refcount == "null":
refcount = None
elif refcount:
refcount = int(refcount)
else:
refcount = None
#
# Get the entry, creating it if nee... |
zowper/ldstext | ldstext/wsgi.py | Python | gpl-2.0 | 389 | 0.002571 | """
WSGI config for ldstext project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this | file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ldstext.settings")
fro | m django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
xin3liang/platform_external_chromium_org | tools/binary_size/explain_binary_size_delta_unittest.py | Python | bsd-3-clause | 10,211 | 0.006757 | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Check that explain_binary_size_delta seems to work."""
import cStringIO
import sys
import unittest
import explain_binary_size_delt... | assert ('/file_all_changed', 't', 'changed', 1000, 2000) in changed
# File with one symbol, deleted.
assert ('/file_all_deleted', 't', 'removed', 1000, None) in removed
# New file with one symbol added
assert ('/file_new', 't', 'added', None, 1000) in added
# File with two symbols, one unchanged, o... | 00) in unchanged
assert ('/file_pair_unchanged_changed',
't', 'changed', 1000, 2000) in changed
# File with two symbols, one unchanged, one removed, same bucket
assert ('/file_pair_unchanged_removed',
't', 'unchanged', 1000, 1000) in unchanged
assert ('/file_pair_unchanged_remove... |
Boris1961/My-Projects | tst_csv_read.py | Python | mit | 208 | 0.009615 | import csv
with open('export.c | sv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamread | er:
# if row[0].find('laminat'):
print(row[0])
|
baibaichen/eagle | eagle-external/hadoop_jmx_collector/lib/kafka-python/kafka/client.py | Python | apache-2.0 | 18,107 | 0.001049 | import binascii
import collections
import copy
import functools
import itertools
import logging
import time
import kafka.common
from kafka.common import (TopicAndPartition, BrokerMetadata,
ConnectionError, FailedPayloadsError,
KafkaTimeoutError, KafkaUnavailableError... | ownTopicOrPartitionError,
NotLeaderForPartitionError, ReplicaNotAvailableError)
from kafka.conn import collect_hosts, KafkaConnection, DEFAULT_SOCKET_TIMEOUT_SECONDS
from kafka.protocol import KafkaProtocol
log = logging.getLogger("kafka")
class KafkaClient(object):
CLIENT_ID = b"kafk... | ould always be greater than the
# one passed to SimpleConsumer.get_message(), otherwise you can get a
# socket timeout.
def __init__(self, hosts, client_id=CLIENT_ID,
timeout=DEFAULT_SOCKET_TIMEOUT_SECONDS):
# We need one connection to bootstrap
self.client_id = client_id
... |
errikos/amtt | setup.py | Python | gpl-3.0 | 5,374 | 0 | """setuptools based packaging and installation module.
Defines the project properties, as well as a special command to build a
standalone executable, by using PyInstaller.
Run with --help to see available options.
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a co... | _description=long_description,
# The project's main homepage.
url='https://github.com/errikos/amtt',
# Author details
author='Ergys Dona',
author_email='ergys.dona@cern.ch',
# Choose your license
license='GPL-3.0',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
cla... | ject? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Manufacturing',
'Intended Audience :: Science/Research',
'Topic :: Scientific/... |
resolutedreamer/NESLDashboard | src/sam/sam_out/smap_out_parser_json.py | Python | mit | 2,605 | 0.01382 | """
Authors: Jeremy Haugen, UCLA, Anthony Nguyen, UCLA
Created: June 2015
Copyright notice in LICENSE file
This file is used to take the raw files generated by
the SAM, which are in CSV format and processes it into
json format. Then it will contact the sMAP server and
upload the json data into sMAP
"""
import uuid_... | print j
path = "/ManisHouse/" + row[1]
if path == "/ManisHouse/MainMeter":
path = "/ManisHouse/ShenitechMainMeter"
num_cols = (len(row) - 3)/3
#print num_cols
for i in range(num_cols):
channel = row[3*i + 3]
... | row[3*i + 4]
unit = row[3*i + 5]
full_path = path + "/" + channel
#uuid = uuid_gen.get_uuid(full_path)
timestamp = int(float(row[2])) * 1000
if full_path not in data:
data[full_path] = []
data[full_path].... |
croxis/kmr | config.py | Python | mit | 1,101 | 0 | __author__ = 'croxis'
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'stuff lumps pumps in pajamas'
CSRF_ENABLED = True
OPENID_PROVIDERS = [
{'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id'},
{'name... | ig(Config):
TESTING = True
MONGODB_SETTINGS = {'DB': 'kmr-test'}
class ProductionConfig(Config):
MONGODB_SETTINGS = {'DB': 'kmr'}
config = {
'dev | elopment': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
|
kenkov/smt | smt/langmodel/ngram.py | Python | mit | 551 | 0 | #! /usr/bin/env python
# coding:utf-8
from __future__ import division, print_function
imp | ort itertools
class NgramException(Exception):
pass
def ngram(sentences, n):
s_len = len(sentences)
if s_len < n:
raise NgramException("the sentences length is not enough:\
len(sentences)={} < n={}".format(s_len, n))
xs = itertools.tee(sentences, n)
for i, t ... | pass
|
adamtiger/NNSharp | PythonUtils/LSTM.py | Python | mit | 994 | 0.018109 | from keras.models import Sequential
from keras.layers import LSTM
import numpy as np
model = Sequential()
ly = LSTM(2, activation='tanh', recurrent_activation='relu',implementation = 1, stateful=False, batch_input_shape=(5, 3, 3))
model.add(ly)
model.compile(optimizer='sgd', loss='mse')
kernel = np.ones((3, 8))
rec_k... | el.predict(data, batch_size=5) # the batch_size has no impact on the result here
print(ou | tput)
print(model.summary())
print(model.get_config())
print(model.get_weights())
|
dnjohnstone/hyperspy | hyperspy/misc/eels/hartree_slater_gos.py | Python | gpl-3.0 | 6,912 | 0 | # -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... | ))
# Calculate the cross section at each energy position of the
# tabulated GOS
gamma = 1 + E0 / 511.06
T = 511060 | * (1 - 1 / gamma ** 2) / 2
for i in range(0, self.gos_array.shape[0]):
E = self.energy_axis[i] + energy_shift
# Calculate the limits of the q integral
qa0sqmin = (E ** 2) / (4 * R * T) + (E ** 3) / (
8 * gamma ** 3 * R * T ** 2)
p02 = T / (R * (1 -... |
Kunalpod/codewars | kooka-counter.py | Python | mit | 216 | 0.027778 | #Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Kooka-Count | er
#Problem level: 7 kyu
from itertools import groupby |
def kooka_counter(laughing):
return len([key for key,_ in groupby(laughing.split('a')[:-1])])
|
veltri/DLV2 | tests/parser/functions.5.test.py | Python | apache-2.0 | 271 | 0 | input = """
q("1","2","3").
q("3","te,s,t!","new").
q(1,2,"Work?").
p(f(f(X,Y),Z)) :- q(X,Y,Z).
r(X,Y,Z) :- p(f(f(X,Y),Z)).
"""
output = """
q("1","2","3").
q("3","te,s,t!","new").
q(1,2,"Work?").
p | (f(f(X,Y | ),Z)) :- q(X,Y,Z).
r(X,Y,Z) :- p(f(f(X,Y),Z)).
"""
|
jmeehan16/voter-demo | voter.py | Python | gpl-2.0 | 22,031 | 0.016386 | #!/usr/bin/python
import syslog
from flask import Flask, request, render_template, send_f | rom_directory, Response, jsonify
from flask.ext.bootstrap | import Bootstrap
import json
import re, os, sys
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
import time
app = Flask(__name__)
bootstrap = Bootstrap(app)
# Set deb... |
luispedro/pymorph | tests/test_patspec.py | Python | bsd-3-clause | 436 | 0.08945 | import pymorph
import numpy as np
def test_patspec():
f = np.array([
[0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,0,0],
[0,1,0,1,1,1,0,0],
[0,0,1,1,1,1,0,0],
[1,1,0,0,0,0,0,0]], bool)
assert pymorph.patspec(f).sum() == (f > 0).sum()
def test_linear_h():
| f = np.arange(9).reshape((3,3)) % 3 > 0
# This crashed in 0.95
# reported by Alexandre Harano
g = pymorph.pat | spec(f, 'linear-h')
|
MarcosCommunity/odoo | marcos_addons/demo/models.py | Python | agpl-3.0 | 147 | 0.006803 | # -*- co | ding: utf-8 -*-
from openerp import models, fields, api
# class demo(models.Model):
# _name = 'demo.demo'
# name = | fields.Char() |
adityacs/ansible | lib/ansible/modules/cloud/azure/azure_rm_virtualmachine.py | Python | gpl-3.0 | 60,330 | 0.004343 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# 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 Soft... | e value. For example, 'Standard_D4'. The list of choices varies depending on the
subscription and location. Check your subscription for available choices.
default: Standard_D1
required: false
admin_username:
description:
| - Admin username used to access the host after it is created. Required when creating a VM.
default: null
required: false
admin_password:
description:
- Password for the admin username. Not required if the os_type is Linux and SSH password authentication
is ... |
BigDataRepublic/bdr-analytics-py | setup.py | Python | apache-2.0 | 932 | 0 | from setuptools import setup
setup(
name='bdranalytics',
version='0.3',
license='Apache License 2.0',
author='bigdatarepublic',
author_email='info@bigdatarepublic.nl',
url='http://www.bigdatarepublic.nl',
long_description="README.md",
packages=['bdrana | lytics',
'bdranalytics.images',
'bdranalytics.keras',
'bdranalytics.pdlearn',
'bdranalytics.plot',
'bdranalytics.sklearn'],
include_package_data=True,
package_data={'bdranalytics': ['data/*.dat'],
'bdranalytics.images': ['bd... |
install_requires=[
"NumPy>=1.6.1",
"SciPy>=0.9",
"scikit-learn>=0.18",
"keras",
"pandas",
"matplotlib",
],
setup_requires=["pytest-runner"],
tests_require=["pytest"]
)
|
jakobkolb/MayaSim | tests/test_model.py | Python | gpl-3.0 | 217 | 0 | """
test script for the model itself.
Just checking whether it runs without
errors, no sanity check so far
"""
from mayasim.model.ModelCore i | mport ModelCore a | s M
m_instance = M()
assert m_instance.run_test(1) == 1
|
Azure/azure-sdk-for-python | sdk/servicebus/azure-mgmt-servicebus/azure/mgmt/servicebus/v2015_08_01/operations/_namespaces_operations.py | Python | mit | 52,182 | 0.005136 | # 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 may ... | "NamespacesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this op | eration group.
:type models: ~azure.mgmt.servicebus.v2015_08_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def ... |
bencorbett90/Graph | graph/imageitem.py | Python | gpl-2.0 | 22,662 | 0.000838 | from PyQt4 import QtGui
from utils import *
import pyqtgraph as pqg
import numpy as np
from colorButton import ColorButton
import traceitem
class ImageItem():
def __init__(self, imageTab):
self.imageTab = imageTab
self.sliceTable = None
self.name = None
self.sliceParams = {}
... | inue
if 1 < v < yIndex:
axisDict[k] += 1
data = | np.rollaxis(data, yIndex, 2)
cIndex = None
if axisDict['c'] is not None:
cIndex = 3
return data, {'t': 0, 'x': 1, 'y': 2, 'c': cIndex}
else:
xIndex = axisDict['x']
for k, v in axisDict.iteritems():
if v is None:
... |
AtelierSoude/shrooms | ShroomsAPI/profiles/signals.py | Python | gpl-3.0 | 947 | 0.003168 | #from actstream import action
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.core.exceptions import ObjectDoesNotExist
from django.dispatch import receiver
from profiles.models import Organisation, OrganisationGroup, UserProfile
UserModel = get_user_model()
... | oup(sender, instance, created, **kwargs):
"""
Create a new organisation group for the new Organisation
"""
if created:
OrganisationGroup.objects.create(organisation=ins | tance, name=instance.full_name)
|
littlecodersh/itchatmp | itchatmp/controllers/mpapi/qy/common.py | Python | mit | 286 | 0 | from requests import get
from | itchatmp.config import COMPANY_URL, COROUTINE
from itchatmp.returnvalues import ReturnValue
from itchatmp.utils import retry
from ..requests import requests
update_access_token = access_token = get_server_ip = \
filter_request = lamb | da x: x
|
fgmacedo/django-awards | awards/tasks.py | Python | mit | 337 | 0 | from celery.task import Task
from ..notifications.contextmanagers import BatchNotifications
class AsyncBadgeAward(Task):
ignore_result = True
def run(self, badge, state, **kwargs):
# from celery.contr | ib import rd | b; rdb.set_trace()
with BatchNotifications():
badge.actually_possibly_award(**state)
|
ampl/amplpy | setup.py | Python | bsd-3-clause | 5,545 | 0 | # -*- coding: utf-8 -*-
"""
AMPLPY
------
AMPL API is an interface that allows developers to access the features of the
AMPL interpreter from within a programming language. All model generation and
solver interaction is handled directly by AMPL, which leads to great stability
and speed; the library just acts as an int... | t fpath.startswith(LIBRARY_BASE)
]
library_only = [
fpath for fpath in all_files
if fpath.startswith(LIBRARY_DIR)
if fpath.endswith(LIBRARY_EXT)
]
lst = source_only + library_only
return [
fpath.replace('amplpy/', '', 1)
for fpath i... | nore_warnings = [
'-Wno-stringop-truncation',
'-Wno-catch-value',
'-Wno-unused-variable',
]
return ['-std=c++11'] + ignore_warnings
elif OSTYPE == 'Darwin':
ignore_warnings = [
'-Wno-unused-variable',
]
return ['-std=c++11', '-m... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/numpy/polynomial/tests/test_polynomial.py | Python | agpl-3.0 | 16,770 | 0.011866 | """Tests for polynomial module.
"""
from __future__ import division
import numpy as np
import numpy.polynomial.polynomial as poly
from numpy.testing import *
def trim(x) :
return poly.polytrim(x, tol=1e-6)
T0 = [ 1]
T1 = [ 0, 1]
T2 = [-1, 0, 2]
T3 = [ 0, -3, 0, 4]
T4 = [ 1, 0, -8, 0, 8]
T5 = [ 0... | or, poly.polydiv, [1], [0])
# check scalar division
quo, rem = poly.polydiv([2],[2])
assert_equal((quo, rem), (1, 0))
quo, rem = poly.polydiv([2,2],[2])
assert_equal((quo, rem), ((1 | ,1), 0))
# check rest.
for i in range(5) :
for j in range(5) :
msg = "At i=%d, j=%d" % (i,j)
ci = [0]*i + [1,2]
cj = [0]*j + [1,2]
tgt = poly.polyadd(ci, cj)
quo, rem = poly.polydiv(tgt, ci)
res ... |
akrherz/pyWWA | parsers/rr7.py | Python | mit | 128 | 0 | """Split RR7 products, for some reason!"""
# Local
from pywwa.workflo | ws.rr7 import main
if __name__ == "__main__":
| main()
|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/apport/REThread.py | Python | gpl-3.0 | 4,593 | 0.00283 | '''Enhanced Thread with support for return values and exception propagation.'''
# Copyright (C) 2007 Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.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 ... |
return x / y
class _T(unittest.TestCase):
def test_return_value(self):
| '''return value works properly.'''
t = REThread(target=div, args=(42, 2))
t.start()
t.join()
# exc_raise() should be a no-op on successful functions
t.exc_raise()
self.assertEqual(t.return_value(), 21)
self.assertEqual(t.ex... |
mlperf/training_results_v0.7 | Google/benchmarks/bert/implementations/bert-cloud-TF2.0-tpu-v3-32/modeling/networks/__init__.py | Python | apache-2.0 | 1,212 | 0.002475 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | f2_bert.modeling.networks.masked_lm import MaskedLM
from REDACTED.tf2_bert.modeling.netw | orks.span_labeling import SpanLabeling
from REDACTED.tf2_bert.modeling.networks.transformer_encoder import TransformerEncoder
|
particl/particl-core | test/functional/feature_includeconf.py | Python | mit | 4,378 | 0.004797 | #!/usr/bin/env python3
# Copyright (c) 2018-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Tests the includeconf argument
Verify that:
1. adding includeconf to the configuration file causes th... | n(os.path.join(self.options.tmpdir, "node0", "relative.conf"), "a", encoding="utf8") as f:
f.write("includeconf=relative2.conf\n")
self.start_node(0)
subversion = self.nodes[0].getnetworkinfo()["subversion"]
assert subversion.endswith("main; | relative)/")
self.stop_node(0, expected_stderr="warning: -includeconf cannot be used from included files; ignoring -includeconf=relative2.conf")
self.log.info("-includeconf cannot contain invalid arg")
# Commented out as long as we ignore invalid arguments in configuration files
#with... |
LLNL/spack | var/spack/repos/builtin/packages/r-illuminahumanmethylation450kanno-ilmn12-hg19/package.py | Python | lgpl-2.1 | 982 | 0.004073 | # 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 RIlluminahumanmethylation450kannoIlmn12Hg19(RPackage):
"" | "Annotation for Illumina's 450k methylation arrays
Manifests and annotation for Illumina's 450k array data."""
# This package is available via bioconductor but there is no available git
# repository.
homepage = "https://bioconductor.org/packages/release/data/ann | otation/html/IlluminaHumanMethylation450kanno.ilmn12.hg19.html"
url = "https://bioconductor.org/packages/release/data/annotation/src/contrib/IlluminaHumanMethylation450kanno.ilmn12.hg19_0.6.0.tar.gz"
version('0.6.0', sha256='249b8fd62add3c95b5047b597cff0868d26a98862a47cebd656edcd175a73b15')
depends_o... |
thesgc/cbh_chembl_id_generator | setup.py | Python | bsd-3-clause | 1,618 | 0.000618 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
impo | rt cbh_chembl_id_generator
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = cbh_chembl_id_generator.__version__
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
print("You probably want to also tag the version now:")
print(" ... | rsion %s'" % (version, version))
print(" git push --tags")
sys.exit()
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='cbh_chembl_id_generator',
version=version,
description="""Unique Identifier Generator for compounds in the Chemb... |
dmlc/xgboost | tests/python-gpu/test_gpu_demos.py | Python | apache-2.0 | 1,044 | 0.000958 | import os
import subprocess
import sys
import pytest
sys.path.append("tests/python")
import testing as tm
import test_demos as td # noqa
@pytest.mark.skipif(**tm.no_cupy())
def test_data_iterator():
script = os.path.join(td.PYTHON_DEMO_DIR, 'quantile_data_iterator.py')
cmd = ['python', script]
sub... | y())
@pytest.mark.mgp | u
def test_dask_training():
script = os.path.join(tm.PROJECT_ROOT, 'demo', 'dask', 'gpu_training.py')
cmd = ['python', script, '--ddqdm=1']
subprocess.check_call(cmd)
cmd = ['python', script, '--ddqdm=0']
subprocess.check_call(cmd)
|
dparaujo/projeto | app_administrativo/candidato/migrations/0001_initial.py | Python | gpl-3.0 | 1,043 | 0.004794 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-31 01:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TblAdm... | ions={
'ordering': ['codigo'],
| 'db_table': 'tbl_administrativo_candidato',
},
),
]
|
sridevikoushik31/nova | nova/scheduler/rpcapi.py | Python | apache-2.0 | 4,921 | 0.004877 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, 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
#
... | nt to run_instance()
1.7 - Add create_volume() method, remove topic from live_migration()
2.0 - Remove 1.x backwards compat
2.1 - Add image_id to create_volume()
2.2 - Remove reservations argument to create_volume()
2.3 - Remove create_volume()
2.4 - Change update_servic... | Add select_hosts()
'''
#
# NOTE(russellb): This is the default minimum version that the server
# (manager) side must implement unless otherwise specified using a version
# argument to self.call()/cast()/etc. here. It should be left as X.0 where
# X is the current major API version (1.0, 2.0, .... |
openslack/openslack-web | openslack/openslack/views.py | Python | apache-2.0 | 355 | 0.002817 | # coding=utf-8
import time
from django.core.cache import cache
from django.conf import set | tings
from django.shortcuts import render_to_response, RequestContext
from dateutil.parser import parse as parse_date
from silk.profiling.profiler import silk_profile
def index(request):
return render_to_response('index.html', {}, RequestContex | t(request))
|
chudichudichudi/neuro-tedx-2 | migrations/versions/46c97aa9285d_.py | Python | bsd-3-clause | 1,843 | 0.015735 | """empty message
Revision ID: 46c97aa9285d
Revises: None
Create Date: 2015-01-20 10:34:38.095562
"""
# revision identifiers, used by Alembic.
revision = '46c97aa9285d'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... | a.String(length=80), nullable | =False),
sa.Column('password', sa.String(length=128), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('first_name', sa.String(length=30), nullable=True),
sa.Column('last_name', sa.String(length=30), nullable=True),
sa.Column('active', sa.Boolean(), nullable=True),
... |
pombredanne/pyjs | pyjswidgets/pyjamas/locale.py | Python | apache-2.0 | 685 | 0.004425 | # encoding: utf-8
"""
(C) 2012 by Maho (?ukasz Mach)
License: GPL
Poor man's i18n support for Pyjamas.
_("identifier") returns you translated version of "identifier". If you want
original (English) version, just do nothing. If you want other language
(eg. PL), please | import translation_pl in your project, when it's content
is:
from pyjamas.locale import msgs
msgs["Week"] = "Tydzień"
msgs["Jan"] = "Sty"
msgs["January"] = "Styczeń"
msgs["Other eng identifier you'd like to translate"] = "Inny ang. identyfikator który chciałbyś przetłumaczyć"
"""
msgs = {}
... | dentifier):
return msgs.get(identifier,identifier)
|
AshishBora/csgm | src/mnist_model_def.py | Python | mit | 867 | 0.00346 | """Model definitions for MNIST"""
# pylint: disable = C0301, C0103, R0914, C0111
import os
im | port sys
import tensorflow as tf
sys.path.append(os. | path.join(os.path.dirname(__file__), '..'))
from mnist_vae.src import model_def as mnist_vae_model_def
from mnist_e2e.model_def import end_to_end
def construct_gen(hparams, model_def):
model_hparams = model_def.Hparams()
z = model_def.get_z_var(model_hparams, hparams.batch_size)
_, x_hat = model_def.gen... |
Shopify/shopify_python_api | test/application_credit_test.py | Python | mit | 1,374 | 0.002911 | import shopify
import json
from test.test_helper import TestCase
class ApplicationCreditTest(TestCase):
def test_get_application_credit(self):
self.fake("application_credits/445365009", method="GET", body=self.load_fixture("applica | tion_credit"), code=200)
application_credit = shopify.ApplicationCredit.find(445365009)
self.assertEqual("5.00", applica | tion_credit.amount)
def test_get_all_application_credits(self):
self.fake("application_credits", method="GET", body=self.load_fixture("application_credits"), code=200)
application_credits = shopify.ApplicationCredit.find()
self.assertEqual(1, len(application_credits))
self.assertEqu... |
drewja/flask | tests/test_apps/cliapp/inner1/__init__.py | Python | bsd-3-clause | 55 | 0 | from | flask import Flask
application = | Flask(__name__)
|
MITLibraries/ebooks | ebooks/config.py | Python | mit | 905 | 0 | import os
class Config():
DEBUG = os.getenv('FLASK_DEBUG', default=False)
ENV = os.getenv('FLASK_ENV', default='production')
SECRET_KEY = os.getenv('SECRET_KEY')
ALMA_API_KEY = os.getenv('ALMA_API_KEY')
ALMA_API_URL = os.gete | nv('ALMA_API_URL')
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_BUCKET_NAME = o | s.getenv('AWS_BUCKET_NAME')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_REGION_NAME = os.getenv('AWS_REGION_NAME')
class DevelopmentConfig(Config):
DEBUG = True
ENV = 'development'
SECRET_KEY = 'devsecrets'
class TestingConfig(Config):
TESTING = True
SECRET_KEY = 'test... |
spaghetti-open-data/ODFest2017-horizon2020-network | H2020_Code_2017/delKCoreSubGraphs.py | Python | mit | 4,608 | 0.015408 | # Powered by Python 2.7
# To cancel the modifications performed by the script
# on the current graph, click on the undo button.
# Some useful keyboards shortcuts :
# * Ctrl + D : comment selected lines.
# * Ctrl + Shift + D : uncomment selected lines.
# * Ctrl + I : indent selected lines.
# * Ctrl + Shift +... | etDoubleProperty("viewRotation")
viewSelection = graph.getBooleanProperty("viewSelection")
viewShape = graph.getIntegerProperty("viewShape")
viewSize = graph.getSizeProperty("viewSize")
viewSrcAnchorShape = graph.getIntegerProperty("viewSrcAnchorShape")
viewSrcAnchorSize = graph.getSizeProperty("viewSrcAnchor... | Shape")
viewTgtAnchorSize = graph.getSizeProperty("viewTgtAnchorSize")
wBarPower = graph.getDoubleProperty("wBarPower")
weightedBarPower = graph.getDoubleProperty("weightedBarPower")
for sg in graph.getSubGraphs():
gName = sg.getName()
if gName[:1] == 'K':
success = graph.delSubGraph(sg)
|
freakboy3742/django | django/test/runner.py | Python | bsd-3-clause | 32,557 | 0.000584 | import ctypes
import faulthandler
import io
import itertools
import logging
import multiprocessing
import os
import pickle
import sys
import textwrap
import unittest
from contextlib import contextmanager
from importlib import import_module
from io import StringIO
from django.core.management import call_command
from dj... | ().stopTest(test)
self.logger.removeHandler(self.handler)
if self.showAll:
self.debug_sql_stream.seek(0)
self.stream.write(self.debug_sql_stream.read())
self.stream.writeln(self.separator2)
def addError(self, test, err):
super().addError(test, err)
... | tream is None:
# Error before tests e.g. in setUpTestData().
sql = ''
else:
self.debug_sql_stream.seek(0)
sql = self.debug_sql_stream.read()
self.errors[-1] = self.errors[-1] + (sql,)
def addFailure(self, test, err):
super().addFailure(test, e... |
drammock/mne-python | mne/viz/_brain/_brain.py | Python | bsd-3-clause | 151,930 | 0 | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Oleh Kozynets <ok7mailbox@gmail.com>
# Guillaume Favelier <guillaume.favelier@gmail.com>
# jona-sassenhagen <jona.sassenhagen@gmail.com>
# Joan Massich <mailsik@gmail.com>
#... | t _get_cmap
from matplotlib.colors import Colormap, ListedColormap
if isinstance(self._colormap, str):
cmap = _get_cmap(self._colormap) |
elif isinstance(self._colormap, Colormap):
cmap = self._colormap
else:
cmap = ListedColormap(
self._colormap / 255., name=str(type(self._colormap)))
logger.debug(
f'Color mapping {repr(self._name)} with {cmap.name} '
f'colormap and... |
ScaleXY/speedby | speedby/vehicle/migrations/0002_auto_20160414_1246.py | Python | gpl-2.0 | 844 | 0.001185 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-04-14 12:4 | 6
from __future__ import unicode_literals
from django.db impor | t migrations, models
class Migration(migrations.Migration):
dependencies = [
('vehicle', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='vehicle',
old_name='scannedrecord_1',
new_name='registration_plate_1',
),
mig... |
DreamSourceLab/DSView | libsigrokdecode4DSL/decoders/ade77xx/pd.py | Python | gpl-3.0 | 4,779 | 0.005022 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2017 Karl Palsson <karlp@etactica.com>
##
## Permiss | ion 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, distribute, sublicense, and/or sell
## copies of... | he following conditions:
##
## The above copyright notice and this permission notice shall be included in all
## copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
##... |
hammerlab/cohorts | test/test_count.py | Python | apache-2.0 | 9,382 | 0.002558 | # Copyright (c) 2016. Mount Sinai School of Medicine
#
# 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 o... | ariants(filterable_variant):
return filterable_variant.variant.ref == 'G'
g_variants = {'1': 2, '4': 1, '5': 3}
cohort_variants = cohort.load_variants(filter_fn=filter_g_variants)
| for (sample, variants) in cohort_variants.items():
eq_(len(variants), g_variants[sample])
finally:
if vcf_dir is not None and path.exists(vcf_dir):
rmtree(vcf_dir)
if cohort is not None:
cohort.clear_caches()
def test_filter_effects():
vcf_dir, cohort = ... |
tylertian/Openstack | openstack F/keystone/keystone/identity/backends/ldap/core.py | Python | apache-2.0 | 34,443 | 0.000116 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | lf, tenant_id, user_id):
self.get_tenant(tenant_id)
self.get_u | ser(user_id)
return self.tenant.add_user(tenant_id, user_id)
def get_tenants_for_user(self, user_id):
self.get_user(user_id)
tenant_list = []
for tenant in self.tenant.get_user_tenants(user_id):
tenant_list.append(tenant['id'])
return tenant_list
def get_ten... |
melinath/django-ticketeer | ticketeer/backends/dummy.py | Python | bsd-2-clause | 426 | 0.049296 | from ticketeer.backends.base import BaseBackend
class Ticket(object):
"""
A ticket mock
"""
def | __init__(self, id=1, name="Ticket Name", description="Ticket Description" | ):
self.id = id
self.name = name
self.description = description
class DummyBackend(BaseBackend):
"""
Dummy backend
"""
def get_ticket(self, request):
return Ticket()
def get_ticket_list(self, request):
return [Ticket(1),Ticket(2)]
|
bdestombe/flopy-1 | examples/scripts/flopy_swi2_ex5.py | Python | bsd-3-clause | 15,804 | 0.000063 | from __future__ import print_function
import os
import sys
import math
import collections
import numpy as np
import flopy
import matplotlib.pyplot as plt
# --modify default matplotlib settings
updates = {'font.family': ['Univers 57 Condensed', 'Arial'],
'mathtext.default': 'regular',
'pdf.com... | owWel(ml, stress_period_data=well_data)
swi = flopy.modflow.ModflowSwi2(ml, iswizt=55, npln=1, istrat=1,
toeslope=0.025, tipslope=0.025,
nu=[0, 0.025], zeta=z, ssz=ssz,
isource=isource, nsolver=2,
... | 2params=solver2params)
oc = flopy.modflow.ModflowOc(ml, stress_period_data=ocspd)
pcg = flopy.modflow.ModflowPcg(ml, hclose=1.0e-6, rclose=3.0e-3,
mxiter=100, iter1=50)
# --write the modflow files
ml.write_input()
m = ml.run_model(silent=False)
# --read model zeta... |
lantra/vugamedev | src/combat.py | Python | mit | 5,778 | 0.011769 | import rogueutil as rutil
import libtcodpy as libtcod
def roll_to_hit(attacker, defender, messagefunction, player_actor):
roll = rutil.roll(100)
atck_bonus = fatigue_bonus(defender.fighter.fatigue, defender.fighter.max_fatigue)
defender_bonus = fatigue_bonus(attacker.fatigue, attacker.max_fatigue)
... | if roll == 100: #if the roll is 100, the attacker scores a devastating critical
devastating_crit(attacker, defender, messagefunction)
player_actor.modify_rating(10)
return 'hit'
elif roll >= 96 - a | ttacker.stance_recklessness: #if the roll is > or = 96, the attacker scores a regular critical
critical_hit(attacker, defender, messagefunction)
player_actor.modify_rating(5)
return 'hit'
elif roll <= 1 + attacker.stance_recklessness:
messagefunction(attacker.owner.name + ' misses ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.