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 |
|---|---|---|---|---|---|---|---|---|
edx/edx-platform | openedx/core/djangoapps/user_authn/api/tests/test_views.py | Python | agpl-3.0 | 7,808 | 0.00269 | """
Logistration API View Tests
"""
from unittest.mock import patch
from urllib.parse import urlencode
import socket
import ddt
from django.conf import settings
from django.urls import reverse
from rest_framework.test import APITestCase
from common.djangoapps.student.models import Registration
from common.djangoapps.s... | elf.user)
result = self.client.login(username=self.user.username, password="test")
assert result, 'Could not log in'
self.path = | reverse('send_account_activation_email')
@patch('common.djangoapps.student.views.management.compose_activation_email')
def test_send_email_to_inactive_user_via_cta_dialog(self, email):
"""
Tests when user clicks on resend activation email on CTA dialog box, system
sends an activation em... |
litex-hub/fpga_101 | lab004/load.py | Python | bsd-2-clause | 105 | 0 | # | !/usr/bin/env python3
import os
os.system("djtgcfg prog -d Nexys4DDR -i 0 -f ./build/gateware/top.bit" | )
|
jtvaughan/calligraphy | fodtitalicsheets.py | Python | cc0-1.0 | 6,988 | 0.014024 | #!/usr/bin/env python3
# Combine SVG Images of Italic Practice Sheets into an OpenDocument Document
# Written in 2014 by Jordan Vaughan
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software ... | frame draw:style-name="fr1" draw:name="n{1}" text:anchor-type="paragraph" svg:width="{2}{4}" svg:height="{3}{4}" draw:z-index="0"><draw:image><office:binary-data>""".format(paragraph_style, imgno, imgwidth, imgheight, args.units))
data = None
try:
with open(path, "rb") as imgfile:
data = imgfile.read()
exc... | "unable to read " + path + ": " + e.strerror)
if data:
sys.stdout.write(str(base64.b64encode(data), encoding="UTF-8"))
sys.stdout.write("""</office:binary-data></draw:image></draw:frame></text:p>\n""")
for index, path in enumerate(args.sheetimage):
add_image(path, index, "Standard" if index is 0 else "P1")
... |
ukhas/habitat | habitat/tests/test_sensors/test_stdtelem.py | Python | gpl-3.0 | 4,262 | 0 | # Copyright 2011 (C) Daniel Richman
#
# This file is part of habitat.
#
# habitat 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.
#
# h... | "001:12", "12:002", "001:12:56", "04:42:005", "12:005:25",
"24:00", "25:00", "11:60", "11:62", "24:12:34", "35:12:34",
"12:34:66", "12:34:99", "126202", "1234567", "123"
]
for i in invalid_times:
self.check_invalid_time(i)
def test_coordinate(self):
coord... | ("ddmm.mm", "-3506.192", -35.1032),
("ddmm.mm", "03506.0", 35.1),
("ddd.dddddd", "+12.1234", 12.1234),
("dddmm.mmmm", "-3506.192", -35.1032),
("dddmm.mmmm", "-2431.5290", -24.5254833),
("dddmm.mmmm", "2431.529", 24.525483),
("dddmm.mmmm"... |
ternus/arcnet | cyber/pythonsudoku/check_modules.py | Python | gpl-2.0 | 644 | 0.00311 | # -*- coding: utf-8 -*-
"""Module to check modules existance.
This exports this booleans:
- has_reportlab -- True if reportlab is found
- has_PIL -- True if PIL is found
- has_pygtk -- True if pygtk is found
Copyright (C) 2005-2008 Xos | é Otero <xoseotero@users.sourceforge.net>
"""
__all__ = ["has_reportlab", "has_PIL", "has_pygtk"]
try:
import reportlab
has_reportlab = True
except ImportError:
has_reportlab = False
try:
import PIL
has_PIL = True
except:
has_PIL = False
try:
import pygtk
pygtk.require('2.0')
i... | has_pygtk = False
|
rloliveirajr/sklearn_transformers | trans4mers/feature_extraction/diff.py | Python | gpl-2.0 | 634 | 0 | import math
from .fingerprint import Fingerprint
class Diff(Fingerprint):
def trans_func_(self, row):
'' | '
F. Dong, Y. Chen, J. Liu, Q. Ning, and S. Piao, "A Calibration-free
localiztion solution for handling signal strength variance", in
MELT (Berlin, Heidelberg), pp. 79-90, Springer-Verlag, 2009
'''
values = row
features = []
for i in range(0, len(values)):
... | ge(0, len(values)):
if i == j:
continue
r = values[i] - values[j]
features.append(r)
return features
|
oujiaqi/suiyue | routes/setting.py | Python | apache-2.0 | 2,131 | 0.013429 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from base import BaseHandler
import os
import sys
sys.path.append('..')
from models.user import User
class ChangeHandler(BaseHandler):
def get(self):
uname = self.get_current_user()
user = User.get_user_by_name(uname)
error=""
if len(... | dy'])>max_size:
| error="图片太大"
self.render("change.html",error=error,user=user)
hpic = file_name+"."+ext
with open(save_dir+hpic,'wb') as up:
up.write(pic['body'])
User.change(user[0].uid,uname,password,profile,hpic,sex)
self.re... |
dnanexus/dx-toolkit | src/python/dxpy/ssh_tunnel_app_support.py | Python | apache-2.0 | 5,946 | 0.002691 | # Copyright (C) 2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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... | is will have the OS automatically
open the URL in the default web browser.
"""
if platform == "linux" or platform == "linux2":
cmd = ['xdg-open', cmd]
elif platform == "darwin":
cmd = ['open', cmd]
elif platform == "win32":
cmd = ['start', cmd]
subprocess.check_call(cmd)
... | tebook_app_versions():
"""
Get the valid version numbers of the notebook app.
"""
notebook_apps = dxpy.find_apps(name=NOTEBOOK_APP, all_versions=True)
versions = [str(dxpy.describe(app['id'])['version']) for app in notebook_apps]
return versions
def run_notebook(args, ssh_config_check):
""... |
CodeCatz/litterbox | Pija/LearnPythontheHardWay/ex17.py | Python | mit | 570 | 0.005263 | from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
# in | _file = open(from_file)
# indata = in_file.read()
indata = open(from_file).read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file, 'w')
out_file.write(in | data)
print "Alright, all done."
out_file.close()
# in_file.close() |
shawncaojob/LC | PY/4_median_of_two_sorted_arrays.py | Python | gpl-3.0 | 3,984 | 0.00753 | # 4. Median of Two Sorted Arrays My Submissions QuestionEditorial Solution
# Total Accepted: 94496 Total Submissions: 504037 Difficulty: Hard
# There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
# ... | lf_len = 0, m, (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
if i > 0 and j < n and nums1[i-1] > nums2 | [j]:
# i too big
imax = i - 1
elif j > 0 and i < m and nums2[j-1] > nums1[i]:
# j too big, i too small
imin = i + 1
else:
# i is perfect
if i == 0: max_of_left = nums2[j-1]
elif j == 0... |
hotfix-project/hotfix-api | api/migrations/0005_patch_md5sum.py | Python | mit | 456 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:14
from __future__ imp | ort unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0004_auto_20170824_0954'),
]
operations = [
migrations.AddField(
model_name='patch',
| name='md5sum',
field=models.CharField(default='', max_length=32),
),
]
|
siosio/intellij-community | python/testData/intentions/PyInvertIfConditionIntentionTest/commentsInlineIf_after.py | Python | apache-2.0 | 130 | 0.007692 | def func():
value = | "not-none"
if value is not None:
print("Not none")
else: | # Is none
print("None") |
RobinDavid/pystack | pystack/layers/udp_application.py | Python | gpl-3.0 | 6,311 | 0.006655 | # -*- coding: utf-8 -*-
'''
Author: Robin David
License: GNU GPLv3
Repo: https://github.com/RobinDavid
Copyright (c) 2012 Robin David
PyStack 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 ... | elt = self.data[0]
s = self.data[0][2][:size]
self.data[0] = (self.data[0][0], self.data[0][1], self.data[0][2][size:])
elt = (elt[0], elt[1], s)
else:
| elt = self.data.pop(0)
else:
elt = self.data.pop(0)
self.mutex.release()
return elt
#Methods added to help pysocket
def get_conn_addr(self):
"""Return tuple of the remote IP remote port"""
return (self.remoteIP, self.remotePort)
def get... |
RetailMeNotSandbox/dart | src/python/dart/trigger/scheduled.py | Python | mit | 11,491 | 0.003568 | import json
import logging
import boto3
import hashlib
import jsonpatch
from dart.context.locator import injectable
from dart.model.trigger import Tr | iggerType, TriggerState
from dart.message.call import TriggerCall
from dart.trigger.base import TriggerProcessor, execute_trigger
from dart.model.exception import DartValidationException
_logger = logging.getLogger(__name__)
scheduled | _trigger = TriggerType(
name='scheduled',
description='Triggering from a scheduler',
params_json_schema={
'type': 'object',
'properties': {
'cron_pattern': {
'type': 'string',
'description': 'The CRON pattern for the schedule. See <a target="_blank... |
RDFLib/rdflib | rdflib/plugins/serializers/nt.py | Python | bsd-3-clause | 2,617 | 0.001146 | """
N-Triples RDF graph serializer for RDFLib.
See <http://www.w3.org/TR/rdf-testcases/#ntriples> for details about the
format.
"""
from typing import IO, Optional
from rdflib.graph import Graph
from rdflib.term import Literal
from rdflib.serializer import Serializer
import warnings
import codecs
__all__ = ["NTSeria... | de(l | _)
if l_.language:
if l_.datatype:
raise Exception("Literal has datatype AND language!")
return "%s@%s" % (encoded, l_.language)
elif l_.datatype:
return "%s^^<%s>" % (encoded, l_.datatype)
else:
return "%s" % encoded
def _quote_encode(l_):
return '"%s"' % ... |
svinota/cxnet | cxnet/zeroconf.py | Python | gpl-3.0 | 69,198 | 0.004393 | """ Multicast DNS Service Discovery for Python
Copyright (c) 2003, Paul Scott-Murphy
Copyright (c) 2008-2011, Peter V. Saveliev
This module provides a framework for the use of DNS Service Discovery
using IP multicast. It has been tested against the JRendezvous
implementation from <a href="http://s... | nused
_MAX_MSG_ABSO | LUTE = 8972
_FLAGS_QR_MASK = 0x8000 # query response mask
_FLAGS_QR_QUERY = 0x0000 # query
_FLAGS_QR_RESPONSE = 0x8000 # response
_FLAGS_AA = 0x0400 # Authorative answer
_FLAGS_TC = 0x0200 # Truncated
_FLAGS_RD = 0x0100 # Recursion desired
_FLAGS_RA = 0x8000 # Recursion available
_FLAGS_Z = 0x0040 # Zero
_FLAGS_AD =... |
willmcgugan/rich | examples/suppress.py | Python | mit | 489 | 0 | try:
import click
except ImportError:
print("Please install click for this example")
print(" pip install click")
exit()
from rich.traceback i | mport install
install(suppress=[click])
@click.command()
@click.option("--count", default=1, help="Number of greetings.")
def hello(count):
"""Simple program that greets NAME for a total of COUNT times."""
1 / 0
for x in range(count):
click.echo(f"Hello {na | me}!")
if __name__ == "__main__":
hello()
|
bsmedberg/socorro | socorro/unittest/external/postgresql/unittestbase.py | Python | mpl-2.0 | 3,375 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import socorro.database.database as db
from configman import ConfigurationManager, Namespace
from configman.converters i... | ='Hostname to connect to database',
)
required_config.add_option(
name='database_username',
default='breakpad_rw',
doc='Username to connect to databas | e',
)
required_config.add_option(
name='database_password',
default='aPassword',
doc='Password to connect to database',
)
required_config.add_option(
name='database_superusername',
default='test',
doc='Username to connect to database',
)
require... |
willkg/douglas | douglas/app.py | Python | mit | 37,546 | 0.000027 | # Python imports
import cgi
import locale
import logging
import os
import os.path
import sys
import time
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# Douglas imports
from douglas import __version__
from douglas import crashhandling
from douglas import plugin_utils
fr... | # Skip files that have extensions we don't know what to do
# with.
ext = os.path.splitext(mem)[1].lstrip('.')
if not ext in cfg['ex | tensions'].keys():
continue
# Get the mtime of the entry.
mtime = time.mktime(tools.filestat(self._request, mem))
# remove the datadir from the front and the bit at the end
mem = mem[len(datadir):mem.rfind('.')]
# This is the compiled file f... |
WZQ1397/automatic-repo | python/emailOps/sendemailWithFile.py | Python | lgpl-3.0 | 1,776 | 0.003759 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import enc | oders
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr
# 格式化邮件地址
def formatAddr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
def sendMail(body, attachment):
smtp_server = 'smtp.163.com'
from_mail = 'xxx@163.com'
mail_pass... | # Header对中文进行转码
msg['From'] = formatAddr('管理员 <%s>' % from_mail).encode()
msg['To'] = ','.join(to_mail)
msg['Subject'] = Header('监控', 'utf-8').encode()
# plain代表纯文本
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# 二进制方式模式文件
with open(attachment, 'rb') as f:
# MIMEBase表示附件的对象
... |
moreati/pylons | tests/test_units/__init__.py | Python | bsd-3-clause | 2,788 | 0.004663 | import json
import os
import sys
from unittest import TestCase
from urllib import quote_plus
from xmlrpclib import loads, dumps
data_dir = os.path.dirname(os.path.abspath(__file__))
try:
shutil.rmtree(data_dir)
except:
pass
cur_dir = os.path.dirname(os.path.abspath(__file__))
pylons_root = os.path.dirnam... | eq(self, method, args=None):
if args is None:
args = ()
ee = dict(CONTENT_TYPE='text/xml')
data = dumps(args, methodname=method)
self.response = response = self.app.post('/', params = data,
extra_environ=ee)
return load... | ance(args, dict))
ee = dict(CONTENT_TYPE='application/json')
data = json.dumps(dict(id='test',
method=method,
params=args))
self.response = response = self.app.post('/', params=quote_plus(data),
... |
jreese/ircstat | ircstat/defaults.py | Python | mit | 4,274 | 0.000936 | # Copyright 2013 John Reese
# Licensed under the MIT license
######################
# Parsing options
######################
# the regex to parse data from irc log filenames.
# must contain two named matching groups:
# channel: the name of the channel
# date: the date of the conversation
filename_regex = r'(?P<ch... | suffixes
# values should be the primary nick to use in place of the aliased nick
# note: a large number of aliases may impact time spent parsing log files
aliases = {}
# l | ist of nicks, or regexes to match to nicks, that should be ignored
ignore = []
######################
# Graphing options
######################
# image format to use as output from matplotlib
image_format = 'png'
# enable matplotlib's XKCD mode, where graphs will look hand-drawn
xkcd_mode = True
# for time-series ... |
jwodder/ghutil | src/ghutil/cli/issue/lock.py | Python | mit | 179 | 0 | import click
from ghutil | .types import Issue
@click.command()
@Issue.a | rgument_list("issues")
def cli(issues):
"""Lock issues/PRs"""
for i in issues:
i.lock.put()
|
rabbitinaction/sourcecode | python/chapter-10/api_ping_check.py | Python | bsd-2-clause | 1,459 | 0.00891 | ###############################################
# RabbitMQ in Action
# Chapter 10 - RabbitMQ ping (HTTP API) check.
###############################################
#
#
# Author: Jason J. W. Williams
# (C)2011
###############################################
import sys, json, httplib, urllib, base64, socket
# | (apic.0) Nagios status codes
EXIT_OK = 0
EXIT_WARNING = 1
EXIT_CRITICAL = 2
EXIT_UNKNOWN = 3
#/(apic.1) Parse arguments
server, port = sys.argv[1].split(":")
vhost = sys.argv[2]
username = s | ys.argv[3]
password = sys.argv[4]
#/(apic.2) Connect to server
conn = httplib.HTTPConnection(server, port)
#/(apic.3) Build API path
path = "/api/aliveness-test/%s" % urllib.quote(vhost, safe="")
method = "GET"
#/(apic.4) Issue API request
credentials = base64.b64encode("%s:%s" % (username, password))
try:
conn... |
oemof/oemof_examples | oemof_examples/oemof.solph/v0.4.x/storage_investment/v2_invest_optimize_only_gas_and_storage.py | Python | gpl-3.0 | 6,369 | 0 | # -*- coding: utf-8 -*-
"""
General description
-------------------
This example shows how to perform a capacity optimization for
an energy system with storage. The following energy system is modeled:
input/output bgas bel
| | | |
| ... | invest_relation_output_capacity=1 / 6,
inflow_conversion_factor=1,
outflow_conversion_factor=0.8,
investment=solph.Investment(ep_costs=epc_storage),
)
energysystem.add(excess, gas_resource, wind, pv, d | emand, pp_gas, storage)
##########################################################################
# Optimise the energy system
##########################################################################
logging.info("Optimise the energy system")
# initialise the operational model
om = solph.Model(energysystem)
# if... |
valtandor/easybuild-framework | test/framework/variables.py | Python | gpl-2.0 | 3,243 | 0.002158 | # #
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | BAR']), "0 1 2 10 11 20")
v.nappend_el('BAR', 30, idx= -2)
self.assertEqual(str(v), "{'BAR': [[0, 1, 2], [10, 11, 30], [20]]}")
| self.assertEqual(str(v['BAR']), '0 1 2 10 11 30 20')
v['FOO'] = range(3)
self.assertEqual(str(v['FOO']), "0,1,2")
v['BARSTR'] = 'XYZ'
self.assertEqual(v['BARSTR'].__repr__(), "[['XYZ']]")
v['BARINT'] = 0
self.assertEqual(v['BARINT'].__repr__(), "[[0]]")
v... |
jonasfoe/COPASI | copasi/bindings/python/unittests/Test_CCopasiObject.py | Python | artistic-2.0 | 4,243 | 0.036295 | # -*- coding: utf-8 -*-
# Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
# Properties, Inc., University of Heidelberg, and University of
# of Connecticut School of Medicine.
# All rights reserved.
# Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
# Properties, Inc., Universit... | jectType'
,'test_getObjectParent'
,'test_getCN'
,'test_isContainer'
,'test_isVector'
,'test_isMatrix'
,'test_isNameVector'
,'test_isReference'
,'test_isValueBool'
,'test_isValueInt'
,'test_isValueDbl'
,'test_isNonUniqueNa... | turn unittest.TestSuite(map(Test_CDataObject,tests))
if(__name__ == '__main__'):
unittest.TextTestRunner(verbosity=2).run(suite())
|
cevaris/pants | contrib/node/tests/python/pants_test/contrib/node/tasks/test_node_resolve_integration.py | Python | apache-2.0 | 1,125 | 0.003556 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... | sh(self):
command = ['resolve',
| 'contrib/node/examples/src/node/server-project']
pants_run = self.run_pants(command=command)
self.assert_success(pants_run)
def test_resolve_local_and_3rd_party_dependencies(self):
command = ['resolve',
'contrib/node/examples/src/node/web-project']
pants_run = self.run_pa... |
javiercantero/streamlink | src/streamlink/stream/hls_playlist.py | Python | bsd-2-clause | 10,407 | 0.000961 | import re
from binascii import unhexlify
from collections import namedtuple
from itertools import starmap
from streamlink.compat import urljoin, urlparse
__all__ = ["load", "M3U8Parser"]
# EXT-X-BYTERANGE
ByteRange = namedtuple("ByteRange", "range offset")
# EXT-X-KEY
Key = namedtuple("Key", "method uri iv key_fo... | ributes)
self.state["expect_playlist"] = True
elif line.startswith("#EXT-X-PLAYLIST-TYPE"):
self.m3u8.playlist_type = self.parse_tag(line)
elif line.st | artswith("#EXT-X-ENDLIST"):
self.m3u8.is_endlist = True
elif line.startswith("#EXT-X-MEDIA"):
attr = self.parse_tag(line, self.parse_attributes)
media = Media(self.uri(attr.get("URI")), attr.get("TYPE"),
attr.get("GROUP-ID"), attr.get("LANGUAGE"),
... |
hikelee/launcher | launcher/utils/common/auth_backends.py | Python | mit | 703 | 0.02276 | from __future__ import division,print_function,unicode_literals,with_statement
import logging
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
User=get_user_model()
class EmailBackend(ModelBackend):
def authenticate(self,username=None,password=None,**kwargs):
... | y:
user=User.objects.get(email=username)
if user.check_password(password):
return use | r
except (User.DoesNotExist,User.MultipleObjectsReturned):
logging.warning('Unsuccessful login attempt using username/email: {0}'.format(username))
return None
|
PaulSec/SPIPScan | spipscan.py | Python | mit | 16,919 | 0.000473 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import optparse
import sys
import requests
import re
from bs4 import BeautifulSoup
major_version = 0
intermediary_version = 0
minor_version = 0
folder_plugins = None
folder_themes = None
plugins = {}
# Detect the version of a SPIP install
# Version is in the header (f... | req = requests.get(url_to_visit, timeout=10)
# code for both status code 200/403
if req.status_code == 200 or req.status_code == 403:
if isForPlugins:
print("[!] Plugin folder is: %s" % folder)
| if req.status_code == 200:
opts.bruteforce_plugins_file = None
else:
print("[!] Theme folder is: %s" % folder)
if req.status_code == 200:
opts.bruteforce_themes_file = None
# code only for 200 (directory listing)
... |
ccqpein/Arithmetic-Exercises | Distribute-Coins-in-Binary-Tree/DCIBT.py | Python | apache-2.0 | 433 | 0.002309 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
class Solution:
def distributeCoins(self, root: TreeNode) -> int:
total = 0 |
def dfs(node):
| if not node:
return 0
L, R = dfs(node.left), dfs(node.right)
total += abs(L) + abs(R)
return node.val + L + R - 1
dfs(root)
return total
|
aktorion/bpython | bpython/test/test_args.py | Python | mit | 1,098 | 0 | import subprocess
import sys
import tempfile
from textwrap import dedent
from bpython import args
from bpython.test import FixLanguageTestCase as TestCase
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
from nose.plugins.attrib import attr
except ImportError:
def attr(func,... | sys.stderr.flush()"""))
f.flush()
p = subprocess.Popen(
[sys.executable, "-m", "bpython.curtsies", f.name],
stderr=subprocess.PIPE,
universal_newlines=True)
(_, stderr) = p.communicate()
self.assertEquals(stderr.strip()... | (SystemExit):
args.parse(['--version'])
|
globality-corp/microcosm-flask | microcosm_flask/operations.py | Python | apache-2.0 | 3,019 | 0.000994 | """
A naming convention and discovery mechanism for HTTP endpoints.
Operations provide a naming convention for references between endpoints,
allowing easy construction of | links or audit trails for external consumption.
"""
from collections import namedtuple
from enum import Enum, unique
# metadata for an operation
OperationInfo = | namedtuple("OperationInfo", ["name", "method", "pattern", "default_code"])
# NB: Namespace.parse_endpoint requires that operation is the second argument
NODE_PATTERN = "{subject}.{operation}.{version}"
EDGE_PATTERN = "{subject}.{operation}.{object_}.{version}"
@unique
class Operation(Enum):
"""
An enumerate... |
mbdevpl/maildaemon | maildaemon/_logging.py | Python | apache-2.0 | 760 | 0.002632 |
import logging
import logging.config
def configure_logging():
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'brief': {
| '()': 'colorlog.ColoredFormatter',
'style': '{',
'format': '{name} [{log_color}{levelname}{reset}] {message}'},
'precise': {'style': '{', 'format': '{asctime} {name} [{levelname}] {message}'}
},
'handlers': {
'console': {
| 'class': 'logging.StreamHandler', 'formatter': 'brief', 'level': logging.NOTSET,
'stream': 'ext://sys.stdout'}
},
'root': {'level': logging.WARNING, 'handlers': ['console']}
})
|
andresfcardenas/marketing-platform | userprofile/urls.py | Python | bsd-3-clause | 645 | 0 | #! /usr/bin/env python
# -*- coding: utf- | 8 -*-
from django.conf.urls import patterns
from django.conf.urls import url
urlpatterns = patterns(
'userprofile.views',
# login
url(
r'^ajax-login/$',
'ajax_login',
name='ajax_login',
),
# Ajax register
url(
r'^ajax-register/$',
'ajax_register',
... | _request',
),
# dashboard
url(
r'^dashboard/$',
'dashboard',
name='dashboard',
),
)
|
zsjohny/python-apt | setup.py | Python | gpl-2.0 | 1,759 | 0.010233 | #! /usr/bin/env python
# $Id: setup.py,v 1.2 2002/01/08 07:13:21 jgg Exp $
from distutils.core import setup, Extension
from distutils.sysconfig import parse_makefile
from DistUtilsExtra.command import *
import glob, os, string
# The apt_pkg module
files = map(lambda source: "python/"+source,
string.split(... | author_email="deity@lists.debian.org",
ext_modules=[apt_pkg,apt_inst],
packages=['apt', 'aptsources'],
data_files = [('share/python-apt/templates',
glob.glob('build/data/templates/*.info')),
('share/python-apt/templates',
glob.glob('data... | uild" : build_extra.build_extra,
"build_i18n" : build_i18n.build_i18n },
license = 'GNU GPL',
platforms = 'posix'
)
|
gquirozbogner/contentbox-master | third_party/requests_oauthlib/oauth1_session.py | Python | apache-2.0 | 12,076 | 0.001822 | from __future__ import unicode_literals
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from oauthlib.common import add_params_to_uri, urldecode
from oauthlib.oauth1 import SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER
import requests
from . import OAuth1
import sys
if ... | kwargs.items())
def fetch_request_token(self | , url, realm=None):
"""Fetch a request token.
This is the first step in the OAuth 1 workflow. A request token is
obtained by making a signed post request to url. The token is then
parsed from the application/x-www-form-urlencoded response and ready
to be used to construct an aut |
JuhaniImberg/DragonPy | dragonpy/core/configs.py | Python | gpl-3.0 | 4,067 | 0.003196 | # coding: utf-8
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __fu... | "]:
# raw_rom_cfg = cfg_dict["rom"]
# raise NotImplementedError("TODO: create rom cfg!")
# else:
self.rom_cf | g = self.DEFAULT_ROMS
if cfg_dict["trace"]:
self.trace = True
else:
self.trace = False
self.verbosity = cfg_dict["verbosity"]
self.mem_info = DummyMemInfo()
self.memory_byte_middlewares = {}
self.memory_word_middlewares = {}
def _get_initia... |
webgeodatavore/pyqgis-samples | gui/qgis-sample-QgsDualView.py | Python | gpl-2.0 | 314 | 0.003185 | # coding: utf-8
from qgis.gui import QgsDualView
from qgis.utils import iface
layer = iface.activeLayer()
canvas = iface.mapCanvas()
dv = QgsDualView()
dv.init(layer, canvas) # The active layer is a vector layer
dv.setView(QgsDualView.Attri | buteEditor) # It could be Qgs | DualView.AttributeTable instead
dv.show()
|
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/consumption/_client_factory.py | Python | mit | 1,308 | 0.000765 | # --------------------------------- | -----------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
def cf_c... | ure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.mgmt.consumption import ConsumptionManagementClient
return get_mgmt_service_client(cli_ctx, ConsumptionManagementClient)
def usage_details_mgmt_client_factory(cli_ctx, kwargs):
return cf_consumption(cli_ctx, **kwargs).usage_det... |
coderbone/SickRage-alt | tests/sickchill_tests/show/coming_episodes_tests.py | Python | gpl-3.0 | 3,730 | 0.002413 | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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 vers... | ': 'date',
'network': 'network',
'NetWork': 'network',
'show': 'show',
'Show': 'show',
}
for tests in test_cases, unicode_test_cases:
for (sort, result) in six.iteritems(tests):
self.assertEqual(ComingEpisodes._get_sort(sort), ... | estLoader().loadTestsFromTestCase(ComingEpisodesTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
|
emdodds/DictLearner | DictLearner.py | Python | mit | 16,189 | 0.000309 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 12:01:18 2015
@author: Eric Dodds
Abstract dictionary learner.
Includes gradient descent on MSE energy function as a default learning method.
"""
import numpy as np
import pickle
# the try/except block avoids an issue with the cluster
try:
import matp... | hape, pca)
self.Q = self.rand_dict()
def initialize_stats(self):
nunits = self.nunits
self.corrmatrix_ave = np.zeros((nunits, nunits))
s | elf.L0hist = np.array([])
self.L1hist = np.array([])
self.L2hist = np.array([])
self.L0acts = np.zeros(nunits)
self.L1acts = np.zeros(nunits)
self.L2acts = np.zeros(nunits)
self.errorhist = np.array([])
self.meanacts = np.zeros_like(self.L0acts)
def ... |
lmazuel/azure-sdk-for-python | azure-mgmt-web/azure/mgmt/web/models/proxy_only_resource.py | Python | mit | 1,493 | 0.00067 | # 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 ... | on import Model
class ProxyOnlyResource(Model):
"""Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.... | 'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'kind': {'key': 'kind', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
... |
luzheqi1987/nova-annotation | nova/tests/unit/api/openstack/compute/contrib/test_extended_virtual_interfaces_net.py | Python | apache-2.0 | 4,516 | 0.000443 | # Copyright 2013 IBM Corp.
# 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 app... | self.prefix]
def assertVIFs(self, vifs):
result = []
for net_id in self._get_net_id(vifs):
result.append(net_id)
sorted(result)
for i, net_uuid in enumerate(result):
self.assertEqual(net_uuid, EXPECTED_NET_UUIDS[i])
def test_get_extend_virtual_interface... | self.assertEqual(res.status_int, 200)
self.assertVIFs(self._get_vifs(res.body))
class ExtendedServerVIFNetSerializerTest(ExtendedServerVIFNetTest):
content_type = 'application/xml'
prefix = "{%s}" % extended_virtual_interfaces_net. \
Extended_virtual_interfaces_net.namespac... |
MediaKraken/MediaKraken_Deployment | source/common/common_logging_elasticsearch_httpx.py | Python | gpl-3.0 | 2,920 | 0.000342 | """
Copyright (C) 2020 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
... | hout even the imp | lied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fi... |
vmendez/DIRAC | DataManagementSystem/scripts/dirac-dms-replica-metadata.py | Python | gpl-3.0 | 1,519 | 0.044766 | #!/usr/bin/env python
########################################################################
# $HeadURL$
########################################################################
__RCSID__ = "$Id$"
from DIRAC import exit as DIRACExit
from DIRAC.Core.Base import Script
Script.setUsageMessage( """
Get the gi... | s
args = Script.getPositionalArgs()
if not len( args ) == 2:
Script.showHelp()
DIRACExit( -1 )
else:
inputFileName = args[0]
storageElement = args[1]
if os.path.exists( inputFileName ):
inputFile = open( inputFileName, 'r' )
string = inputFile.read()
| lfns = [ lfn.strip() for lfn in string.splitlines() ]
inputFile.close()
else:
lfns = [inputFileName]
res = DataManager().getReplicaMetadata( lfns, storageElement )
if not res['OK']:
print 'Error:', res['Message']
DIRACExit( 1 )
print '%s %s %s %s' % ( 'File'.ljust( 100 ), 'Migrated'.ljust( 8 ), 'Cached'.ljus... |
Narrato/mongotron | test.py | Python | bsd-2-clause | 337 | 0.002967 |
import pymongo
import mongotron
conn = pymongo.Connection()
mongotron.GetConnectionManager().add_c | onnection(conn)
class Doc(mongotron.Document):
__db__ = 'test'
structure = {
'name': unicode,
'age': i | nt,
'events': [int]
}
d = Doc()
d.age = 103
#d.age = "dave"
d.save()
pprint((d))
print d.age
|
RackHD/RackHD | test/stream-monitor/sm_plugin/stream_monitor.py | Python | apache-2.0 | 8,487 | 0.001178 | """
Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved.
"""
import logging
import os
from nose.plugins import Plugin
from stream_sources import LoggingMarker, SelfTestStreamMonitor, AMQPStreamMonitor, SSHHelper
import sys
from nose.pyversion import format_exception
from nose.plugins.xunit import... | _stderr:
value = self.__current_stderr.getvalue()
if value:
return value
return ''
def startContext(self, context):
self.__start_capture()
def stopContext(self, context):
self.__end_capture()
def addError(self, test, err):
"""
... |
logging to record all this stuff about the error.
Note: since 'errors' are related to _running_ the test (vs the
test deciding to fail because of an incorrect value), we asking
logging to record it as an error.
"""
if issubclass(err[0], SkipTest):
# Nothing ... |
cloudera/hue | desktop/core/ext-py/cx_Oracle-6.4.1/samples/tutorial/solutions/type_converter.py | Python | apache-2.0 | 959 | 0.009385 | #------------------------------------------------------------------------------
# type_converter.py (Section 6.2)
#----------------------------------------------------------------------- | -------
#------------------------------------------------------------------------------
# Copyright 2017, 2018, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
from __future__ import print_function
import cx_Oracle
import decimal
impo... | db_config
con = cx_Oracle.connect(db_config.user, db_config.pw, db_config.dsn)
cur = con.cursor()
def ReturnNumbersAsDecimal(cursor, name, defaultType, size, precision, scale):
if defaultType == cx_Oracle.NUMBER:
return cursor.var(str, 9, cursor.arraysize, outconverter = decimal.Decimal)
cur.outputtypeha... |
evernym/zeno | stp_zmq/test/test_node_to_node_quota.py | Python | apache-2.0 | 3,525 | 0.001135 | from copy import copy
import pytest
from plenum.common.stacks import nod | eStackClass
from plenum.common.util import randomString
from stp_core.loop.eventually import eventually
from stp_core.network.auth_mode import AuthMode
from stp_core.network.port_dispenser import genHa
from stp_core.test.helper import Printer, prepStacks, checkStacksConnected
from stp_zmq.kit_zstack import KITZStack
f... | f registry():
return {
'Alpha': genHa(),
'Beta': genHa(),
'Gamma': genHa(),
'Delta': genHa()
}
@pytest.fixture()
def connection_timeout(tconf):
# TODO: the connection may not be established for the first try because
# some of the stacks may not have had a remote yet (th... |
inflector/singnet | agent/examples/multi_agent_adapter/entity_extracter/__init__.py | Python | mit | 823 | 0 | #
# entity_extracter/__init__.py - demo agent service adapter...
#
# Copyright (c) 2017 SingularityNET
#
# Distributed under the MIT software license, see LICENSE file.
#
import logging
from sn_agent.job.job_descriptor import JobDescriptor
from sn_agent.service_adapter import ServiceAdapterABC
logger = logging.getLo... | file.write("entity:\n")
file.write(" pig\n")
| file.write(" farmer\n")
file.write(" tractor\n")
file.write(" cornfield\n")
|
hgn/hippod | tests/0303-same-object-default.py | Python | mit | 8,290 | 0.003378 | #!/usr/bin/python3
# coding: utf-8
import sys
import json
import requests
import pprint
import unittest
import string
import random
import os
import json
import time
import datetime
import base64
import uuid
import argparse
pp = pprint.PrettyPrinter(depth=6)
parser = argparse.ArgumentParser()
parser.add_argument('--... | t():
d = | ['passed']
return d[random.randint(0, len(d) - 1)]
def random_submitter():
d = ['anonym']
return d[random.randint(0, len(d) - 1)]
def query_full(id, sub_id):
url = 'http://localhost:8080/api/v1/object/{}/{}'.format(id, sub_id)
data = ''' '''
headers = {'Content-type': 'application/json', 'Acc... |
M4rtinK/anaconda | tests/unit_tests/pyanaconda_tests/modules/payloads/payload/test_image_installation.py | Python | gpl-2.0 | 4,138 | 0.000242 | #
# Copyright (C) 2021 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be... | ionProgressTestCase(unittest.TestCase):
"""Test the installation progress of the image installation."""
@p | atch("os.statvfs")
@patch_dbus_get_proxy_with_cache
def test_canceled_progress(self, proxy_getter, statvfs_mock):
"""Test the canceled installation progress."""
callback = Mock()
with tempfile.TemporaryDirectory() as sysroot:
os.mkdir(join_paths(sysroot, "/boot"))
... |
fedspendingtransparency/data-act-broker-backend | dataactcore/migrations/versions/224dac8f951c_merge_ee7bf_f6a9c.py | Python | cc0-1.0 | 581 | 0.006885 | """Merge ee7bff1d660c and f6a9c7e6694b
Revision ID: 224dac8f951c
Revises: ee7bff1d660c, f6a9c7e6694b
Create Date: 2018-03-30 09:56:19.308323
"""
# revis | ion identifiers, used by Alembic.
revision = '224dac8f951c'
down_revision = ('ee7bff1d660c', 'f6a9c7e6694b')
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgra... | ker():
pass
|
misli/django-domecek | domecek/admin/agegroup.py | Python | bsd-3-clause | 275 | 0.014545 | from __fut | ure__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
from django.contrib import admin
class AgeGroupAdmin(admin.ModelAdmin):
list_display = ('name', 'ord | er')
list_editable = ('order',)
|
epii/pyramid_airbrake | pyramid_airbrake/airbrake/submit.py | Python | mit | 3,343 | 0.000897 | from urlparse import urlparse
import logging
import urllib3
import pyramid_airbrake
log = logging.getLogger(__name__)
def create_http_pool(settings):
url = settings['notification_url']
maxsize = settings['threaded.threads'] # sort of a lie, potentially
timeout = settings['timeout']
if settings['us... | .data))
else:
log.error("Airbrake submission returned code '{0}', wich is not in "
"the Airbrake API spec. Very strange. | Error message: '{1}'"
.format(status, response.data))
return False
|
jslang/responsys | responsys/tests/test_client.py | Python | gpl-2.0 | 7,054 | 0.001701 | from time import time
import unittest
from unittest.mock import patch, Mock
from urllib.error import URLError
from suds import WebFault
from ..exceptions import (
ConnectError, ServiceError, ApiLimitError, AccountFault, TableFault, ListFault)
from .. import client
class InteractClientTests(unittest.TestCase):
... | oint')
@patch.object(client.InteractClient, 'connect', Mock())
def test_entering_context_calls_connect(self):
| self.assertFalse(self.interact.connect.called)
with self.interact:
self.assertTrue(self.interact.connect.called)
@patch.object(client.InteractClient, 'disconnect', Mock())
def test_leaving_context_calls_disconnect(self):
with self.interact:
self.assertFalse(self.int... |
bin3/toynlp | script/merge_dict_files.py | Python | apache-2.0 | 922 | 0.019523 | #!/usr/bin/env python
import sys
import argparse
from collections import defaultdict
from collections import Counter
def run(args):
dic = set()
wcnt = 0
for i, indict in enumerate(args.dicts):
print('Processing dict# %d: %s' % (i, indict))
with open(indict) as df:
for line in df:
dic.add(l... | different words' % (wcnt, len(dic)))
with open(args.dictf, 'w') as df:
for word in dic:
df.write(word + '\n')
if __name__ == '__main__':
print('------%s------' % sys.argv[0])
parser = argparse.ArgumentParser(description='Merge multiple dictionaries to one dictionary with unique words')
parser.add_ar... | args: %s' % args)
run(args)
|
Luxoft/SDLP2 | SDL_Core/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py | Python | lgpl-2.1 | 63,295 | 0.000063 | """SmartFactory code generator base.
Base of code generator for SmartFactory that provides SmartSchema object in
accordance with given internal model.
"""
# pylint: disable=W0402
# pylint: disable=C0302
import codecs
import collections
import os
import string
import uuid
from generator import Model
class GenerateE... | ng value with enum to string converting functions.
"""
if enums is None:
raise GenerateError("Enums is None")
return u"\n".join([self._enum_to_str_converter_template.substitute(
namespace=namespace,
enum=x.name,
mapping=self._indent_code(self._g... | string mapping code.
Generates part of source code with specific enum to string value
mapping.
Keyword arguments:
enums -- enum to generate string mapping.
namespace -- namespace to address enum.
Returns:
String value with enum to string mapping source code.
... |
prajnamort/LambdaOJ2 | main/migrations/0013_auto_20170821_1522.py | Python | mit | 719 | 0.001473 | # -*- coding: utf-8 -*-
# | Generated by Django 1.10.6 on 2017-08-21 07:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0012_auto_20170820_2355'),
]
operations = [
migrations.AddField(
model_name='pro... | field=models.BigIntegerField(default=0, verbose_name='通过次数'),
),
migrations.AddField(
model_name='problem',
name='submit_cnt',
field=models.BigIntegerField(default=0, help_text='只记录成功完成判题的提交', verbose_name='提交次数'),
),
]
|
gauthier-delacroix/Varnish-Cache | lib/libvcc/generate.py | Python | bsd-2-clause | 28,397 | 0.04342 | #!/usr/bin/env python3
#-
# Copyright (c) 2006 Verdens Gang AS
# Copyright (c) 2006-2015 Varnish Software AS
# All rights reserved.
#
# Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditio... | subject to change in
future versi | ons, you should avoid using it.
"""
),
('req.can_gzip',
'BOOL',
( 'client',),
( ), """
Does the client accept the gzip transfer encoding.
"""
),
('req.backend_hint',
'BACKEND',
( 'client', ),
( 'client',), """
Set bereq.backend to this if we attempt to fetch.
"""
),
('req.hash_ignore_busy',
... |
fullmooninu/tools | downloadQbitTorrentScripts.py | Python | gpl-3.0 | 515 | 0.01165 | # run with: python3 downloadQbitTorrentScripts.py | xargs wget
# then in qbitorrent you can go view -> search engine --> search plugins -> install a new one ->
# and select the good ones this got
import requests, re
from bs4 import BeautifulSoup
r = requests.get("https://github.com/qbittorrent/search-plugins/wiki/Un... | up.find_all(href=re.compile("\.py$"))
for l in python_scripts:
print(l.attrs.get("href | "))
|
bakie/Belphegor | roles/sabnzbd/molecule/default/tests/test_default.py | Python | mit | 860 | 0 | import pytest
def test_sabnzbd_group_exists(host):
assert host.group("sabnzbd").exists
def test_sabnzbd_user_exists(host):
assert host.user("sabnzbd").exists
@pytest.mark.parametrize("dir", [
"/opt/sabnzbd",
"/opt/sabnzbd/.sabnzbd",
"/opt/sabnzbd/incomplete",
"/opt/sabnzbd/complete",
"... | e/tv",
"/opt/sabnzbd/complete/movies",
"/ | opt/sabnzbd/complete/music",
"/opt/sabnzbd/nzb"
])
def test_dirs_exists(host, dir):
assert host.file(dir).is_directory
def test_sabnzbd_runs_as_sabnzbd_user(host):
file = host.file("/etc/default/sabnzbdplus")
assert file.contains("USER=sabnzbd")
def test_sabnzbd_is_running(host):
with host.sudo(... |
Alicimo/codon_optimality_code | legacy_code/latest_version/get_pdb.py | Python | gpl-2.0 | 730 | 0.050685 | #!/usr/bin/env python
#
# Provides simple functionallity to download pdb files using python.
# Returns the path to the downloaded file
import os, urllib2, gzip
def get_pdb(pdb_id):
fname = 'pdb/'+pdb_id+'.pdb'
| #check if pdb is | present
if os.path.exists(fname):
return fname
#check for pdb dir
if not os.path.exists('pdb/'):
os.makedirs('pdb')
#download pbd.gz
f = urllib2.urlopen("http://www.rcsb.org/pdb/files/"+pdb_id+".pdb.gz")
g = open(fname+'.gz','w')
while 1:
packet = f.read()
if not packet:
break
g.write(packet... |
ikerexxe/orderedFileCopy | configurationGui.py | Python | gpl-3.0 | 5,243 | 0.051879 | '''
' configurationGui.py
' Author: Iker Pedrosa
'
' License:
' This file is part of orderedFileCopy.
'
' orderedFileCopy 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 Lice... | , command = self.activateUsbName, variable = self.localUsbState, onvalue=1, offvalue=0)
self.checkboxUsb.grid(row = 0, column = 1)
self.textUsb = Text(below_frame, height = 1, width = 25, font = ("Helvetica", 11), state = "disabled")
self.textUsb.grid(row = 0, column = 2)
if globals.selectedUsbState == | 1:
self.textUsb.configure(state = "normal")
else:
self.textUsb.configure(state = "disabled")
self.textUsb.insert(END, globals.selectedUsbName)
#Buttons
self.buttonAccept = Button(bottom_frame, text = "Accept", command = self.accept)
self.buttonAccept.grid(row = 2, column = 0, padx = 25, pady = 20)
... |
eugenekolo/kololib | python/twilio_example.py | Python | mit | 541 | 0.005545 | #! /usr/bin/env python
"""Example of how to send text messages using Twilio
"""
import struct
from twilio.rest import TwilioRestClient
# Find these values at https://twilio.com/user/account
account_sid = "xxxx | "
auth_token = "xxxx"
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.creat | e(to="+17168301181", from_="+17162001181",
body="MSG FROM DOORHUB - ALERT, UNSCHEDULED ENTRY TO APARTMENT! REPLY 'ALARM' to sound alarm. Do not reply if this entry is expected.")
|
nikitanovosibirsk/district42 | tests/list/test_list_of_representation.py | Python | mit | 1,650 | 0 | from baby_steps import given, then, when
from district42 import represent, schema
def test_list_of_representation():
with given:
sch = schema.list(schema.bool)
with when:
res = represent(sch)
with then:
assert res == "schema.list(schema.bool)"
def test_list_of_values_represent... | st_of_min_max_len_representation():
with given:
sch = schema.list(schema.int).len(1, 10)
with when:
res = represent(sch)
with then:
assert res == "schema.list(schema.int).len( | 1, 10)"
|
klen/tweetchi | base/tweetchi/tweetchi.py | Python | bsd-3-clause | 8,042 | 0.00087 | from __future__ import absolute_import
from datetime import timedelta
from random import choice
from celery.schedules import crontab
from twitter import oauth_dance, Twitter, TwitterError, OAuth
from ..ext import cache, db
from .models import Status
from .signals import tweetchi_beat, tweetchi_reply
from .utils impo... | self.app.extensions = dict()
self.app.extensions['tweetchi'] = self
def beat(self):
" Send signal and psrse se | lf stack. "
updates = []
# Send updates
stack = self.stack
while stack:
message, params = stack.pop(0)
meta = params.pop('meta', None)
status = self.update(message, **params)
updates.append((status, meta))
# Clean queue
s... |
saturday06/FrameworkBenchmarks | frameworks/Python/web2py/compile_apps.py | Python | bsd-3-clause | 368 | 0.002717 | # | -*- coding: utf-8 -*-
import sys
import os
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'web2py')
sys.path = [path] + [p for p in sys.path if not p == path]
from gluon.compileapp import compile_application
compile_application(os.path.join(path, 'applications', 'standard'))
compile_application(os... | |
classicsc/syncthingmanager | syncthingmanager/tests/test_stman.py | Python | gpl-3.0 | 7,370 | 0.006106 | from unittest import TestCase
def device1_info(s):
cfg = s.system.config()
a = filter(lambda x: x['name'] == 'SyncthingManagerTestDevice1', cfg['devices'])
return a
def folder1_info(s):
cfg = s.system.config()
a = filter(lambda x: x['id'] == 'stmantest1', cfg['folders'])
return a
def test_de... | der1_info(s))
assert a['order'] == 'random'
assert b['order'] == 'alphabetic'
def test_folder_set_ignore_perms(s):
a = next(folder1_info(s))
s.folder_set_ignore_perms('stmantest1', True)
b = next(folder1_info(s))
assert not a['ignorePerms']
assert b['ignorePerms']
def test_folder_setup_ver... | antest1', 9)
b = next(folder1_info(s))
assert b['versioning'] == {'params': {'cleanoutDays': '9'}, 'type':
'trashcan'}
def test_folder_setup_versioning_simple(s):
a = next(folder1_info(s))
s.folder_setup_versioning_simple('stmantest1', 6)
b = next(folder1_info(s))
assert b['versioning']... |
google-research/google-research | task_set/tasks/fixed/fixed_mlp_ae_test.py | Python | apache-2.0 | 1,322 | 0.003782 | # 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... | verning permissions and
# limitations under the License.
"""Tests for task_set.tasks.fixed_mlp_ae_test."""
from absl.testing import parameterized
from task_set import registry
from task_set.tasks import family_test_utils
from task_set.tasks.fixed import fixed_mlp_ae # pylint: disable=unused-import
import tensorflow.... | _tasks(self):
task_names = registry.task_registry.get_all_fixed_config_names()
self.assertLen(task_names, 3)
@parameterized.parameters(registry.task_registry.get_all_fixed_config_names())
def test_tasks(self, task_name):
self.task_test(registry.task_registry.get_instance(task_name))
if __name__ == "_... |
bocchan/costly | public_goods_reg_noise/views.py | Python | bsd-3-clause | 793 | 0.006305 | # -*- coding: utf-8 -*-
from __future__ impo | rt division
from otree.common import Currency as c, currency_range, safe_json
from . import models
from ._builtin import Page, WaitPage
from .models import Constants
class Contribute(Page):
form_model = models.Player
| form_fields = ['contribution']
class ResultsWaitPage(WaitPage):
def after_all_players_arrive(self):
self.group.set_records()
class Punishment(Page):
form_model = models.Player
form_fields = ['punishment_p1', 'punishment_p2', 'punishment_p3']
class ResultsWaitPage2(WaitPage):
def afte... |
quantumlib/Cirq | cirq-core/cirq/ops/permutation_gate_test.py | Python | apache-2.0 | 2,986 | 0.001037 | # Copyright 2020 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 0b_101: 0b_101,
},
[2, 1, 0],
],
],
)
def test_permutation_gate_maps(maps, permutation):
qs = cirq. | LineQubit.range(len(permutation))
permutationOp = cirq.QubitPermutationGate(permutation).on(*qs)
circuit = cirq.Circuit(permutationOp)
cirq.testing.assert_equivalent_computational_basis_map(maps, circuit)
|
jaeilepp/mne-python | tutorials/plot_brainstorm_phantom_ctf.py | Python | bsd-3-clause | 4,215 | 0 | # -*- coding: utf-8 -*-
"""
=======================================
Brainstorm CTF phantom tutorial dataset
=======================================
Here we compute the evoked from raw for the Brainstorm CTF phantom
tutorial dataset. For comparison, see [1]_ and:
http://neuroimage.usc.edu/brainstorm/Tutorials/Phan... | e entire epoch
# when creating our evoked data. We also then crop to a single time point
# (@t=0) because this is a peak in our signal.
tmin = -0.5 / dip_ | freq
tmax = -tmin
epochs = mne.Epochs(raw, events, event_id=1, tmin=tmin, tmax=tmax,
baseline=(None, None))
evoked = epochs.average()
evoked.plot()
evoked.crop(0., 0.)
del raw, epochs
###############################################################################
# To do a dipole fit, let's use the... |
FabriceSalvaire/PyResistorColorCode | PyResistorColorCode/ConfigInstall.py | Python | gpl-3.0 | 1,206 | 0.003317 | ####################################################################################################
#
# PyResistorColorCode - Python Electronic Tools.
# Copyright (C) 2012 Salvaire Fabrice
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as... | ublic License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
""" This module defines configuration settings. """
#############################################################################... | ory = '/usr/share/PyResistorColorCode'
|
lem8r/woodwerk-addons | woodwerk/__manifest__.py | Python | agpl-3.0 | 936 | 0 | # -*- coding: utf-8 -*-
{
'name': 'Woodwerk Customizations',
'description': '''
Odoo Customization for Woodwerk Manufacturing''',
'author': 'ERP Ukraine',
'website': 'https://erp.co.ua',
'support': 'support@erp.co.ua',
'license': 'AGPL-3',
'category': 'Specific Industry Applicatio... | es',
'sale_stock',
'delivery',
'purchase',
'mrp',
'sale_mrp',
],
'data': [
'security/ir.model.access.csv',
'data/data.xml',
'views/sale_vi | ew.xml',
'views/res_partner_view.xml',
'views/templates.xml',
'views/po_templates.xml',
'views/purchase_view.xml',
'views/mrp_view.xml',
'views/mrp_templates.xml',
'views/product_view.xml',
'report/report_stock_forecast.xml',
],
}
|
CMUSV-VisTrails/WorkflowRecommendation | vistrails/packages/pythonCalcQt/__init__.py | Python | bsd-3-clause | 2,396 | 0.017947 | ###############################################################################
##
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistrib | ution 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 the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
... |
lvidarte/lai-server | laiserver/client.py | Python | gpl-3.0 | 2,247 | 0.008456 | # -*- coding: utf-8 -*-
# Author: Leo Vidarte <http://nerdlabs.com.ar>
#
# This file is part of lai-server.
#
# lai-server is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# lai-server is distribut... | c = json.loads(msg)
print doc['session_id' | ]
import time
time.sleep(9)
# Commit
doc['process'] = 'commit'
msg = json.dumps(doc)
enc = crypto.encrypt(msg, PUB_KEY)
data = base64.b64encode(enc)
try:
data = fetch(data)
except:
print "Fetch error"
else:
enc = base64.b64decode(data)
msg = ... |
chromakode/karmabot | karmabot/extensions/eightball.py | Python | bsd-3-clause | 1,155 | 0.038095 | # Copyright the Karmabot authors and contributors.
# All rights reserved. See AUTHORS.
#
# This file is part of 'karmabot' and is distributed under the BSD license.
# See LICENSE for more details.
from karmabot.core.facets import Facet
from karmabot.core.commands import CommandSet, thing
import random
predictions = ... | = "eightball"
commands = thing.add_child(CommandSet(name))
@classmethod
def does_attach(cls, thing):
return thing.name == "eightball"
@commands.add("shake {thing}", help="shake the magic eightbal | l")
def shake(self, thing, context):
context.reply(random.choice(predictions) + ".")
|
poppogbr/genropy | legacy_packages/develop/model/client.py | Python | lgpl-2.1 | 683 | 0.032211 | # encoding: utf-8
class Table(object):
def config_db(self, pkg):
tbl = pkg.table('client', name_short='Client', name_long='Client',name_plural='Clients',
pkey='id',rowcaption='company')
tbl.column('id',size='22',group='_',readOnly='y',name_long='Id')
self.sysFiel... | id=False)
tbl.column('card_id',size='22',name_long='!!Card id') # da decidere bene a cosa collegarlo
tbl.column('company',size=':30',name_long='!!Company') #in italia ragione sociale
tbl.column('address',name_long='!!Address')
tbl.c | olumn('phones','X',name_long='!!Phones')
tbl.column('emails',name_long='!!Emails')
|
Eyra-is/Eyra | Backend/server-interface/qc/scripts/create_wrong_prompts/createBadData.py | Python | apache-2.0 | 4,134 | 0.008224 | # Copyright 2016 The Eyra 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 applicable la... | m.choice(wordlist)
index = random.randint(0,len(ins))
ins.inse | rt(index, word)
newPrompts['ins'] = ins
# deletion (if prompt is more than 4 words), delete all but one word
if len(prompt) > 4:
dele = list(prompt)
for i in range(4):
index = random.randint(0,len(dele)-1)
del dele[index]
newPrompts['dele'] = dele
newPro... |
polyaxon/polyaxon | core/polyaxon/proxies/schemas/streams/base.py | Python | apache-2.0 | 1,940 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | hemas.gzip import get_gzip_config
from polyaxon.proxies.schemas.listen import get_list | en_config
from polyaxon.proxies.schemas.locations import get_streams_locations_config
from polyaxon.proxies.schemas.logging import get_logging_config
from polyaxon.proxies.schemas.streams.gunicorn import (
get_gunicorn_config,
get_k8s_auth_config,
)
from polyaxon.proxies.schemas.streams.k8s import get_k8s_root_... |
alexissmirnov/donomo | donomo_archive/lib/reportlab/graphics/charts/markers.py | Python | bsd-3-clause | 1,801 | 0.007218 | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.report | lab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/markers.py
"""
This modules defines a collection of markers used in charts.
T | he make* functions return a simple shape or a widget as for
the smiley.
"""
__version__=''' $Id: markers.py 2385 2004-06-17 15:26:05Z rgbecker $ '''
from reportlab.lib import colors
from reportlab.graphics.shapes import Rect, Line, Circle, Polygon
from reportlab.graphics.widgets.signsandsymbols import SmileyFace
def ... |
Jeebeevee/DouweBot_JJ15 | plugins_org/util/hook.py | Python | unlicense | 2,904 | 0.000344 | import inspect
import re
def _hook_add(func, add, name=''):
if not hasattr(func, '_hook'):
func._hook = []
func._hook.append(add)
if not hasattr(func, '_filename'):
func._filename = func.func_code.co_filename
if not hasattr(func, '_args'):
argspec = inspect.getargspec(func)
... | rgspec.defaults):
end if end else None])
if argspec.keywords:
args.append(0) # means kwargs present
func._args = args
if not hasattr(func, '_thread'): # does function run in its own thread?
func._thread = False
def sieve( | func):
if func.func_code.co_argcount != 5:
raise ValueError(
'sieves must take 5 arguments: (bot, input, func, type, args)')
_hook_add(func, ['sieve', (func,)])
return func
def command(arg=None, **kwargs):
args = {}
def command_wrapper(func):
args.setdefault('name', fu... |
decarlin/indra | indra/reach/reach_api.py | Python | bsd-2-clause | 3,264 | 0.003064 | import os
import json
import tempfile
import urllib, urllib2
import requests
from indra.java_vm import autoclass, JavaException
import indra.databases.pmc_client as pmc_client
from processor import ReachProcessor
def process_pmc(pmc_id):
xml_str = pmc_client.get_xml(pmc_id)
with tempfile.NamedTemporaryFile() ... | essor( | json_dict)
rp.get_phosphorylation()
rp.get_complexes()
return rp
if __name__ == '__main__':
rp = process_json_file('PMC0000001.uaz.events.json')
|
matthappens/taskqueue | taskqueue/ArchiveJobMessage.py | Python | mit | 716 | 0.036313 | from AmazonSQSMessage import AmazonSQSMessage
class ArchiveJobMessage (AmazonSQSMessage):
"""
Interface for an ArchiveJob message.
"""
def __init__ (self, name = None, bucket = None, destina | tionBucket = None | , filePath = None, destinationPath = None):
"""
Initializes the message and validates the inputs.
"""
# Init the generic message
super(ArchiveJobMessage, self).__init__(name = name, bucket = bucket, destinationBucket = destinationBucket, filePath = filePath, destinationPath = des... |
domguard/django-admin-tools | admin_tools/menu/views.py | Python | mit | 3,362 | 0.007733 | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.contrib import messages
try:
from django.views.decorators.csrf import csrf_e... | rect(request.POST.get('next'))
return HttpResponse('Deleted')
return render_to_response('admin_tools/menu/add_bookmark_form.html',
RequestContext(request, {
'url': request.POST.get('next'),
'title': | '**title**' #This gets replaced on the javascript side
}))
return render_to_response('admin_tools/menu/delete_confirm.html',
RequestContext(request, {
'bookmark': bookmark,
'title': 'Delete Bookmark',
}))
|
vienin/vlaunch | src/createrawvmdk.py | Python | gpl-2.0 | 3,765 | 0.009296 | #!/usr/bin/env python
# UFO-launcher - A multi-platform virtual machine launcher for the UFO OS
#
# Copyright (c) 2008-2009 Agorabox, Inc.
#
# This 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 versi... | block_count = 1
vmdk_file = open(target_path, 'a')
# write header
if partitions == {}:
t = "fullDevice"
else:
t = "partitionedDevice"
vmdk_file.write(string.Template(vmdk_header_template).substitute(type = t))
# write device infos
if partitions == {}:
vmdk_file... | opy partition table
open(partition_table_target_path, "ab").write(open(device_name, "rb").read(512 * mbr_block_count))
# iterate on device partitions
vmdk_file.write("RW " + str(mbr_block_count) + " FLAT \"" + os.path.basename(partition_table_target_path) + "\"\n")
current_part = 1
... |
tanyaschlusser/chipy.org | chipy_org/apps/meetings/feeds.py | Python | mit | 1,268 | 0.003943 | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... | return 'ChiPy Meeting'
| |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatter3d/error_x/_width.py | Python | mit | 438 | 0.002283 | import _plotly_utils.basevalidators
class WidthValidator(_plotly_utils.basev | alidators.NumberValidator):
def __init__(self, pl | otly_name="width", parent_name="scatter3d.error_x", **kwargs):
super(WidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
min=kwargs.pop("min", 0),
**kwargs
)
|
georgecpr/openthread | tests/scripts/thread-cert/Cert_6_1_01_RouterAttach.py | Python | bsd-3-clause | 4,851 | 0.000825 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | PARENT_REQUEST)
self.assertEqual(0x02, msg.mle.aux_sec_hdr.key_id_mode)
msg.assertSentWithHopLimit | (255)
msg.assertSentToDestinationAddress("ff02::2")
msg.assertMleMessageContainsTlv(mle.Mode)
msg.assertMleMessageContainsTlv(mle.Challenge)
msg.assertMleMessageContainsTlv(mle.ScanMask)
msg.assertMleMessageContainsTlv(mle.Version)
scan_mask_tlv = msg.get_mle_message_tlv... |
martin-craig/Airtime | python_apps/media-monitor2/tests/test_config.py | Python | gpl-3.0 | 876 | 0.01484 | # -*- coding: utf-8 -*-
import unittest
import pprint
from media.monitor.config import MMConfig
from media.monitor.exceptions import NoConfigFile, ConfigAccessViolation
pp = pprint.PrettyPrinter(indent=4)
class TestMMConfig(unittest.TestCase):
def setUp(self):
self.real_config = MMConfig("./test_config.c... | nt(self.real_config.cfg.dict)
def test_bad_config(self):
self.assertRaises( NoConfigFile, lambda : MMConfig("/fake/stuff/here") )
def test_no_set(self):
def myf(): self.real_config['bad'] = 'change'
self.assertRaises( ConfigAccessViolation, myf )
def test_copying(self):
k ... | f.assertTrue( len(mycopy) , len(self.real_config[k]) + 1 )
if __name__ == '__main__': unittest.main()
|
necaris/python3-openid | examples/consumer.py | Python | apache-2.0 | 19,199 | 0.000833 | #!/usr/bin/env python
"""
Simple example for an OpenID consumer.
Once you understand this example you'll know the basics of OpenID
and using the Python OpenID library. You can then move on to more
robust examples, and integrating OpenID into your application.
"""
__copyright__ = 'Copyright 2005-2008, Janrain, Inc.'
f... | self.render(
'Enter an OpenID Identifier to verify.',
css_class='error',
| form_contents=openid_url)
return
immediate = 'immediate' in self.query
use_sreg = 'use_sreg' in self.query
use_pape = 'use_pape' in self.query
use_stateless = 'use_stateless' in self.query
oidconsumer = self.getConsumer(stateless=use_stateless)
try:
... |
linvictor88/vse-lbaas-driver | quantum/plugins/services/agent_loadbalancer/drivers/vedge/vselb.py | Python | apache-2.0 | 7,013 | 0.006987 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack LLC.
# 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/... | lf.extract_monitorids(monitors)
old_vsemonitor_maps = self.extract_vsemonitor_maps()
monitor_vseids_update,monitor_vseids_delete = self.ini2monitorvseids(monitor_ids, old_vsemonitor_maps)
#try:
if monitors is not None:
| monitor_vseids,monitors_request = self.vselbapi.update_monitors(monitors, old_vsemonitor_maps,
monitor_ids, monitor_vseids_update,
monitor_vseids_delete, pool_vseid)... |
0todd0000/spm1d | spm1d/examples/nonparam/1d/ex_cca.py | Python | gpl-3.0 | 860 | 0.038372 |
import numpy as np
import matplotlib.pyplot as plt
import spm1d
#(0) Load dataset:
dataset = spm1d.data.mv1d.cca.Dorn2012()
y,x = dataset.get_data() #A:slow, B:fast
#(1) Conduct non-parametric test:
np.random.seed(0)
alpha | = 0.05
two_tailed = False
snpm = spm1d.stats.nonparam.cca(y, x)
snpmi = snpm.inference(alpha, iterations=100)
print( snpmi )
#(2) Compare with parametric result:
spm = spm1d.stats.cca(y, x)
spmi = spm.inference(alpha)
print( spmi )
#(3) Plot
plt.close('all')
plt.figure(figsize=(10,4))... | Non-parametric'
for ax,zi,label in zip([ax0,ax1], [spmi,snpmi], labels):
zi.plot(ax=ax)
zi.plot_threshold_label(ax=ax, fontsize=8)
zi.plot_p_values(ax=ax, size=10)
ax.set_title( label )
plt.tight_layout()
plt.show()
|
topaz1874/srvup | src/billing/migrations/0004_usermerchantid.py | Python | mit | 813 | 0.00246 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('billing', '0003_auto_20160816_1429'),
]
operations = [
migrations.CreateModel(
name='UserMerchantID',
fields=[
('id', models.AutoField(verbo... | ('customer_id', models.CharField(max_length=120)),
('merchant_name', models.CharField(default=b'Braintree', max_length=120)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
],
),
]
|
phaustin/timetable | test_timestamp.py | Python | mit | 3,015 | 0.018905 | from __future__ import print_function, unicode_literals
import site,os
home_dir=os.getenv('HOME')
site.addsitedir('{}/repos/pythonlibs'.format(home_dir))
from pyutils.compat import PY2
from dateutil.parser import parse
import time
import datetime, pytz
from math import floor
def build_rfc3339_phrase(datetime_obj):
... | else:
# Append: decimal, 6-digit uS, -/+, hours, minutes
datetime_phrase += ('%s%02d:%02d' % (
('-' if seconds < 0 else '+'),
abs(int(floor(secon | ds / 3600))),
abs(seconds % 3600)
))
return datetime_phrase
if PY2:
from rfc3339 import rfc3339
EPOCH = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
def timestamp(dt):
"""
given datetime object in utc
return unix timestamp
"""
... |
astrofrog/glue-vispy-viewers | glue_vispy_viewers/volume/layer_state.py | Python | bsd-2-clause | 1,889 | 0.001059 | from __future__ import absolute_import, division, print_function
from glue.core import Subset
from glue.external.echo import (CallbackProperty, SelectionCallbackProperty,
delay_callback)
from glue.core.state_objects import StateAttributeLimitsHelper
from glue.core.data_combo_helper impo... | a')
limits_cache = CallbackProperty({})
def __init__(self, layer=None, **kwargs):
super(VolumeLayerState, se | lf).__init__(layer=layer)
if self.layer is not None:
self.color = self.layer.style.color
self.alpha = self.layer.style.alpha
self.att_helper = ComponentIDComboHelper(self, 'attribute')
self.lim_helper = StateAttributeLimitsHelper(self, attribute='attribute',
... |
mbohlool/client-python | kubernetes/test/test_v1beta1_user_info.py | Python | apache-2.0 | 953 | 0.003148 | # coding: utf- | 8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
... | lient
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1beta1_user_info import V1beta1UserInfo
class TestV1beta1UserInfo(unittest.TestCase):
""" V1beta1UserInfo unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1beta1UserInfo(s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.