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 |
|---|---|---|---|---|---|---|---|---|
moreati/django-userena | userena/tests/test_backends.py | Python | bsd-3-clause | 2,608 | 0.001917 | from django.test import TestCase
from django.contrib.auth import authenticate
from userena.backends import UserenaAuthenticationBackend
from userena.utils import get_user_model
User = get_user_model()
class UserenaAuthenticationBackendTests(TestCase):
"""
Test the ``UserenaAuthenticationBackend`` which shou... | fication='john@example.com',
password='blowfish')
self.failUnless(isinstance(result, User))
def test_get_user(self):
""" Test that the user is returned """
user = self.backend.get_user(1)
self.failUnlessEqual(user.username, 'john')
|
# None should be returned when false id.
user = self.backend.get_user(99)
self.failIf(user)
|
Gussy/mavlink | pymavlink/generator/lib/genxmlif/__init__.py | Python | lgpl-3.0 | 3,040 | 0.003618 | #
# genxmlif, Release 0.9.0
# file: __init__.py
#
# genxmlif package file
#
# history:
# 2005-04-25 rl created
#
# Copyright (c) 2005-2008 by Roland Leuthe. All rights reserved.
#
# --------------------------------------------------------------------
# The generic XML interface is
#
# Copyright (c) 200... | m
return xmlifMinidom.XmlInterfaceMinidom(verbose, useCaching, processXInclude)
elif xmlIf == XMLIF_4DOM:
import xmlif4Dom
return xmlif4Dom.XmlInterface4Dom(verbose, useCaching, processXInclude)
elif xmlIf == XMLIF_ELEMENTTREE:
import xmlifElementTree
return xm... | ee.XmlInterfaceElementTree(verbose, useCaching, processXInclude)
else:
raise AttributeError, "Unknown XML interface: %s" %(xmlIf)
########################################
# define own exception for GenXmlIf errors
# The following errors/exceptions are mapped to a GenxmlIf exception:
# - Expat er... |
albfan/terminator | setup.py | Python | gpl-2.0 | 9,520 | 0.013655 | #!/usr/bin/env python2
from distutils.core import setup
from distutils.dist import Distribution
from distutils.cmd import Command
from distutils.command.install_data import install_data
from distutils.command.build import build
from distutils.dep_util import newer
from distutils.log import warn, info, error
from distu... | h.join(css_dir, 'gtk-3.0', 'apps', '*.css'))
dest = os.path.join('share', 'terminator', css_dir, 'gtk-3.0', 'apps')
data_files.append((dest, srce))
return data_files
class Test(Command):
user_options = []
def initialize_options(self):
pass
def final | ize_options(self):
pass
def run(self):
import subprocess
import sys
errno = subprocess.call(['bash', 'run_tests'])
raise SystemExit(errno)
if platform.system() in ['FreeBSD', 'OpenBSD']:
man_dir = 'man'
else:
man_dir = 'share/man'
setup(name=APP_NAME,
version=APP_VERSION,
descr... |
abhikeshav/ydk-py | core/ydk/mdt/proto_to_dict.py | Python | apache-2.0 | 2,788 | 0.001793 | # ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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 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.
# -------------------------------------------------------------... |
kaimast/inanutshell | linear/common/launch.py | Python | bsd-2-clause | 842 | 0.008314 | import subprocess
import math
def launch(script_name, num_partitions, num_machines, pos, coordinator, machine_name, debug=False):
i | f num_machines > num_partitions:
raise RuntimeError("Need more partitions than machine")
machine_size = int(math.ceil(float(num_partitions) / float(num_machines)))
start = pos * machine_size
end = min((pos+1)*machine_size, num_partitions)
processes = []
#launch content server processes
... | (i))
if debug:
p = subprocess.Popen(["python3-dbg", script_name, coordinator, machine_name, str(i)])
else:
p = subprocess.Popen([script_name, coordinator, machine_name, str(i)])
processes.append(p)
while processes:
p = processes.pop()
p.wait()
|
jaustinpage/frc_rekt | docs/conf.py | Python | mit | 5,302 | 0.000943 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# frc_rekt documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 12 00:19:47 2017.
#
# 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
# a... | st of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'frc_rekt.tex', 'frc\\_rekt Documentation',
'Author', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manu... | ples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'frc_rekt', 'frc_rekt Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start ... |
frreiss/tensorflow-fred | tensorflow/lite/python/metrics_nonportable_test.py | Python | apache-2.0 | 24,385 | 0.004757 | # Lint as: python2, python3
# Copyright 2021 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
#
... | [None, 16, 16, 3], dtype=dtypes.float32, name='in_tensor')
math_ops.add(in_tensor, in_tensor, name='add')
sess = session.Session()
return (
convert_to_constants.convert_variables_to_constants_from_session_graph(
sess, sess.graph_def, ['add']))
def test_conversion_from_constructor... | nverter(frozen_graph_def, None, None,
[('in_tensor', [2, 16, 16, 3])], ['add'])
mock_metrics = mock.create_autospec(
metrics.TFLiteConverterMetrics, instance=True)
converter._tflite_metrics = mock_metrics
tflite_model = converter.convert()
self.assertIsNotNon... |
meidli/yabgp | yabgp/message/attribute/linkstate/__init__.py | Python | apache-2.0 | 3,042 | 0 | # Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | .isisarea import ISISArea # noqa
from .node.sr_capabilities import SRCapabilities # noqa
from .node.sr_algorithm import SRAlgorithm # noqa
from .node.node_msd import NodeMSD # noqa
from .node.nodeflags import NodeFlags # noqa
from .node.opa_node_attr import OpaNodeAttr # noqa
from .node.sid_or_label import SIDor... | ingroup import AdminGroup # noqa
from .link.remote_router_id import RemoteRouterID # noqa
from .link.max_bw import MaxBandwidth # noqa
from .link.max_rsv_bw import MaxResvBandwidth # noqa
from .link.unsrv_bw import UnrsvBandwidth # noqa
from .link.te_metric import TeMetric # noqa
from .link.link_name impor... |
MIPS/external-chromium_org-tools-gyp | pylib/gyp/xcode_emulation.py | Python | bsd-3-clause | 44,910 | 0.007459 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This module contains classes that help to emulate xcodebuild behavior on top of
other build systems, such as make and ninja.
"""
import gyp.common
import os.p... | or self.isIOS:
path = self.GetBundleContentsFolderPath()
elif self.spec['type'] in ('executable', 'loadable_module'):
path = os.path.join(self.GetBundleContentsFolderPath(), 'MacOS')
return os.path.join(path, self.GetExecutableName())
def _GetStandaloneExecutableSuffix(self):
if 'product_exte... | n' in self.spec:
return '.' + self.spec['product_extension']
return {
'executable': '',
'static_library': '.a',
'shared_library': '.dylib',
'loadable_module': '.so',
}[self.spec['type']]
def _GetStandaloneExecutablePrefix(self):
return self.spec.get('product_prefix', {
... |
aerialhedgehog/VyPy | trunk/VyPy/tools/wait.py | Python | bsd-3-clause | 1,311 | 0.039664 |
import time
from random import random
import traceback
WARN_TIME = 3600.
def wait(check,timeout=None,delay=0.5, *args,**kwarg):
start_time = time.time()
warned = False
while True:
try:
result = check(*args,**kwarg)
break
except Exception as exc:... |
#if self.timeout and (time.time()-self._start_time) > self.timeout:
#raise StopIteration
#time.sleep(self.interval)
#try:
#return True
#exce | pt:
#print 'caught'
#for now in wait(timeout=None):
#print 'hello!'
|
maurizi/otm-core | opentreemap/treemap/views/user.py | Python | agpl-3.0 | 9,600 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import collections
from registration.models import RegistrationProfile
from django.conf import settings
from django.contrib.sites.requests import RequestSite
from django.core.exceptio... | l}
def resend_activation_ema | il_page(request):
return {'username': request.GET.get('username')}
def resend_activation_email(request):
username = request.POST['username']
def error(error):
return render(request, 'treemap/resend_activation_email.html',
{'username': username, 'error': error})
if not u... |
maroy/TSTA | cse-581-project-2/src/extract_keywords.py | Python | mit | 1,499 | 0.002668 | import re
import json
import sqlite3
import nltk
stop = nltk.corpus.stopwords.words("english")
stop.append('rt')
contractions = []
with open('contractions.txt', 'rb') as f:
contractions = [c.strip() for c in f.readlines()]
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
tokenizer = nltk.tokenize.... | ex = re.compile(r"http[s]?[^\s]*")
contractions_regex = re.compile("|".join(contractions))
first_tweet = None
con = sqlite3.connect("D:/TWEETS/2014-11-05-22-45-54.db")
c = con.cursor()
with open("out.csv", "wb") as out_file:
for row in c.execute("SELECT tweet FROM tweets"):
if first_tweet is No... | ']
text = text.lower()
text = url_regex.sub('', text)
text = contractions_regex.sub('', text)
all_tokens = tokenizer.tokenize(text)
tokens = []
for token in all_tokens:
token = lemmatizer.lemmatize(token)
if token not in stop:
... |
bmya/odoo-support | adhoc_modules_server/octohub/exceptions.py | Python | lgpl-3.0 | 701 | 0.002853 | # Copyright (c) 2013 Alo | n Swartz <alon@turnkeylinux.org>
#
# This file is part of OctoHub.
#
# OctoHub 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.
import ... | r response
"""
def __init__(self, error):
Exception.__init__(self, error)
self.error = error
def __str__(self):
return json.dumps(self.error, indent=1)
class OctoHubError(Exception):
pass
|
forestdussault/olc_webportalv2 | olc_webportalv2/new_multisample/models.py | Python | mit | 8,667 | 0.000923 | from django.db import models
from olc_webportalv2.users.models import User
from django.contrib.postgres.fields.jsonb import JSONField
import os
from django.core.exceptions import ValidationError
# Create your models here.
def validate_fastq(fieldfile):
filename = os.path.basename(fieldfile.name)
if filename.... | rn float(self.uida.split('%')[0])
def vt1_number(self):
return float(self.vt1.split('%')[0])
def vt2_number(self):
return float(self.vt2.split('%')[0])
def vt2f_number(self):
return float(self.vt2f. | split('%')[0])
def eae_number(self):
return float(self.eae.split('%')[0])
def eae_1_number(self):
return float(self.eae_1.split('%')[0])
def hlya_number(self):
return float(self.hlya.split('%')[0])
def igs_number(self):
return float(self.igs.split('%')[0])
def in... |
ros2/launch | launch_testing/test/launch_testing/test_flake8.py | Python | apache-2.0 | 830 | 0 | # Copyright 2016 Open Source Robotics Foundation, 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... | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_flake8.main import main_with_errors
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d | code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
|
marmorkuchen/jw2html | setup.py | Python | gpl-3.0 | 1,182 | 0.002538 | import os
from setuptools import setup, find_packages
from jw2html import VERSION
setup(
name='JW2HTML',
version=VERSION,
description='JW2HTML converts an issue of the Jungle World from the website to a single HTML file to be used for epub conversion by e.g. calibre.',
long_description='Alas, there is... | etc'), ['jw2html.ini',]),
],
entry_points={
'console_scripts': [
| 'jw2html = jw2html:main',
]
},
install_requires=[
'beautifulsoup4',
],
)
|
GTACSolutions/python-braspag | python_braspag/decorators.py | Python | apache-2.0 | 849 | 0.001178 | # coding: utf8
from functools import wraps
from logging import getLogger
logger = getLogger(__name__)
__author__ = 'marcos.costa'
class request_logger(object):
def __init__(self, method=None):
self.method = method
def __call__(self, func):
method = self.method
if method is None:
... | request=request,
| response=response)
logger.info(msg)
return response
return wrapper |
JunctionAt/JunctionWWW | blueprints/base.py | Python | agpl-3.0 | 504 | 0.001984 | from werkzeug.local import LocalProxy
from . import extension_access
def extension_access_proxy(name):
return LocalProxy(lambda: getattr(extension_access, name, None))
# Mostly for backwards compati | bility
cache = extension_access_proxy("cache")
mongo = extension_access_proxy("mongo")
mail = extension_access_proxy("mail")
admin = extension_access_proxy("admin")
rest_api = extension_access_proxy("rest_api")
markdow | n = extension_access_proxy("markdown")
assets = extension_access_proxy("assets")
|
alex-zoltowski/SSBM-AI | AI/Characters/character.py | Python | gpl-3.0 | 5,818 | 0.004641 | import AI.pad
import AI.state
class Character:
def __init__(self, pad_path):
self.action_list = []
self.last_action = 0
self.pad = AI.pad.Pad(pad_path)
self.state = AI.state.State()
#Set False to enable character selection
self.test_mode = True
self.sm = AI.... | turn self.state.players[0].action_state is test_state
#executes button presses defined in action_list, runs logic() once list is empty
def advance(self):
while self.action_list:
wait, func, args = self.action_list[0]
if self.state.frame - self.last_action < wait:
... | if func is not None:
func(*args)
self.last_action = self.state.frame
else:
self.logic()
'''Methods simulate controller input; appends necessary tuple to action_list'''
def press_button(self, wait, button):
self.action_list.append((wait, sel... |
JoshuaEbenezer/SNLP-reviews | SNLP/src/read_file.py | Python | gpl-3.0 | 795 | 0.023899 | import sys
folder_loc = sys.argv[1]
filename =sys.argv[2]
fileobj = open(folder_loc + filename);
flag=0
real_rev = open(folder_loc + "real_"+filename,"w+")
fake_rev = open(folder_loc + "fake_"+filename,"w+")
for line in fileobj:
for i in range(len(line)):
if (line[i] == '[' and flag == 0): #fo... | ']' and flag == 1): #for end of real reviews
flag = 2
elif (line[i]=='[' and flag == 2): #for beginning of fake reviews
flag = 3
elif (line[i-1] == | ']' and flag == 3): #for end of fake reviews
flag = 4
if(flag ==1):
real_rev.write(line[i])
elif(flag==3):
fake_rev.write(line[i])
|
bluemini/kuma | vendor/packages/translate/filters/test_decoration.py | Python | mpl-2.0 | 3,921 | 0.004108 | # -*- coding: utf-8 -*-
"""tests decoration handling functions that are used by checks"""
from translate.filters import decoration
def test_spacestart():
"""test operation of spacestart()"""
assert decoration.spacestart(" Start") == " "
assert decoration.spacestart(u"\u0020\u00a0Start") == u"\u0020\u0... | riable sans decoations"""
variables = decoration.findmarkedvariables("The <variable> string", "<", ">")
assert variables == [(4, "variable")]
variables = decoration.findmarkedvariables("The $vari | able string", "$", 1)
assert variables == [(4, "v")]
variables = decoration.findmarkedvariables("The $variable string", "$", None)
assert variables == [(4, "variable")]
variables = decoration.findmarkedvariables("The $variable string", "$", 0)
assert variables == [(4, "")]
variables = decoration... |
marbindrakon/eve-poscensus | census.py | Python | gpl-3.0 | 5,093 | 0.001767 | # POS Census v0.1
# Copyright (c) 2012 Andrew Austin
# | This program is free software: | you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR... |
alexlo03/ansible | test/units/modules/network/f5/test_bigip_vcmp_guest.py | Python | gpl-3.0 | 5,742 | 0.000522 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... | me="guest1",
mgmt_network="bridged",
mgmt_address="10.10.10.10/24",
initial_image="BIGIP-13.1.0.0.0.931.iso",
server='localhost',
password='password',
user='admin'
))
module = AnsibleModule(
argument_spec=self.spec.argu... | supports_check_mode=self.spec.supports_check_mode
)
# Override methods to force specific logic in the module to happen
mm = ModuleManager(module=module)
mm.create_on_device = Mock(return_value=True)
mm.exists = Mock(return_value=False)
mm.is_deployed = Mock(side... |
NextThought/pypy-numpy | numpy/random/setup.py | Python | bsd-3-clause | 3,228 | 0.006196 | from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msv... | x in
['mtrand.c', 'randomkit.c', 'i | nitarray.c',
'distributions.c']]+[generate_libraries],
libraries=libs,
depends=[join('mtrand', '*.h'),
join('mtrand', '*.pyx'),
join('mtrand', '*.pxi'),],
... |
zzzoidberg/landscape | finance/quotes/options.py | Python | mit | 7,159 | 0.000978 | # -*- coding: UTF-8 -*-
"""
Options quotes.
"""
import os
import json
import logging
from datetime import datetime
import collections
import requests
from landscape.finance import consts, database, dates, utils
from landscape.finance.volatility import math
OptionQuote = collections.namedtuple(
'OptionQuote',
... | '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
[quote.symbol, quote.type, expiration, quote.strike,
date, time, quote.bid, quote.ask, quote.stock,
quote.iv_bid, quote.iv_ask])
def quote_factory(_, row):
"""Converts row to quote"""
symbol, type_, expir... | time, \
bid, ask, stock, iv_bid, iv_ask = row
expiration = database.decode_date(expiration)
date = database.decode_date(date)
time = database.decode_time(time)
return OptionQuote(symbol, type_, expiration, strike, date, time,
bid, ask, stock, iv_bid, iv_ask)
def _fetch_data(symbol):
... |
JonathonReinhart/killerbee | killerbee/zbwardrive/db.py | Python | bsd-3-clause | 2,845 | 0.009842 | import string
# Manages Local "database" for ZBWarDrive:
# This keeps track of current ZBWarDrive and Sniffing Device State.
# It is different from the online logging database.
class ZBScanDB:
"""
API to interact with the "database" storing information
for the zbscanning program.
"""
def __init_... | n the DB.
def get_networks_channel(self, key):
#print "Looking up channel for network with key of %s" % (key)
for chan, data in self.channels:
if data[0] == key: return chan
return None
def channel_status_logging(self, chan):
'''
Returns False if we have not ... | se Exception("None given for channel number")
elif chan not in self.channels: raise Exception("Invalid channel")
for dev in self.devices.values():
if dev[3] == chan and dev[2] == 'Capture':
return True
return False
# end of ZBScanDB class
def toHex(bin):
return '... |
joopert/home-assistant | homeassistant/components/monoprice/media_player.py | Python | apache-2.0 | 7,123 | 0.000421 | """Support for interfacing with Monoprice 6 zone home audio controller."""
import logging
import voluptuous as vol
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
from homeassistant.components.media_player.const import (
SUPPORT_SELECT_SOURCE,
SUPPORT_TURN_OFF,
SUPPORT... | }
hass.data[DATA_MONOPRICE] = []
for zone_id, extra | in config[CONF_ZONES].items():
_LOGGER.info("Adding zone %d - %s", zone_id, extra[CONF_NAME])
hass.data[DATA_MONOPRICE].append(
MonopriceZone(monoprice, sources, zone_id, extra[CONF_NAME])
)
add_entities(hass.data[DATA_MONOPRICE], True)
def service_handle(service):
... |
bgroff/django-cas-ng | django_cas_ng/migrations/0001_initial.py | Python | mit | 1,628 | 0.003686 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-13 18:08
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='SessionTicket',
fields=[
('id', models.AutoField(auto_cre | ated=True, primary_key=True, serialize=False, verbose_name='ID')),
('session_key', models.CharField(max_length=255)),
('ticket', models.CharField(max_length=255)),
],
),
migrations.AlterUniqueTogether(
name='proxygrantingticket',
unique... |
stefanv/lulu | lulu/tests/test_lulu.py | Python | bsd-3-clause | 1,934 | 0.001551 | from numpy.testing import *
import numpy as np
import lulu
import l | ulu.connected_region_handler as crh
class TestLULU:
img = np.zeros((5, 5)).astype(int)
img[0, 0:5] = 0
img[:, 4] = 1
img[1:3, 1:4] = 2
"""
[[0 0 0 0 1]
[0 2 2 2 1]
[0 2 2 2 1]
[0 0 0 0 1]
[0 0 0 0 1]]
"""
def test_connected_regions(self):
labels, regions = l... | ions[0], 5)
assert_array_equal(crh.todense(regions[0]),
[[5, 5, 5, 5, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 5, 5, 5, 0],
[5, 5, 5, 5, 0]])
assert_array_equal(cr... |
naturalis/HTS-barcode-checker | src/Parse_CITES.py | Python | bsd-3-clause | 2,371 | 0.033319 | #!/usr/bin/env python
from hts_barcode_checker import Taxon, TaxonDB
import logging, datetime, argparse, sqlite3
# NCBI taxonomy tree database 10.6084/m9.figshare.4620733
parser = argparse.ArgumentParser(description = 'Create a table containing the CITES species')
parser.add_argument('-db', '--CITES_db', metavar='C... | 1
# write output
for taxon in expanded:
db.taxa.append(taxon)
handle = open(args.db, 'w')
db.to_csv | (handle)
handle.close()
if __name__ == "__main__":
main()
|
ctiller/grpc | tools/run_tests/lb_interop_tests/gen_build_yaml.py | Python | apache-2.0 | 12,124 | 0.000577 | #!/usr/bin/env python3
# Copyright 2015 gRPC authors.
#
# 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 ... | 'transport_sec': backend_sec,
}],
'fallback_configs': [{
'transport_sec': 'insecure',
}],
'cause_no_error_no_data_for_balancer_a_record':
False,
}
a | ll_configs.append(config)
return all_configs
all_scenarios += generate_client_referred_to_backend_fallback_broken()
def generate_client_referred_to_backend_multiple_backends():
all_configs = []
for balancer_short_stream in [True, False]:
for transport_sec in [
'insecure', 'alts',... |
ThiefMaster/sqlalchemy | lib/sqlalchemy/dialects/postgresql/ext.py | Python | mit | 4,889 | 0.000205 | # postgresql/ext.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from ...sql import expression
from ...sql import elements
from ...sql import funct... | errable=self.deferrable,
initially=self.initially)
c.dispatch._update(self.dispatch)
return c
def array_agg(*arg, **kw):
"""Postgresql-specific form of :class:`.array_agg`, ensures
return type is :class:`.postgresql.ARRAY` and not
the plain :class:`.types.ARRAY`.... | _from_args(arg))
return functions.func.array_agg(*arg, **kw)
|
JNRowe/versionah | tests/test_python_compat.py | Python | gpl-3.0 | 1,950 | 0 | #
"""test_python_compat - Python output compatibility tests"""
# Copyright © 2012-2018 James Rowe <jnrowe@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of versionah.
#
# versionah is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Lic... | h(interp):
skip('Interpreter {!r} unavailable'.format(interp))
file_loc = tmpdir.join('test_wr.py').strpath
CliVersion('1.0.1').write(file_loc, 'py')
retval = call([interp, '-W', 'all', file_lo | c], stdout=PIPE,
stderr=PIPE)
assert retval == 0
# Test interps not available on travis-ci.org, but available on all our test
# machines
@mark.skipif(getenv('TRAVIS_PYTHON_VERSION'), reason='Unavailable on travis')
@mark.requires_exec
@mark.requires_write
@mark.parametrize('interp', [
'pytho... |
enthought/pyside | tests/QtGui/bug_389.py | Python | lgpl-2.1 | 414 | 0.007246 | ''' Test bug 389: http://bugs.openbossa.org/show_bug.cgi?id=389'''
i | mport sys
import unittest
from helper import UsesQApplication
from PySide import QtCore,QtGui
class BugTest(UsesQApplication):
def testCase(self):
s = QtG | ui.QWidget().style()
i = s.standardIcon(QtGui.QStyle.SP_TitleBarMinButton)
self.assertEqual(type(i), QtGui.QIcon)
if __name__ == '__main__':
unittest.main()
|
i-DAT-Qualia/Card-Backend | cards/admin.py | Python | apache-2.0 | 528 | 0.007576 | from django.contrib import admin
from models import | *
from cards.actions import export_as_xls
class ScanAdmin(admin.ModelAdmin):
list_filter = ['readerLocation', 'added']
search_fields = ['card__code']
# Register your models here.
admin.site.register(Batch)
admin.site.re | gister(Card)
admin.site.register(Reader)
admin.site.register(Location)
admin.site.register(ReaderLocation)
admin.site.register(Scan, ScanAdmin)
class MyAdmin(admin.ModelAdmin):
actions = [export_as_xls]
admin.site.add_action(export_as_xls)
|
lgapontes/django-socialregistration | socialregistration/contrib/twitter/auth.py | Python | mit | 487 | 0.002053 | from django.contrib.auth.backends import ModelBackend |
from django.contrib.sites.models import Site
from socialregistration.contrib.twitter.models import TwitterProfile
class TwitterAuth(ModelBackend):
def authenticate(self, twitter_id=None):
try:
return TwitterProfile.objects.get(
twitter_id=twitter_id,
site=... | ).user
except TwitterProfile.DoesNotExist:
return None
|
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2d/xbins/_size.py | Python | mit | 394 | 0.002538 | import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basev | alidators.AnyValidator):
def __init__(self, plotly_name="size", parent_name="histogram2d.xbins", **kwargs):
super(SizeValidator, self).__init__(
plotly_n | ame=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)
|
wzhang1984/Noncoding-tumor-mutation-paper | motif_analysis/ref2alt.py | Python | gpl-3.0 | 1,057 | 0.02649 |
info=[]
for line in open('./info_mappable_50.txt').read().rstrip().split('\n'):
a=line.split('\t')
info.append(a[0])
line_out=''
line_out2=''
seq=''
index=0
for line in open('./seqList_mappable_50.fa'):
if line[0]=='>':
if seq:
replace=seq[7:-7]
if replace!=ref:
... | +seq_alt+'\n'
header=info[index]
ref_alt=header.split('_')[1]
[ref,alt]=ref_alt.split('>')
index+=1
seq=''
if index/1000000==index/1000000.0:
print index
else:
seq+=line.split('\n')[0]
if seq:
replace=seq[7:-7]
if replace!=ref:
pri... | alt+seq[-7:]
line_out+='>'+header+'_ref'+'\n'+seq+'\n'
line_out2+='>'+header+'_alt'+'\n'+seq_alt+'\n'
open('./seqList_mappable_50_ref.fa','wb').write(line_out)
open('./seqList_mappable_50_alt.fa','wb').write(line_out2)
|
sigma-geosistemas/clone | src/manage.py | Python | lgpl-3.0 | 248 | 0 | #!/usr/bin/env python
import os
imp | ort sys
if __name__ == "__main__":
os.environ.setdefault("DJ | ANGO_SETTINGS_MODULE", "clone.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
UdK-VPT/Open_eQuarter | mole/stat_corr/window_wall_ratio_east_MFH_by_building_age_lookup.py | Python | gpl-2.0 | 2,380 | 0.147121 | # coding: utf8
# OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013'
import math
import numpy as np
import oeqLooku... | *xin):
l_lookup = oeq.lookuptable(
[
1849,0.031,
1850,0.031,
1851,0.03,
1852,0.027,
1853,0.024,
1854,0.025,
1855,0.03,
1856,0.042,
1857,0.06,
1858,0.082,
1859,0.105,
1860,0.128,
1861,0.15,
1862,0.168,
1863,0.18,
1864,0.18,
1865,0.18,
1866,0.18,
1867,0.18,
1868,0.179,
1869,0.179,
1870,0.179,
1871,0.18,
1872,0.18,
... | 8,
1883,0.18,
1884,0.18,
1885,0.18,
1886,0.18,
1887,0.18,
1888,0.18,
1889,0.18,
1890,0.18,
1891,0.18,
1892,0.18,
1893,0.18,
1894,0.18,
1895,0.18,
1896,0.18,
1897,0.18,
1898,0.18,
1899,0.18,
1900,0.18,
1901,0.18,
1902,0.18,
1903,0.18,
1904,0.18,
1905,0.18,
1906,0.18,
1907,0.18,
1908,0.179,
1909,0.179,
1910,0.179,
1911,0... |
maroux/django-oauth2-provider | provider/compat/__init__.py | Python | mit | 148 | 0 | try:
from django.contrib.auth.tests.u | tils import skipIfCustomUser
except ImportError:
def sk | ipIfCustomUser(wrapped):
return wrapped
|
vlegoff/cocomud | src/ui/sharp_editor.py | Python | bsd-3-clause | 10,805 | 0.001574 | # Copyright (c) 2016, LE GOFF Vincent
# 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 conditions and th... |
for function in self.functions:
try:
description = t("sharp.{name}.description".format(
name=function.name))
except ValueError:
description = function.description
self.choices.Append((description, ))
self.choi... | ""Populate the list with existing functions."""
self.existing.DeleteAllItems()
script = getattr(self.object, self.attribute)
if self.text:
self.text.SetValue(script)
lines = self.sharp_engine.format(script, return_str=False)
for line in lines:
self.existi... |
userzimmermann/robotframework-python3 | atest/testresources/testlibs/objecttoreturn.py | Python | apache-2.0 | 343 | 0.011662 | try:
import exce | ptions
except ImportError: # Python 3
import builtins as exceptions
class ObjectToReturn:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def exception(self, name, msg=""):
exception = getattr(exceptions, | name)
raise exception(msg)
|
llvm-mirror/lldb | packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py | Python | apache-2.0 | 1,050 | 0 | # encoding: utf-8
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
class ObjCDataFormatterNS... | ssDarwin
def test_nserror_with_run_command(self):
"""Test formatters for NSError."""
self.appkit_tester_impl(self.nserror_data_formatter_commands)
def nserror_data_formatter_commands(self):
self.expect(
'frame variable nserror', substrs=['domain: @"Foobar" - code: 12'])
... |
'frame variable nserrorptr',
substrs=['domain: @"Foobar" - code: 12'])
self.expect(
'frame variable nserror->_userInfo', substrs=['2 key/value pairs'])
self.expect(
'frame variable nserror->_userInfo --ptr-depth 1 -d run-target',
substrs=['@... |
aseemm/flask-template | wentries.py | Python | bsd-3-clause | 256 | 0 | from app import write | _entries
import datetime
import random
ts = datetime.datetime.now().strftime("%Y-%m-%d%H:%M-%S")
offset = random.randrange(0, 1475)
print("Enter user=%s" % ts)
print("Enter email=%s" % offset)
prime = write | _entries.delay(ts, offset)
|
jablonskim/jupyweave | jupyweave/settings/align_types.py | Python | mit | 137 | 0 | from enum import Enum
class ImageAlignType(Enum):
"""Image alignment"""
Default = 1
Left = 2
Rig | ht = 3
Center | = 4
|
Techblogogy/magic-mirror-base | server/routes/gcal.py | Python | gpl-3.0 | 2,343 | 0.003841 | import decor
from flask import Blueprint, redirect, request, url_for
import os, json
def construct_bp(gcal, JSON_DENT):
ALLOWED_ORIGIN = "*"
# JSON_DENT = 4
gcal_api = Blueprint('gcal_api', __name__, url_prefix="/gcal")
# GOOGLE CALENDAR API Routes
# Authenication routes
@gcal_api.route('... | def gauth_call():
return redirect(gcal.get_auth_uri())
@gcal_api.route('/isauth')
def gauth_isauth():
return json.dumps({'is_needed': not gcal.need_auth()})
@gcal_api.route('/istblexist')
def gauth_istblex():
return json.dumps({'is_exist': gcal.if_cal_tbl()})
@gcal_api.route... | ods=['GET','OPTIONS'])
@decor.crossdomain(origin=ALLOWED_ORIGIN)
def gcal_today():
return json.dumps(gcal.get_today(), indent=JSON_DENT)
# Get calendars
@gcal_api.route('/calendars', methods=['GET','OPTIONS'])
@decor.crossdomain(origin=ALLOWED_ORIGIN)
def gcal_cals():
return jso... |
kkopachev/thumbor | thumbor/filters/format.py | Python | mit | 823 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# License | d under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from thumbor.filters import BaseFilter, filter_method
from thumbor.utils import logger
ALLOWED_FORMATS = ["png", "jpeg", "jpg", "gif", "webp"]
class Filter(BaseFilter):
@ | filter_method(BaseFilter.String)
async def format(self, file_format):
if file_format.lower() not in ALLOWED_FORMATS:
logger.debug("Format not allowed: %s", file_format.lower())
self.context.request.format = None
else:
logger.debug("Format specified: %s", file_form... |
IT-PM-OpenAdaptronik/Webapp | apps/calc/measurement/calculus.py | Python | mit | 3,360 | 0.009226 | import numpy as np
import json
import scipy as sci
def get_decimal_delta(data, index,decimals):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places t... | en(deltas)
def numerical_approx(data, diff_Value1_Index, diff_Value2_Index = 0):
'''
This method derives one Data Column by another
Zeitwerte
Example: d Speed / d Time = Acceleration
:param data: the pandas DataFrame of the data
:param diff_Value1_Index: Index of the Column to get the derivati... | e.append(np.float_(0.000))
data = np.array(json.loads(data), dtype=np.float64)
for v1, t1 in zip(get_delta(data, int(diff_Value1_Index)), get_delta(data, int(diff_Value2_Index))):
diff_Value.append(v1 / t1)
return np.asarray(diff_Value)
def trapez_for_each(data, index_x, index_y):
"""... |
edwarod/quickbot_bbb | test.py | Python | bsd-3-clause | 571 | 0.033275 | import Adafruit_BBIO.GPIO as GPIO
import time
a=0
b=0
def derecha(channel):
global a
| a+=1
print 'cuenta derecha es {0}'.format(a)
def izquierda(channel):
global b
b+=1
print 'cuenta izquierda es {0}'.format(b)
GPIO.setup("P9_11", GPIO.IN)
GPIO.setup("P9_13", GPIO.IN)
GPIO.add_event_detect("P9_11", GPIO.BOTH)
GPIO.add_event_detect("P9_13", GPIO.BOTH)
GPIO.add_event_callback("P9_11",derech... | print "event detected"
while True:
print "cosas pasan"
time.sleep(1)
|
kbase/narrative_method_store | test/data/test_repo_1/service/GenomeFeatureComparatorServer.py | Python | mit | 25,877 | 0.002164 | #!/usr/bin/env python
from wsgiref.simple_server import make_server
import sys
import json
import traceback
import datetime
from multiprocessing import Process
from getopt import getopt, GetoptError
from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\
JSONRPCError, ServerError, InvalidRequestE... | s
import requests as _requests
import urlparse as _urlparse
import random as _random
import os
DEPLOY = 'KB_DEPLOYMENT_CONFIG'
SERVICE = 'KB_SERVICE_NAME'
# Note that the error fields do not match the 2.0 JSONRPC spec
def get_config_file():
return environ.get(DEPLOY, None)
def get_service_name():
return en... | ):
return None
retconfig = {}
config = ConfigParser()
config.read(get_config_file())
for nameval in config.items(get_service_name()):
retconfig[nameval[0]] = nameval[1]
return retconfig
config = get_config()
from GenomeFeatureComparatorImpl import GenomeFeatureComparator
impl_Genom... |
google-research/google-research | robust_optim/data.py | Python | apache-2.0 | 2,993 | 0.007016 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | w, dim, temp, rng_key):
"""Samples data from a standard Gaussian with binary noisy labels.
Args:
num: An integer denoting the number of data points.
w: An array of size dim x odim, the weight vector used to generate labels.
dim: An integer denoting the number of input dimensions.
temp: A float deno... | ns:
x: An array of size dim x num denoting data points.
y_pm: An array of size num x odim denoting +/-1 labels.
"""
rng_subkey = jax.random.split(rng_key, 3)
x = jax.random.normal(rng_subkey[0], (dim, num))
prob = jax.nn.sigmoid(-(1 / temp) * w.T.dot(x))
y = jax.random.bernoulli(rng_subkey[1], (prob))... |
meduz/scikit-learn | sklearn/metrics/tests/test_score_objects.py | Python | bsd-3-clause | 17,473 | 0.000057 | import pickle
import tempfile
import shutil
import os
import numbers
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raises_regexp
from sklearn.utils.t... | 0
assert_raises(ValueError, make_scorer, f, needs_threshold=True,
needs_proba=True)
def test_classification_scores():
# Test classifi | cation scorers.
X, y = make_blobs(random_state=0, centers=2)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = LinearSVC(random_state=0)
clf.fit(X_train, y_train)
for prefix, metric in [('f1', f1_score), ('precision', precision_score),
('reca... |
lautr3k/RepRap-iTopie | odmt/ezdxf/ac1021/__init__.py | Python | gpl-3.0 | 330 | 0 | # Purpose: dxf engine for R2007/AC1021
# Created: 12.03.2011
# Copyright (C) , Manfred Moitzi
# License: MIT Licen | se
from __future__ import unicode_literals
__author__ = "mozman <mozman@gmx.at>"
from .headervars import VARMAP
from ..ac1018 import AC1018Factory
class AC1021Factory(AC1018Factory):
HEADERVARS = dict(VA | RMAP)
|
Curly-Mo/audio | __init__.py | Python | mit | 23 | 0 | f | rom audio.io import *
| |
xu6148152/Binea_Python_Project | PythonCookbook/meta/newlower.py | Python | mit | 1,116 | 0.000896 | # -*- encoding: utf-8 -*-
import ast
import inspect
class NameLower(ast.NodeVisitor):
def __init__(self, lowered_names):
self.lowered_names = lowered_names
def visit_FunctionDef(self, node):
code = '__globals = globals()\n'
code += '\n'.join("{0} = __globals['{0}']".format(name) for ... | ef lower(func):
srclines = inspect.getsource(func).split | lines()
for n, line in enumerate(srclines):
if '@lower_names' in line:
break
src = '\n'.join(srclines[n + 1:])
if src.startswith(' ', '\t'):
src = 'if 1:\n' + src
top = ast.parse(src, mode='exec')
cl = Nam... |
PyWavelets/pywt | pywt/tests/test_dwt_idwt.py | Python | mit | 10,352 | 0.00058 | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_allclose, assert_, assert_raises,
assert_array_equal)
import pywt
# Check that float32, float64, complex64, complex128 are preserved.
# Other real type... | cA, cD = pywt.dwt(x, 'db2' | , axis=-1)
x0 = pywt.idwt(cA[0], cD[0], 'db2', axis=-1)
x1 = pywt.idwt(cA[1], cD[1], 'db2', axis=-1)
assert_allclose(x[0], x0)
assert_allclose(x[1], x1)
def test_dwt_invalid_input():
x = np.arange(1)
assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect')
assert_raises(ValueError, pywt.d... |
public0821/nettest | nettest/packets/base.py | Python | apache-2.0 | 7,940 | 0.005038 | from .fields import BitField, Field
from nettest.exceptions import NettestError
import struct
class PacketMeta(type):
def __new__(cls, name, bases, attrs):
fields = attrs.get('fields')
if fields is None:
raise NettestError(_("packet class must have 'fields' field"))
_fields = []... | testError(_("the name '_fields' is reserved in class %s")%(name))
attrs['_fields']= _fields
return super(PacketMeta, cls).__new__(cls, name, bases, attrs)
@staticmethod
def __check_field_type(cls, field):
if not isinstance(field, (Field, Packet, list)):
return False
... | return True
class BitDumper(object):
def __init__(self):
self.data= []
self.data_len = []
self.data_len_sum = 0
def clear(self):
self.data = []
self.data_len = []
self.data_len_sum = 0
def push(self, data, length):
data = int(data)
i... |
fhocutt/grantsbot-matching | matching/utils.py | Python | lgpl-3.0 | 2,104 | 0.002376 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
utils
=====
Utility functions for matching.py.
"""
import datetime
import json
import os
#testme
def parse_timestamp(t):
"""Parse MediaWiki-style timestamps and return a datetime."""
if t == '0000-00-00T00:00:00Z':
return None
else:
return ... | prevrunt | imestamp = timelog.read()
timelog.seek(0)
timelog.write(datetime.datetime.strftime(run_time,
'%Y-%m-%dT%H:%M:%SZ'))
timelog.truncate()
except IOError:
with open(timelogfile, 'wb') as timelog:
prevruntimestam... |
beeleb/Kandori-Mailath-Rob | mc_tools.py | Python | bsd-3-clause | 1,915 | 0.0047 | """
Filename: mc_tools.py
Authors: John Stachurski and Thomas J. Sargent
"""
import numpy as np
from discrete_rv import DiscreteRV
def mc_compute_stationary(P):
"""
Computes the stationary distribution of Markov matrix P.
Parameters
===========
P : a square 2D NumPy array
Returns: A fla... | Markov
matrix P on state space S = {0,...,n-1}.
Parameters |
==========
P : A nonnegative 2D NumPy array with rows that sum to 1
init : Either an integer in S or a nonnegative array of length n
with elements that sum to 1
sample_size : int
If init is an integer, the integer is treated as the determinstic initial
condition. ... |
CINPLA/expipe-dev | python-neo/neo/core/irregularlysampledsignal.py | Python | gpl-3.0 | 20,385 | 0.001864 | # -*- coding: utf-8 -*-
'''
This module implements :class:`IrregularlySampledSignal`, an array of analog
signals with samples taken at arbitrary time points.
:class:`IrregularlySampledSignal` derives from :class:`BaseNeo`, from
:module:`neo.core.baseneo`, and from :class:`quantites.Quantity`, which
inherits from :clas... | the same time points.
*Usage*::
>>> from neo.core import IrregularlySampledSignal
>>> from quantities import s, nA
>>>
>>> irsig0 = IrregularlySampledSignal([0.0, 1.23, 6.78], [1, | 2, 3],
... units='mV', time_units='ms')
>>> irsig1 = IrregularlySampledSignal([0.01, 0.03, 0.12]*s,
... [[4, 5], [5, 4], [6, 3]]*nA)
*Required attributes/properties*:
:times: (quantity array 1D, numpy array 1D, or l... |
openhatch/new-mini-tasks | vendor/packages/Django/tests/regressiontests/utils/dateformat.py | Python | apache-2.0 | 6,241 | 0.001282 | from __future__ import unicode_literals
from datetime import datetime, date
import os
import time
from django.utils.dateformat import format
from django.utils import dateformat, translation, unittest
from django.utils.timezone import utc
from django.utils.tzinfo import FixedOffset, LocalTimezone
class DateFormatTes... | 5, 30, 30)
self.assertEqual(datetime.fro | mtimestamp(int(format(dt, 'U'))), dt)
def test_datetime_with_local_tzinfo(self):
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=ltz)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEqual(datetime.fromtimestamp(int(... |
PaloAltoNetworks-BD/SplunkforPaloAltoNetworks | Splunk_TA_paloalto/bin/splunk_ta_paloalto/aob_py3/solnlib/conf_manager.py | Python | isc | 14,825 | 0.000742 | # Copyright 2016 Splunk, 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,... | if e.status != 404:
raise
return False
return True
@retry(exceptions=[binding.HTTPError])
| def get(self, stanza_name, only_current_app=False):
'''Get stanza from configuration file.
:param stanza_name: Stanza name.
:type stanza_name: ``string``
:returns: Stanza, like: {
'disabled': '0',
'eai:appName': 'solnlib_demo',
'eai:userName': 'nobody... |
lavish205/olympia | src/olympia/addons/tests/test_forms.py | Python | bsd-3-clause | 13,654 | 0 | # -*- coding: utf-8 -*-
import os
import tempfile
import shutil
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.test.client import RequestFactory
from mock import patch
from olympia import amo, core
from olympia.addons import forms
from olympia.addons.mod... | AddonFormBasic(data=data, request=self.request,
instance=self.addon)
| assert form.errors['tags'][0] == (
'"i_am_a_restricted_tag", "sdk" are reserved tags and'
' cannot be used.')
@patch('olympia.access.acl.action_allowed')
def test_tags_admin_restricted(self, action_allowed):
action_allowed.return_value = True
self.add_r |
theojulienne/pyio | pyio/io/StreamWatcher.py | Python | mit | 3,517 | 0.063122 | from collections import namedtuple
import select
StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] )
class StreamWatcher(object):
def __init__( self ):
if _best_backend is None:
raise Exception( "No poll/queue backend could be found for your OS." )
self.backe... | x_events=max_events,
fd_data_map=self.fd_map,
fd_stream_map=self.stream_map )
_best_backend = None
try:
from select import kqueue, kevent
except ImportError:
pass
else:
class KQueueBackend(object):
def __init__( self ):
self.kq = kqueue( )
def watch_read( self, fd ):
event = kevent( fd, filter=sel... | EV_ADD )
self._add_events( [event] )
def _add_events( self, new_events ):
e = self.kq.control( new_events, 0, 0 )
assert len(e) == 0, "Not expecting to receive any events while adding filters."
def wait( self, timeout=None, max_events=4, fd_data_map={}, fd_stream_map={} ):
r_events = self.kq.contr... |
openego/oeplatform | login/urls.py | Python | agpl-3.0 | 2,215 | 0.004966 | from django.conf.urls import include, url
from django.urls import path
from login import views
from django.contrib.auth.views import PasswordResetCompleteView, PasswordResetConfirmView, PasswordResetDoneView
urlpatterns = [
path('password_reset/', views.PasswordResetView.as_view(
html_email_template_name="... | me="input",
),
url(
r"^profile/(?P<user_id>[\d]+)/edit$", views.EditUserView.as_view(), name="input"
),
url(r"^groups/$", views.GroupManagement.as_view(), name="input"),
url(
r"^groups/new/$",
views.GroupCreate.as_view(),
name="input",
),
url(
r"^group... | views.GroupView.as_view(),
),
url(
r"^groups/(?P<group_id>[\w\d_\s]+)/members$",
views.GroupEdit.as_view(),
name="input",
),
url(r"^groups/new/$", views.GroupCreate.as_view(), name="input"),
url(r"^register$", views.CreateUserView.as_view()),
url(r"^detach$", views.Deta... |
tensorflow/federated | tensorflow_federated/python/core/impl/computation/__init__.py | Python | apache-2.0 | 651 | 0 | # Copyright 2020, The TensorFlow Federated Authors.
#
# 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 the License is distributed o... | or the specific language governing permissions and
# limitations under the License.
"""Libraries for interacting with a computation."""
|
UltrosBot/Ultros3K | src/ultros/core/networks/base/servers/base.py | Python | artistic-2.0 | 942 | 0.002123 | # coding=utf-8
from abc import ABCMeta, abstractmethod
from typing import Optional
from weakref import ref
from logging import getLogge | r
from ultros.core.networks.base.connectors import base as base_connector
from ultros.core.networks.base.networks import base as base_network
__author__ = "Gareth Coles"
class BaseServer(metaclass=ABCMeta):
def __init__(self, name: str, network: "base_network.BaseNetwork"):
self.name = name
self... | ogger(self.name) # TODO: Logging
@property
def network(self) -> "base_network.BaseNetwork":
return self._network()
@abstractmethod
async def connector_connected(self, connector: "base_connector.BaseConnector"):
pass
@abstractmethod
async def connector_disconnected(self, conne... |
MarcFord/Emburse-python | emburse/client.py | Python | gpl-3.0 | 4,177 | 0.002394 | from emburse.resource import (
EmburseObject,
Account,
Allowance,
Card,
| Category,
Company,
Department,
Label,
Location,
Member,
SharedLink,
Statement,
Transaction
)
class Client(EmburseObject):
"""
Emburse API Client
API enables for the cre | ation of expense cards at scale for custom business solutions as well as for
third-party app integrations. Cards can be created with set spending limits and assigned with just an email.
Some use cases include vendor payments, employee expense control, and fleet card management.
API Version:
... |
flavour/iscram | modules/s3/s3aaa.py | Python | mit | 198,273 | 0.003299 | # -*- coding: utf-8 -*-
""" Authentication, Authorization, Accouting
@requires: U{B{I{gluon}} <http://web2py.com>}
@copyright: (c) 2010-2012 Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated docum... | messages.lock_keys = False
self.messages.registration_pending_approval = "Account registered, however registration is still pending approval - please wait until confirmation received."
self.messages.email_approver_failed = "Failed to send mail to Approver - see if you can notify them manually!"
... | d or our email server is down"
self.messages.email_sent = "Verification Email sent - please check your email to validate. If you do not receive this email please check you junk email or spam filters"
self.messages.email_verified = "Email verified - you can now login"
self.messages.welcome_email_... |
tjmcewan/odin | setup.py | Python | bsd-3-clause | 1,229 | 0 | from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='odin',
version='0.4.2',
url='https://github.com/timsavage/odin',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredbype... | generation
'doc_gen': ["jinja2>=2.7"],
# Pint integration
'pint': ["pint"],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Pro... | g Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
science-en-poche/yelandur | docs/source/conf.py | Python | gpl-3.0 | 7,995 | 0.007383 | # -*- coding: utf-8 -*-
#
# Yelandur documentation build configuration file, created by
# sphinx-quickstart on Thu Jan 10 16:10:42 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> document... | hort_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = ... |
pyrate-build/pyrate-build | examples/test03.py | Python | apache-2.0 | 489 | 0.03272 | import logging
try:
create_external('xml2', build_helper = 'xml2-config',
version_query = '--version', version_parser = lambda x: 'invalid')
except Exception:
logging.critical('external version parsing')
try:
tools['c'].std = 'latest'
except Exception:
logging.critical('std setting | ')
try:
shared_library('x', [])
except Exception:
logging.critical('shared_library | : empty input')
try:
static_library('x', [])
except Exception:
logging.critical('static_library: empty input')
|
biomodels/MODEL8687196544 | MODEL8687196544/model.py | Python | cc0-1.0 | 427 | 0.009368 | import os
path = os.path.dirname(os.path.rea | lpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL8687196544.xml')
with open(sbmlFilePath,'r') as f:
sbmlSt | ring = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) |
liangsuilong/ztq | ztq_demo/tasks.py | Python | mit | 586 | 0.020478 | # encoding: utf-8
from ztq_core import async
import time
@async
def send(body):
print 'START: ', body
time.sleep(3)
print 'END: ', body
@async(queue='mail')
def send_failed(body):
print 'FAIL START:', body
rais | e Exception('connection error...')
@async(queue='mail')
def failed_callback(ret | urn_code, return_msg):
print 'FAILED CALLBACK:', return_code, return_msg
@async(queue='index')
def index(data):
print 'INDEX:', data
time.sleep(1)
def do_commit():
print 'COMMITTED'
import ztq_worker
ztq_worker.register_batch_queue('index', 5, do_commit)
|
tvarney/txtrpg | rpg/io/configuration.py | Python | mit | 15,670 | 0 |
import abc
import os
import os.path
import platform
import yaml
import typing
if typing.TYPE_CHECKING:
from typing import Any, Dict, IO, Optional, Sequence, Type
class PropertyTypeError(ValueError):
def __init__(self, property_name: str, value: 'Any') -> None:
ValueError.__init__(self, "can not set... | loat = 0.0) -> None:
"""Create a new Float property.
:param default: The default value of the property
"""
if type(default) is not float:
raise PropertyTypeError("Float", default)
PrimitiveProperty.__init__(self, default)
@property
d | ef value(self) -> float:
"""The value of the property."""
return self._value
@value.setter
def value(self, value: float) -> None:
if type(value) is not float:
raise PropertyTypeError("Float", value)
self._value = value
@property
def default(self) -> int:
... |
elegion/djangodash2013 | wtl/wtlib/tests/models.py | Python | mit | 2,921 | 0 | from __future__ import unicode_literals
from django.test import TestCase
from wtl.wtlib.models impo | rt Library, LibraryVersion
from wtl.wtlib.tests.factories import (LibraryFactory, LibraryVersionFacto | ry,
ProjectFactory)
class LibraryTestCase(TestCase):
def test_str(self):
x = LibraryFactory()
self.assertEqual(str(x), x.name)
class LibraryVersionTestCase(TestCase):
def test_str(self):
x = LibraryVersionFactory()
self.assertEqual(str(x... |
rehandalal/morgoth | morgoth/wsgi.py | Python | mpl-2.0 | 296 | 0 | imp | ort os
from configurations.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "morgoth.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Production")
application = DjangoWhiteNoise | (get_wsgi_application())
|
itziakos/trait-documenter | trait_documenter/trait_documenter.py | Python | bsd-3-clause | 4,946 | 0.000404 | #----------------------------------------------------------------------------
#
# Copyright (c) 2014, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in /LICENSE.txt and may be redistributed only
# under the conditions described in... | # AttributeError, but importing modules with side effects can raise
# all kinds of errors.
except Exception as err:
if self.env.app and not self.env.app.quiet:
| self.env.app.info(traceback.format_exc().rstrip())
msg = (
'autodoc can\'t import/find {0} {r1}, it reported error: '
'"{2}", please check your spelling and sys.path')
self.directive.warn(msg.format(
self.objtype, str(self.fullname),... |
maat25/brain-decoding | classifier/knn-correlation.py | Python | mit | 427 | 0.04918 | from scipy.spatial.distance import cdist
import numpy as np
class KNNC1(object):
def fit(self, X, Y):
self.X = X
self.Y = Y
def predict(self, Z):
dists = cdist(self.X, | Z, 'correlation')
indices = dists.argmin(axis = 0)
return self.Y[indices]
def predict_proba(self, Z):
predictions = self.predict(Z)
result = np.zeros((Z.shape[0], np.unique(self.Y).size | ))
result[:,predictions-1] = 1
return result
|
won0089/oppia | core/domain/collection_domain.py | Python | apache-2.0 | 22,777 | 0 | # coding: utf-8
#
# Copyright 2015 The Oppia 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 requi... | nChange object from a dict.
change_dict represents a command. It should have a 'cmd' key, and one
or more other keys. The keys depend on what the value for 'cmd' is.
The possible values for 'cmd' are listed below, together with the other
keys in the dict:
- 'add_collection_node... | ploration_id)
- 'edit_collection_node_property' (with exploration_id,
property_name, new_value and, optionally, old_value)
- 'edit_collection_property' (with property_name, new_value and,
optionally, old_value)
- 'migrate_schema' (with from_version and to_version)
... |
PaballoDitshego/grassroot-platform | docs/tests/vote_requests.py | Python | bsd-3-clause | 2,148 | 0.021881 | __author__ = 'aakilomar'
import requests, json, time
requests.packages.urllib3.disable_warnings()
host = "https://localhost:8443"
#from rest_requests import add_user
def add_user(phone):
post_url = host + "/api/user/add/" + str(phone)
return requests.post(post_url,None, verify=False).json()
def add_group(use... | d,userid,message):
post_url = host + "/api/event/rsvp/" + str(eventid) + "/" + str(userid) + "/" + str(message)
return requests.post(post_url,None, verify=False).json()
def add_user_to | _group(userid,groupid):
post_url = host + "/api/group/add/usertogroup/" + str(userid) + "/" + str(groupid)
return requests.post(post_url,None, verify=False).json()
def manualreminder(eventid,message):
post_url = host + "/api/event/manualreminder/" + str(eventid) + "/" + str(message)
return requests.pos... |
lucc/alot | alot/db/envelope.py | Python | gpl-3.0 | 13,285 | 0 | # Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
import glob
import logging
import os
import re
import email
import email.policy
from email.encoders import encode_7or8bit
from email.mi... | .. import __version__
from .. import helper
from .. import crypto
from ..settings.const import settings
from ..errors import GPGProblem, GPGCode
charset.add_charset('utf-8', charset.QP, charset.QP, 'utf-8')
class Envelope(object):
"""a message that is not yet sent and still editable.
It holds references to ... | bar.baz'` and
'e.get_all('To')' would work for an envelope `e`..
"""
headers = None
"""
dict containing the mail headers (a list of strings for each header key)
"""
body = None
"""mail body as unicode string"""
tmpfile = None
"""template text for initial content"""
attachmen... |
quantrocket-llc/quantrocket-client | quantrocket/ibg.py | Python | apache-2.0 | 6,653 | 0.002856 | # Copyright 2017 QuantRocket - 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 applicable law or ... | esponse.json()
def _cli_list_gateway_statuses(*args, **k | wargs):
return json_to_cli(list_gateway_statuses, *args, **kwargs)
def start_gateways(gateways=None, wait=False):
"""
Start one or more IB Gateways.
Parameters
----------
gateways : list of str, optional
limit to these IB Gateways
wait: bool
wait for the IB Gateway to star... |
b0ttl3z/SickRage | sickbeard/metadata/helpers.py | Python | gpl-3.0 | 1,452 | 0.001377 | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 L... | import print_function, unicode_literals
f | rom sickbeard import helpers, logger
meta_session = helpers.make_session()
def getShowImage(url, imgNum=None):
if url is None:
return None
# if they provided a fanart number try to use it instead
if imgNum is not None:
tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg"
else:
... |
LLNL/spack | var/spack/repos/builtin/packages/py-azure-mgmt-deploymentmanager/package.py | Python | lgpl-2.1 | 877 | 0.002281 | # 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)
class PyAzureMgmtDeploymentmanager(PythonPackage):
"""Microsoft Azure Deployment Manager Client Library for Python."""
homepage = "https://github.com/Azure/a | zure-sdk-for-python"
pypi = "azure-mgmt-deploymentmanager/azure-mgmt-deploymentmanager-0.2.0.zip"
version('0.2.0', sha256='46e342227993fc9acab1dda42f2eb566b522a8c945ab9d0eea56276b46f6d730')
depends_on('py-setuptools', type='build')
depends_on('py-msrest@0.5.0:', type=('build', 'run'))
depends_on('... |
Mkaysi/weechat | doc/docgen.py | Python | gpl-3.0 | 30,574 | 0.000065 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2015 Sébastien Helleu <flashcode@flashtux.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your opt... | for key in ('min', 'max', 'null_value_allowed'):
options[config][section][option][key] = \
weechat.infolist_integer(infolist, key)
weechat.infolist_free(infolist | )
return options
def get_infos():
"""
Get list of WeeChat/plugins infos as dictionary with 3 indexes: plugin,
name, xxx.
"""
infos = defaultdict(lambda: defaultdict(defaultdict))
infolist = weechat.infolist_get('hook', '', 'info')
while weechat.infolist_next(infoli |
sbrandtb/flop | flop/dashboard/views.py | Python | mit | 320 | 0 | from django.contrib.auth.decorators import login_required
from django.vi | ews.generic import TemplateView
from flop.cooking.forms import MealForm, MealContributionFormSet
from flop.decorators import view_decorator
@view_decorator(login_required)
class IndexView(TemplateView):
template_name = 'dashboard/in | dex.html'
|
containers-tools/base | base/file.py | Python | mit | 3,057 | 0.001636 | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
"""
import os
import shutil
import grp
import pwd
from cct.module import Module
from cct.lib.file_utils import create_dir
class File(Module):
... | """
# supplied owner/group might be symbolic (e.g. 'wheel') or numeric.
# Try interpreting symbolically first
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
gid = int(group,0)
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyEr... | os.chown(path, uid, gid)
if recursive and os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for f in (dirnames + filenames):
os.chown(os.path.join(dirpath, f), uid, gid)
def chmod(self, mode, path, recursive=False):
"""
... |
jhawthorn/plugin.video.gomtv.net | gomtv.py | Python | gpl-3.0 | 9,910 | 0.005045 | import urllib, urllib2, re, cookielib, os, tempfile, json, md5, time
from BeautifulSoup import BeautifulSoup
import proxy
from gomutil import *
class NotLoggedInException(Exception):
pass
def request(url, params=None, headers={}, opener=None):
data = params and urllib.urlencode(params)
req = urllib2.Reque... | (1)
self.set_cookie(" | oauth_token", oauth_token)
self.set_cookie("oauth_token_secret", oauth_token_secret)
data = self._request(location)
soup = BeautifulSoup(data)
oauth_token = soup.find("input", {"id": "oauth_token"})["value"]
auth_token = soup.find("input", {"name": "authentic... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/jockey/xorg_driver.py | Python | gpl-3.0 | 48 | 0.020833 | ../../../ | ../share/pyshared/jo | ckey/xorg_driver.py |
SNoiraud/gramps | gramps/gen/filters/rules/person/_hasrelationship.py | Python | gpl-2.0 | 3,035 | 0.005601 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 you... | specified_type = FamilyRelType()
specified_type.set_from_xml_str(self.list[1])
# count children and look for a relationship type match
for f_id in person.get_family_handle_list():
f = db.get_family_from_handle(f_id)
if f:
cnt = cnt + len(f.get_ch... | _list())
if self.list[1] and specified_type == f.get_relationship():
rel_type = 1
# if number of relations specified
if self.list[0]:
try:
v = int(self.list[0])
except:
return False
if v != num_rel:
... |
bstrebel/OxAPI | test/_attachment.py | Python | gpl-2.0 | 3,939 | 0.010916 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys, re, json, requests
from oxapi import *
def get_a_task(ox):
folder = ox.get_standard_folder('tasks')
task = list(ox.get_tasks(folder.id))[0]
return task
def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachme... | #'attached': bean.id,
'folder': bean.folder_id}
counter = | 0; fields = []
for data in args:
# json metadata
rf = RequestField(name='json_' + str(counter) ,data=json.dumps(meta))
rf.make_multipart(content_disposition='form-data')
fields.append(rf)
# content: data or file to read
filename = 'attachment.txt'
mimetype =... |
cbrepo/django-reversion | src/reversion/tests_deprecated.py | Python | bsd-3-clause | 25,219 | 0.005512 | """Tests for the deprecated version of the django-reversion API."""
from __future__ import with_statement
import datetime
from django.db import models, transaction
from django.test import TestCase
from django.core.management import call_command
import reversion
from reversion.models import Version, Revision, VERSIO... | st(TestCase):
"""Tests that django-reversion can retrieve revisions using the api."""
model = ReversionTestMod | el
def setUp(self):
"""Sets up the ReversionTestModel."""
# Clear the database.
Revision.objects.all().delete()
self.model.objects.all().delete()
# Register the model.
reversion.register(self.model)
# Create some initial revisions.
with reversion.... |
3dfxsoftware/cbss-addons | account_analytic_btree/account_analytic_btree.py | Python | gpl-2.0 | 1,689 | 0 | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com)
####################################... | rit = 'account.analytic.account'
_order = "parent_left"
_parent_order = "code"
_parent_store = True
_columns = {
'parent_right': fields.integer('Parent Right', | select=1),
'parent_left': fields.integer('Parent Left', select=1),
}
|
akshmakov/Dolfin-Fijee-Fork | test/unit/book/python/chapter_1_files/stationary/poisson/dnr_p2D.py | Python | lgpl-3.0 | 3,020 | 0.004305 | """
FEniCS tutorial demo program: Poisson equation with Dirichlet,
Neumann and Robin conditions.
The solution is checked to coincide with the exact solution at all nodes.
The file is a modification of dn2_p2D.py. Note that the boundary is now also
split into two distinct parts (separate objects and integrations)
and w... | ):
tol = 1E-14 # tolerance for coordinate comparisons
| return on_boundary and abs(x[0] - 1) < tol
Gamma_1 = RightBoundary()
Gamma_1.mark(boundary_parts, 3)
#-------------- Solution and problem definition step -----------------
# given mesh and boundary_parts
u_L = Expression('1 + 2*x[1]*x[1]')
u_R = Expression('2 + 2*x[1]*x[1]')
bcs = [DirichletBC(V, u_L, boundar... |
thuck/proc | proc/consoles.py | Python | lgpl-3.0 | 1,126 | 0.000888 | from .basic import ProcFile
from collections import namedtuple
class Consoles(ProcFile):
filename = '/proc/consoles'
Console = namedtuple('Console', ['operations', 'flags', 'major', 'minor'])
def names(self):
return [line.split()[0] for line in self._readfile()]
def get(self, name, default=N... | fo = line.replace('(', '').replace(')', '').split()
if name == console_info[0]:
major, minor = console_info[-1].split(':')
return [console_info[1],
''.join(console_info[2:-1]), major, minor
]
else:
return de... | ames():
return self.Console(*tuple(self.get(name)))
else:
raise AttributeError
if __name__ == '__main__':
CONSOLES = Consoles()
print(CONSOLES.names())
print(CONSOLES.get('tty0'))
print(CONSOLES.tty0.operations)
print(CONSOLES.tty0.flags)
print(CONSOLES.tty0.maj... |
JeroenBosmans/nabu | nabu/neuralnetworks/trainers/cost_features_rec.py | Python | mit | 1,705 | 0.002346 | '''@file cross_enthropytrainer_rec.py
contains the CrossEnthropyTrainerRec for reconstruction of the audio samples'''
import tensorflow as tf
import trainer
from nabu.neuralnetworks import ops
class CostFeaturesRec(trainer.Trainer):
'''A trainer that minimises the cross-enthropy loss, the output sequences
mus... | ength: the length of all the logit sequences as a tuple of
[batch_size] vectors
target_seq_length: the length of all the target sequences as a
tupple of two [batch_size] vectors, both for one of the elements
in the targets tupple
Returns:
... | return total_loss
|
abn/python-bugzilla | examples/query.py | Python | gpl-2.0 | 3,441 | 0.000872 | #!/usr/bin/env python
#
# 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. See http://www.gnu.org/copyleft/gpl.html for
# ... | = bzapi.build_query(
product="Fedora",
component="python-bugzilla",
include_fields=["id", "summary"])
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Quicker query processing time: %s" % (t2 - t1))
# bugzilla.redhat.com, and bugzilla >= 5.0 support queries using the same
# format as is ... | artner-bugzilla.redhat.com -> Search -> Advanced Search, select
# Classification=Fedora
# Product=Fedora
# Component=python-bugzilla
# Unselect all bug statuses (so, all status values)
# Under Custom Search
# Creation date -- is less than or equal to -- 2010-01-01
#
# Run that, copy the URL and bring it ... |
apertus-open-source-cinema/elmyra | src/python/lib/media.py | Python | gpl-3.0 | 974 | 0 | """Methods to set media related (resolution, length) scene properties"""
import bpy
def setup(animated, width, height, length):
"""
Sets up the type, resolution and length of the currently open scene
The render resolution of the scene is set, and additionally ...
... for stills, sets the length of... | .render.resolution_percentage = 100
bpy.context.scene.render.resolution_x = int(width)
bpy.context.scene.render.resolution_y = int(height)
if not animated:
bpy.context.scene.frame_end = 1
else:
bpy.context.scene.cycles.use_animated_seed = True
bpy.context.scene.frame_end = lengt... | s you know)
bpy.context.scene.render.fps_base = 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.