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 |
|---|---|---|---|---|---|---|---|---|
madongo/Intel-i-gent-Pet-Feeder | scan.py | Python | gpl-2.0 | 1,801 | 0.031094 | # /org/bluez/hci0/dev_18_7A_93_02_C5_A9
#address 18:7A:93:02:C5:A9
# Device 18:7A:93:02:C5:A9 UUIDs:
# 00001800-0000-1000-8000-00805f9b34fb
# 00001802-0000-1000-8000-00805f9b34fb
# 00001803-0000-1000-8000-00805f9b34fb
# 00001804-0000-1000-8000-00805f9b34fb
# 0000180a-0... | set_as_default=True)
bus = dbus.SystemBus()
bus.add_signal_receiver(print_rssi,
dbus_interfac | e = "org.freedesktop.DBus.Properties",
signal_name = "PropertiesChanged",
arg0 = "org.bluez.Device1",
path_keyword = "path")
bus.add_signal_receiver(property_changed,
dbus_interface = "org.bluez.Adapter1",
signal_name = "PropertyChanged")
mainloop = GObject.MainLoop()
mainloop.run() |
scop/bash-completion | test/t/test_pylint.py | Python | gpl-2.0 | 786 | 0 | import pytest |
class TestPylint:
@pytest.mark.complete("pylint --v", require_longopt=True)
def test_1(self, completion):
assert completion
@pytest.mark.complete("pylint --confidence=HIGH,")
def test_2(self, completion):
| assert completion
@pytest.mark.complete("pylint --help-msg=", require_longopt=True)
def test_all_message_ids(self, completion):
assert any("-" in x for x in completion)
@pytest.mark.complete("pylint --disable=", require_longopt=True)
def test_enabled_message_ids(self, completion):
ass... |
tetherless-world/satoru | search.py | Python | apache-2.0 | 152 | 0.013158 | import warnings as | __warnings
__warnings.warn("unqualified module names deprecated, use whyis.search", DeprecationWarning)
from w | hyis.search import *
|
openstack/mistral | mistral/lang/v2/actions.py | Python | apache-2.0 | 2,707 | 0 | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, 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
#
# Unl... | F ANY KIND, either express or implied.
# See the L | icense for the specific language governing permissions and
# limitations under the License.
from mistral.lang import types
from mistral.lang.v2 import base
from mistral_lib import utils
class ActionSpec(base.BaseSpec):
# See http://json-schema.org
_schema = {
"type": "object",
"properties"... |
leiferikb/bitpop-private | chrome/test/install_test/chrome.py | Python | bsd-3-clause | 3,017 | 0.002652 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Extended WebDriver interface that uses helper extension.
This file is makeshift and should eventually be switched over to
using the new ChromeDriver ... | WebDriver interface that uses helper extension."""
def __init__(self, url, desired_capabilities):
switches = desired_capabilities.get('chrome.switches', [])
switches += ['--load-extension=' + _EXTENSION]
desired_capabilities['chrome.switches'] = switc | hes
super(Chrome, self).__init__(url, desired_capabilities)
custom_commands = {
_CHROME_GET_VIEW_HANDLES:
('GET', '/session/$sessionId/chrome/views'),
}
self.command_executor._commands.update(custom_commands)
views = self.execute(_CHROME_GET_VIEW_HANDLES)['value']
self.set_s... |
LTKills/languages | python/15.py | Python | gpl-3.0 | 156 | 0.012821 | #Specia | l Numbers
import math
for i in range(1000, 10000):
a = str(i)
b, c = int(a[:2]), int(a[2:])
if(math.sqrt(i) == b+c): |
print (i)
|
MutsuGhost1/StudyGroupPython | hw1/look_folder_yield_2.py | Python | gpl-2.0 | 1,995 | 0.007519 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Administrator
#
# Created: 06/09/2013
# Copyright: (c) Administrator 2013
# Licence: <your licence>
#-----------------------------------------------------------------------------... | "Usage: python look_folder_recursive.py [full-path]"
else:
print "Usage: python look_folder_recursi | ve.py [full-path]"
if __name__ == '__main__':
main()
|
FedoraScientific/salome-paravis | test/VisuPrs/IsoSurfaces/A0.py | Python | lgpl-2.1 | 1,507 | 0.002654 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library ... | You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
# This case correspond... | sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
import pvserver as paravis
# Create presentations
myParavis = paravis.myParavis
# Directory for saving snapshots
picturedir = get_picture_dir("IsoSurfaces/A0")
file = datadir + "fra.med"
print "... |
larrybradley/astropy-helpers | astropy_helpers/sphinx/conf.py | Python | bsd-3-clause | 11,881 | 0.002525 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# Astropy shared Sphinx settings. These settings are shared between
# astropy itself and affiliated packages.
#
# Note that not all possible configuration values are present in this file.
#
# All configuration values have a defau... | on.
#html_theme_options = {}
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# I | f true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# |
BeyondTheClouds/nova | nova/tests/unit/compute/test_resource_tracker.py | Python | apache-2.0 | 57,954 | 0.000466 | # Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licen | sed 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.
"""Tests for compute resource tracking."... |
BGmi/BGmi | tests/test_data_source.py | Python | mit | 1,562 | 0.001295 | import pytest
from bgmi.lib.fetch import DATA_SOURCE_MAP
from bgmi.website import mikan
from bgmi.website.base import BaseWebsite
from bgmi.website.model import Episode, SubtitleGroup, WebsiteBangumi
@pytest.mark.parametrize("source", DATA_SOURCE_MAP.keys())
def test_info(source, data_source_bangumi_name):
w = D... | keys())
def test_search(source, data_source_bangumi_name):
w = DATA_SOURCE_MAP[source]()
search_result = w.search_by_keyword(data_source_bangumi_name[source][0], count=1)
assert search_result
for episode in search_result:
assert isinstance(episode, Episode)
def test_mikan_fetch_all_episode():
... | results = w.fetch_episode_of_bangumi("2242", ["34"])
assert len(results) > 15, "should fetch more episode in expand button"
|
WesleyPeng/uiXautomation | src/test/python/bpt/pages/binghomepage.py | Python | apache-2.0 | 1,210 | 0 | # Co | pyright (c) 2017-2018 {Flair Inc.} WESLEY PENG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m | ay 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 t... |
guildenstern70/pyfab | src/generators/pdfgenerator/loader.py | Python | mit | 4,301 | 0.00651 | """
FableGenerator
fablegenerator.loader.py
@author: Alessio Saltarin
"""
from generators import chapter, templateloader
import sys
import codecs
import os.path
import fablepage
import fableme.utils as utils
import logging
class SimpleLoader(templateloader.TemplateLoader):
def __init__(self, fable_id, l... |
def get_resources_path_to(self, filename):
filename = os.path.join(self._get_resources_path(), filename)
return utils.GoogleUtils.get_from_ | google(filename)
def get_template(self):
return self._template_file
def _read_file_template(self):
read_ok = True
try:
template_googlepath = self._get_resources_path_to(self._template['template_text_file'])
logging.debug('Reading from ' + template_go... |
Soovox/django-socialregistration | socialregistration/clients/__init__.py | Python | mit | 1,878 | 0.007455 | from django.conf import settings
USE_HTTPS = bool(getattr(settings, 'SOCIALREGISTRATION_USE_HTTPS', False))
class Client(object):
"""
Base class for OAuth/OpenID clients. Subclasses must implement all the
methods.
"""
def is_https(self):
"""
Check if the site is using HTTPS. ... | s should take in
acc | ount the value returned by ``self.is_https()``.
"""
raise NotImplementedError
def request(self, url, method="GET", params=None, headers=None, **kwargs):
"""
Make signed requests against ``url``. Signing method depends on the
protocol used.
:param url: The API e... |
possoumous/Watchers | seleniumbase/fixtures/email_manager.py | Python | mit | 17,901 | 0.000056 | """
EmailManager - a helper class to login, search for, and delete emails.
"""
import email
import htmlentitydefs
import imaplib
import quopri
import re
import time
import types
from seleniumbase.config import settings
class EmailManager:
""" A helper class to interface with an Email account. These imap methods
... | ""
return self.search(timeout=timeout,
c | ontent |
maxalbert/blaze | blaze/expr/expressions.py | Python | bsd-3-clause | 22,980 | 0.000218 | from __future__ import absolute_import, division, print_function
from keyword import iskeyword
import re
import datashape
from datashape import dshape, DataShape, Record, Var, Mono, Fixed
from datashape.predicates import isscalar, iscollection, isboolean, isrecord
import numpy as np
from odo.utils import copydoc
impo... | )
False
>>> isvalid_identifier(None)
False
"""
# the re module compiles and caches regexs so no need to compile it
return (s is not None and not iskeyword(s) and
re.match(r'^[_a-zA-Z][_a-zA-Z0-9]*$', s) is not None)
def valid_identifier(s):
"""Rewrite a string to be a val | id identifier if it contains
>>> valid_identifier('hello')
'hello'
>>> valid_identifier('hello world')
'hello_world'
>>> valid_identifier('hello.world')
'hello_world'
>>> valid_identifier('hello-world')
'hello_world'
>>> valid_identifier(None)
>>> valid_identifier('1a')
"""
... |
andymiller/flecks | examples/st_lgcp_mix_examples.py | Python | mit | 6,575 | 0.025551 | import pylab as plt
import numpy as np
from lgcp.examples.util import gen_synthetic_data
from lgcp.st_mix_lgcp import SpatioTemporalMixLGCP
#def st_lgcp_mix_examples_1d():
if __name__=="__main__":
""" Very simple 1d space example """
np.random.seed(100)
# example parameters and sythetic data
xdim = 1
... | 0].scatter(data[:,0], data[:,1], marker='.')
axarr[2,0].set_title("observed point process")
axarr[2,0].set_xlabel('X space')
a | xarr[2,0].set_ylabel("TIME")
axarr[2,0].set_xlim(xbbox[0])
axarr[2,0].set_ylim(tbbox/2)
fig.tight_layout()
#
# fit model
#
train_data = data[ data[:,1] < tbbox[1]/2 ] #grab
K = 2
dim = 1
#xgrid_dims = xgrid_dims # downsample space and time
#tgrid_dims = tgrid_dims
#tbb... |
msneddon/narrative | src/biokbase/narrative/handlers/authhandlers.py | Python | mit | 4,088 | 0.002446 | """
KBase handlers for authentication in the Jupyter notebook.
"""
__author__ = 'Bill Riehl <wjriehl@lbl.gov>'
from tornado.escape import url_escape
from notebook.base.handlers import IPythonHandler
from traitlets.config import Application
from notebook.auth.login import LoginHandler
from notebook.auth.logout import L... | on"
class KBaseLoginHandler(LoginHandler):
"""KBase-specific login handler.
This should get the cookie and put it where it belongs.
A (not-so-distant) future version will return a session token.
"""
def get(self):
"""
Initializes the KBase session from the c | ookie passed into it.
"""
cookie_regex = re.compile('([^ =|]+)=([^\|]*)')
client_ip = self.request.remote_ip
http_headers = self.request.headers
ua = http_headers.get('User-Agent', 'unknown')
# save client ip in environ for later logging
kbase_env.client_ip = cl... |
chenzheng128/ns-3-dev-git | src/dsdv/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 525,693 | 0.015264 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | ns3::AttributeConstructionList'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buff... | twork')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.net... |
tysonholub/twilio-python | twilio/rest/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/auth_registrations_credential_list_mapping.py | Python | mit | 17,559 | 0.003816 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... | so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
... | records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.... |
marratj/ansible | test/units/modules/network/netscaler/test_netscaler_servicegroup.py | Python | gpl-3.0 | 22,813 | 0.00114 |
# Copyright (c) 2017 Citrix Systems
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | e=servicegroup_proxy_mock)
servicegroup_exists_mock = Mock(side_effect=[True, True])
servicegroup_identical_mock = Mock(side_effect=[False, True])
monitor_bindings_identical_mock = Mock(side_effect=[True, True])
| with patch.multiple(
'ansible.modules.network.netscaler.netscaler_servicegroup',
ConfigProxy=m,
servicegroup_exists=servicegroup_exists_mock,
servicegroup_identical=servicegroup_identical_mock,
monitor |
ioggstream/mysql-utilities | mysql/fabric/services/resharding.py | Python | gpl-2.0 | 35,111 | 0.003589 | #
# Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
#
# 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; version 2 of the License.
#
# This program is distributed in the hope ... | s.Event("SETUP_RESHARDING_SWITCH")
PRUNE_SHARDS = _events.Event("PRUNE_SHARDS")
class MoveShardServer(ProcedureShard):
"""Move the shard represented by the shard_id to the destination group.
By default this operation takes a backup, restores it on the destination
group and guarantees that source and destin... | are synchronized
before pointing the shard to the new group. If users just want to update
the state store and skip these provisioning steps, the update_only
parameter must be set to true.
"""
group_name = "sharding"
command_name = "move_shard"
def execute(self, shard_id, group_id, update_on... |
TaliesinSkye/evennia | src/objects/migrations/0020_remove_old_attr_value_field.py | Python | bsd-3-clause | 8,327 | 0.007686 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'ObjAttribute.db_value'
db.delete_column('objects_objattribute', 'db_value')
db.ren... | ls.fields.TextField', [], {}),
'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'players.playerdb': {
'Met... | [], {'max_length': '255', 'null': 'True'}),
'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'db_is_connected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'db_key': ('django.db.models.fields.CharFiel... |
cyplp/botanik | paulla.ircbot/docs/source/conf.py | Python | bsd-3-clause | 10,828 | 0.00628 | # -*- coding: utf-8 -*-
#
# paulla.ircbot documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 29 07:58:36 2014.
#
# 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.... | this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'paullaircbotdoc'
# -- Options for LaTeX output -----------... | 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, ... |
SnowOnion/CodeForcesLee | dp/testStackDepth.py | Python | mit | 146 | 0.054795 | ''' |
# Runtime:
python 2.7.3 (win)
# Result:
0
1
<...>
998
boom
'''
def f(n):
print | n
f(n+1)
try:
f(0)
except:
print 'boom' |
pyembed/pyembed-rst | setup.py | Python | mit | 2,816 | 0.00071 | # The MIT License(MIT)
# Copyright (c) 2013-2014 Matt Thomson
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mo... | lf.test_args = ['pyembed']
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main( | self.test_args)
sys.exit(errno)
setup(
name='pyembed-rst',
version='1.1.0',
author='Matt Thomson',
author_email='mattjohnthomson@gmail.com',
url='http://pyembed.github.io',
description='Python reStructuredText directive for embedding content using OEmbed',
long_description=open('REA... |
googleads/google-ads-python | google/ads/googleads/v8/services/services/campaign_criterion_simulation_service/transports/base.py | Python | apache-2.0 | 3,895 | 0.000513 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | your own client library.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
# If no credentials are provided, then determine the appropriate
# defaults | .
if credentials is None:
credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES)
# Save the credentials.
self._credentials = credentials
# Lifted into its own function so it can be stubbed out during tests.
self._prep_wrapped_messages(client_info)
def _p... |
samuelclay/NewsBlur | utils/archive/bootstrap_intel.py | Python | mit | 1,384 | 0.00289 | import sys
from mongoengine.queryset import OperationError
from mongoengine.errors import ValidationError
from apps.analyzer.models import MClassifierFeed
from apps.analyzer.models import MClassifierAuthor
from apps.analyzer.models i | mport MClassifierTag
from apps.analyzer.models import MClassifierTitle
for classifier_cls in [MClassifierFeed, MClassifierAuthor,
MClassifierTag, MClassifierTitle]:
print(" ================================================================= ")
print((" Now on %s " % class... | ")
classifiers = classifier_cls.objects.filter(social_user_id__exists=False)
count = classifiers.count()
print((" ---> Found %s classifiers" % count))
for i, classifier in enumerate(classifiers):
if i % 1000 == 0:
print((" ---> %s / %s" % (i, count)))
sys.stdout.flush()
... |
great-expectations/great_expectations | great_expectations/rule_based_profiler/domain_builder/__init__.py | Python | apache-2.0 | 990 | 0.007071 | from great_expectations.rule_based_profiler.domain_builder.domain_builder import ( # isort:skip
DomainBuilder,
)
from great_expectations.rule_based_profiler.domain_builder.table_domain_builder import ( # isort:skip
TableDomainBuilder,
)
from great_expectations.rule_based_profiler.domain_builder.column_domain_... | isort:skip
ColumnDomainBuilder,
)
from great_expectations.rule_based_profiler.domain_builder.simple_column_suffix_domain_builder import ( # isort:skip
SimpleColumnSuffixDomainBuilder,
)
from great_expectations.rule_based_profiler.domain_builder.categorical_column_domain_builder import ( # isort:skip
Cate... | _builder import (
MapMetricColumnDomainBuilder,
)
from great_expectations.rule_based_profiler.domain_builder.simple_semantic_type_domain_builder import ( # isort:skip
SimpleSemanticTypeColumnDomainBuilder,
)
|
classcat/cc-prism-hids | main/pylib/ccprism/search.py | Python | gpl-3.0 | 23,411 | 0.00487 | """
/**
* Ossec Framework
*
* 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 t... | ck
from ossec_categories import global_categories
from ossec_formats import log_ca | tegories
from .view import View
class Search(View):
def __init__(self, request):
super().__init__()
self.request = request
self.html = ""
self.contents= ""
self.is_post = False
if request.method == 'POST':
self.is_post = True
self._make_con... |
macarthur-lab/xbrowse | deploy/docker/seqr/config/local_settings.py | Python | agpl-3.0 | 2,316 | 0.004318 | import os
import pymongo
import imp
# django stuff
reference_data_dir = '../data/reference_data'
#DEBUG = True
#COMPRESS_ENABLED = False
GENERATED_FILES_DIR = os.path.join(os.path.dirname(__file__), 'generated_files')
MEDIA_ROOT = os.path.join(GENERATED_FILES_DIR , 'media/')
DATABASES = {
'default': {
... | _DB = _conn['coverage']
READ_VIZ_BAM_PATH = 'https://broad-seqr'
READ_VIZ_CRAM_PATH = 'broad-seqr:5000'
READ_VIZ_USERNAME = "xbrowse-bams"
READ_VIZ_PASSWD = "xbrowse-bams"
ADMINS = [
('Ben Weisburd', 'weisburd@ | broadinstitute.org'),
('Hana Snow', 'hsnow@broadinstitute.org'),
] |
ambasta/mcmd | mcmd/config.py | Python | gpl-3.0 | 251 | 0 | GSD_BUS_NAME = 'org.gnome.SettingsDaemon.Power'
GSD_OBJ_PATH = '/org/gnome/SettingsDaemon/Power'
GSD_SCR_NAME = 'org.gnome.SettingsD | aemon.Power.Screen'
BRI_PRO_NAME = 'Brig | htness'
FD_PRO_IFACE = 'org.freedesktop.DBus.Properties'
BRIGHTNESS_S = 1.6875
|
0nse/WikiWho | scripts/dataAnalysis/BlockedAfDUserExtraction.py | Python | mit | 3,833 | 0.010447 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@author: Michael Ruster
Extract the timestamp and user of contributions which were authored before the
respecitve user had been blocked. The result can be further processed by
TimeframeCalculations.py.
Requirements: MediaWiki Utilities, WikiWho DiscussionParser
Usage: py... | p (XML, 7z, bz2…).')
parser.add_argument('-b', dest='blockLog', type=argparse.FileType('r') | ,
default=None, nargs='?',
help='Path to the block log file produced with 0nse/WikiParser (CSV).'),
args = parser.parse_args()
usersFile = '../data/blockedAfDUserNames_temp.pkl'
TimeframeCalculations.extractLastPostToBlockDeltas(usersOutputFile=usersFile)
# If you st... |
patrickwestphal/owlapy | owlapy/model/owldataintersectionof.py | Python | gpl-3.0 | 1,028 | 0 | from .owldatarangevisitor import OWLDataRangeVisitor, OWLDataRangeVisitorEx
from .owldatavisitor import OWLDataVisitor, OWLDataVisitorEx
from .owlnarydatarange import OWLNaryDataRange
from .owlobjectvisitor import OWLObjectVisitor, OWLObjectVisitorEx
from owlapy.util import accept_default, accept_default_ex
class OWL... | Of(OWLNaryDataRange):
"""TODO: implement"""
def __init__(self, operands):
"""
:param operands: a set of owlapy.model.OWLDataRange objects
"""
super().__init__(operands)
self._accept_fn_for_visitor_cls[OWLDataRangeVisitor] = accept_default
self._a | ccept_fn_for_visitor_cls[OWLDataRangeVisitorEx] = \
accept_default_ex
self._accept_fn_for_visitor_cls[OWLDataVisitor] = accept_default
self._accept_fn_for_visitor_cls[OWLDataVisitorEx] = accept_default_ex
self._accept_fn_for_visitor_cls[OWLObjectVisitor] = accept_default
self... |
dragorosson/heat | heat/db/sqlalchemy/migrate_repo/versions/064_raw_template_predecessor.py | Python | apache-2.0 | 1,809 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
fkey.drop()
tmpl_table.c.predecessor.drop()
def upgrade_sqlite(migrate_engine):
meta = sqlalchemy.MetaData()
meta.bind = migrate_engine
tmpl_table = sqlalchemy.Table('raw_template', meta, autoload=True)
ignorecols = [tmpl_table.c.predecessor.name]
new_template = migrate_utils.clone_table... | meta, ignorecols=ignorecols)
# migrate stacks to new table
migrate_utils.migrate_data(migrate_engine,
tmpl_table,
new_template,
skip_columns=['predecessor'])
|
bgpfu/bgpfu | src/bgpfu/prefixlist/simple.py | Python | apache-2.0 | 3,810 | 0.000262 | # Copyright (C) 2016 Matt Griswold <grizz@20c.com>
#
# This file is part of bgpfu
#
# 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... | refixListBase, collections.abc.MutableSequence):
"""
Simple PrefixList implemenatation using collections
*NOTE* loses prefix length info on aggregate
"""
def __init__(self, prefixes=None):
if prefixes:
self._prefixes = list(map(ipaddress.ip_network, list(map(str, prefixes))))
... | def insert(self, i, v):
self._prefixes.insert(i, self.check_val(v))
def iter_add(self, it):
for v in it:
self._prefixes.append(self.check_val(v))
def __delitem__(self, i):
del self._prefixes[i]
def __len__(self):
return len(self._prefixes)
def __eq__(s... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_generated_aiplatform_v1beta1_metadata_service_purge_executions_async.py | Python | apache-2.0 | 1,664 | 0.001803 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | aService_PurgeExecutions_async]
from google.cloud import aiplatform_v1beta1
async def sample_purge_executions():
# Create a client
client = aiplatform_v1beta1.MetadataServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.PurgeExecutionsRequest(
parent="parent_valu... | request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the response
print(response)
# [END aiplatform_generated_aiplatform_v1beta1_MetadataService_PurgeExecutions_async]
|
andyraib/data-storage | python_scripts/env/lib/python3.6/site-packages/pandas/io/tests/test_stata.py | Python | apache-2.0 | 56,765 | 0.000018 | # -*- coding: utf-8 -*-
# pylint: disable=E1101
import datetime as dt
import os
import struct
import sys
import warnings
from datetime import datetime
from distutils.version import LooseVersion
import nose
import numpy as np
import pandas as pd
import pandas.util.testing as tm
from pandas import compat
from pandas.co... | StataReader, InvalidColumnName,
PossiblePrecisionLoss, StataMissingValue)
from pandas.t | slib import NaT
from pandas.types.common import is_categorical_dtype
class TestStata(tm.TestCase):
def setUp(self):
self.dirpath = tm.get_data_path()
self.dta1_114 = os.path.join(self.dirpath, 'stata1_114.dta')
self.dta1_117 = os.path.join(self.dirpath, 'stata1_117.dta')
self.dta... |
DigitalCampus/django-ujjwal-oppia | oppia/viz/urls.py | Python | gpl-3.0 | 1,094 | 0.009141 | # oppia/viz/urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^summary/$', 'oppia.viz.views.summary_view', name="oppia_viz_summary"),
url(r'^user-registrations/$', 'oppia.viz.views.user_registrations_view', name="oppia_viz_use... | vity-by-country/$', 'oppia.viz.views.activity_by_country_view',
name="oppia_viz_activity_by_country"),
url(r'^course-activity/$', 'oppia.viz.views.course_activity_view', name="oppia_viz_course_activity"),
url(r'^course-downloads/$', 'oppia.viz.views.course_downloads_v | iew', name="oppia_viz_course_downloads"),
url(r'^method-mixes/$', 'oppia.viz.views.method_mixes_view', name="oppia_viz_method_mixes"),
url(r'^unique-repeat-clients/$', 'oppia.viz.views.clients_view', name="oppia_viz_clients"),
url(r'^films-for-method/$', 'oppia.viz.views.films_for_method_view', ... |
sametmax/Django--an-app-at-a-time | ignore_this_directory/ignore_me/views.py | Python | mit | 391 | 0 | # coding: utf-8
from _ | _future__ import unicode_literals
import re
import os
from django.shortcuts import render
from django.conf import settings
def index(request):
p = re.compile(r'^app\d+_')
apps = (a.split('_') for a in settings.INSTALLED_APPS if p.match(a))
return render(request, 'ignore_me/ind | ex.html',
{"apps": sorted(apps), "settings": settings})
|
barak/ninja | misc/ninja_syntax.py | Python | apache-2.0 | 5,166 | 0.002904 | #!/usr/bin/python
"""Python module for generating | .ninja files.
Note that this is emphatically not a required piece of Ninja; it's
just a helpful utility for build-file-generation systems that already
use Python.
"""
import textwrap
import re
def escape_path(word):
return word.replace('$ ','$$ ').replace(' ','$ ').replace(':', '$:')
class Writer(object):
... | for line in textwrap.wrap(text, self.width - 2):
self.output.write('# ' + line + '\n')
def variable(self, key, value, indent=0):
if value is None:
return
if isinstance(value, list):
value = ' '.join(filter(None, value)) # Filter out empty strings.
se... |
1337/yesterday-i-learned | leetcode/42h.py | Python | gpl-3.0 | 1,171 | 0 | from typing import List
# Scan left, scan right, subtract actual heights, sum them all up
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
left_heights = [0] * len(height)
right_heights = [0] * len(height)
left_max = 0
for idx,... | erate(reversed(height)):
idx = len(height) - flip - 1
right_heights[idx] = max(right_max, cur)
if cur > right_max:
right_max = cur
print(left_heights, right_heights)
mins = []
for idx, pairs in enumerate(zip( | left_heights, right_heights)):
mins.append(min(pairs) - height[idx])
print(mins)
return sum(mins)
a = Solution()
assert a.trap([4, 2, 3]) == 1
assert a.trap([1, 0, 1]) == 1
assert a.trap([1]) == 0
assert a.trap([2, 1, 2]) == 1
assert a.trap([0, 0, 0]) == 0
assert a.trap([0, 1, 0]) == 0
ass... |
karllessard/tensorflow | tensorflow/lite/testing/generate_examples_report.py | Python | apache-2.0 | 4,055 | 0.009618 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ite the main table and use onclick on the items that have log items.
fp.write("""
<body>
<h1>TOCO Conversion</h1>
<h2>%s</h2>
"" | " % title)
# Get a list of keys that are in any of the records.
param_keys = {}
for params, _ in reports:
for k in params.keys():
param_keys[k] = True
fp.write("<table>\n")
fp.write("<tr><td class='horiz'>\n")
fp.write("<div style='height:1000px; overflow:auto'>\n")
fp.write("<table>\n")
fp.... |
supercheetah/diceroller | pyinstaller/buildtests/import/test_app_with_plugins.py | Python | artistic-2.0 | 2,260 | 0 | #
# Copyright (C) 2012, Daniel Hyams
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed i... | tic plugin; the application might have
# | certain plugins that it always loads.
try:
print('Attempting to import static_plugin...')
mdl = __import__('static_plugin')
except ImportError:
raise SystemExit('Failed to import the static plugin.')
plugin_contents = """
print('DYNAMIC PLUGIN IMPORTED.')
print('This is some user-generated plugin that doe... |
levkar/odoo-addons | sale_multiple_invoice/wizard/__init__.py | Python | agpl-3.0 | 124 | 0 | # -*- c | oding: utf-8 -*-
import sale_make_invoice_advance
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftw | idth=4:
|
CivilNet/Gemfield | dockerfiles/py-faster-rcnn/files/gemfield/py-faster-rcnn/tools/train_svms.py | Python | gpl-3.0 | 13,475 | 0.000816 | #!/usr/bin/env python
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Train post-hoc SVMs using the algorithm and ... | roidb = self.imdb.roidb
num_images = len(roidb)
# num_images = 100
for i in range(num_images):
im = cv2.imread(self.imdb.image_path_at(i))
if roidb[i]['flipped']:
im = im[:, ::-1, :]
gt_inds = np.where(roidb[i]['gt_classes'] > 0)[0]
... | feat = self.net.blobs[self.layer].data
for j in range(1, self.imdb.num_classes):
cls_inds = np.where(roidb[i]['gt_classes'][gt_inds] == j)[0]
if len(cls_inds) > 0:
cls_feat = feat[cls_inds, :]
self.trainers[j].append_pos(cls_feat)
... |
Glottotopia/aagd | moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/action/fullsearch.py | Python | mit | 10,979 | 0.004099 | # -*- coding: iso-8859-1 -*-
"""
MoinMoin - fullsearch action
This is the backend of the search form. Search pages and print results.
@copyright: 2001 by Juergen Hermann <jh@web.de>
@license: GNU GPL, see COPYING for details.
"""
import re, time
from MoinMoin.Page import Page
from MoinMoi... | title = _('Full Text Search: "%s"')
sort = 'w | eight'
# search the pages
from MoinMoin.search import searchPages, QueryParser, QueryError
try:
query = QueryParser(case=case, regex=regex,
titlesearch=titlesearch).parse_query(needle)
except QueryError: # catch errors in the search query
request.theme.add_msg(_(... |
HBEE/accounting | ecoservice_financeinterface_datev/models/account_invoice.py | Python | gpl-3.0 | 3,072 | 0.00293 | # -*- coding: utf-8 -*-
from openerp import api, fields, models, _
from . import exceptions
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
enable_datev_checks = fields.Boolean('Perform Datev Checks', default=True)
@api.multi
def is_datev_validation_active(self):
self.ensur... | g(u'\n'.join(errors))
return is_valid
class AccountInvoiceLine(models.Model):
_inherit = 'account.invoice.line'
@api.multi
def perform_datev_validation(self, silent=False, line_no=None):
| """
Performs tests on an invoice line for whether the taxes are correctly set or not.
The major use of this method is in the condition of a workflow transition.
:param line_no: int Line number to be displayed in an error message.
:param silent: bool Specifies whether an exceptio... |
jorgebastida/gordon | gordon/resources/kinesis.py | Python | bsd-3-clause | 139 | 0 | from . import base
class | Kinesis(base.BaseStream) | :
"""Resource which consumes ``Kinesis``streams."""
grn_type = 'kinesis-stream'
|
pixlie/oxidizr | oxidizr/apps/twitter/management/commands/twitter_feed.py | Python | gpl-2.0 | 4,372 | 0.003202 | from twitter import OAuth, TwitterStream
from dateutil import parser
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.db.utils import IntegrityError
from apps.keywords.models import BaseKeyword
from apps.twitter.models import Tweet, Account
class Command... | _count=user['statu | ses_count'] if 'statuses_count' in user else 0,
follower_count=user['followers_count'] if 'followers_count' in user else 0,
following_count=user['friends_count'] if 'friends_count' in user else 0,
listed_in_count=user['listed_count'] if 'listed_count' in user else 0,
... |
MesserLab/SLiM | treerec/tests/test_specific_recipes.py | Python | gpl-3.0 | 6,364 | 0.004243 | """
Tests that look at the result of specific recipes in test_recipes
These may depend on the exact random seed used to run the SLiM simulation.
Individual recipes can be specified by decorating with
@pytest.mark.parametrize('recipe', ['test_____my_specific_recipe.slim'], indirect=True)
"""
import msprime
import numpy ... | ts.node(n).individual >= 0 # has an individual
ind = ts.individual(ts.node(n).individual)
assert ts.node(n).is_sample()
assert (ind.flags & pyslim.INDIVIDUAL_REMEMBERED) != 0
num_unary_nodes += 1
... | odes > 0
@pytest.mark.parametrize('recipe', indirect=True, argvalues=[
"test_____retain_and_remember_individuals.slim",
"test_____retain_individuals_nonWF.slim",
"test_____remember_individuals.slim",
])
def test_no_purely_unary_internal_nonsample_nodes(self, recipe):
for res... |
YunoHost/yunotest | jsonschema/validators.py | Python | gpl-3.0 | 14,604 | 0.003766 | from __future__ import division
import contextlib
import json
import numbers
try:
import requests
except ImportError:
requests = None
from jsonschema import _utils, _validators
from jsonschema.compat import (
Sequence, urljoin, urlsplit, urldefrag, unquote, urlopen,
str_types, int_types, iteritems,
)... | u"multipleOf" : _validators.multipleOf,
u"not" : _validators.not_draft4,
u"oneOf" : _validators.oneOf_draft4,
u"pattern" : _validators.pattern,
u"patternProperties" : _validators.patternProperties,
u"properties" : _validators.properties_draft4,
u"required" : _valid... | aft4,
u"uniqueItems" : _validators.uniqueItems,
},
version="draft4",
)
class RefResolver(object):
"""
Resolve JSON References.
:argument str base_uri: URI of the referring document
:argument referrer: the actual referring document
:argument dict store: a mapping from URIs to docum... |
FireballDWF/cloud-custodian | c7n/resources/ecr.py | Python | apache-2.0 | 11,773 | 0.00034 | # Copyright 2016-2017 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | onError(
("{} has invalid lifecycle rule {} tagprefi | xlist "
"required for tagStatus: tagged").format(
policy.name, rule))
if (rule['selection']['countType'] == 'sinceImagePushed' and
'countUnit' not in rule['selection']):
raise PolicyValidationError(
("{} has invalid lifecycle rule {} countUnit "
... |
mistercrunch/panoramix | superset/examples/country_map.py | Python | apache-2.0 | 3,977 | 0.000754 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ",
| "viz_type": "country_map",
"entity": "DEPT_ID",
"metric": {
"expressionType": "SIMPLE",
"column": {"type": "INT", "column_name": "2004"},
"aggregate": "AVG",
"label": "Boys",
"optionName": "metric_112342",
},
"row_limit": 500... |
kubaszostak/gdal-dragndrop | osgeo/apps/Python27/Scripts/gdal2tiles.py | Python | mit | 123,604 | 0.001659 | #!C:\OSGEO4~1\bin\python.exe
# -*- coding: utf-8 -*-
# ******************************************************************************
# $Id: gdal2tiles.py 1f32f6fdbfd2fd352047db41d316d8afbe3c3319 2018-11-30 01:05:06 +0100 Even Rouault $
#
# Project: Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
... | nctions necessary for generation of tiles in Spherical Mercator projection,
EPSG:3857.
Such tiles are compatible with Google Maps, Bing Maps, Yahoo Maps,
UK Ordnance Survey OpenSpace | API, ...
and you can overlay them on top of base maps of those web mapping applications.
Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
What coordinate conversions do we need for TMS Global Mercator tiles::
LatLon <-> Meters <-> Pixels ... |
sciCloud/OLiMS | lims/browser/method.py | Python | agpl-3.0 | 3,775 | 0.002384 | from lims.browser import BrowserView
from dependencies.dependency import getToolByName
from dependencies.dependency import check as CheckAuthenticator
import json
class ajaxGetInstruments(BrowserView):
""" Returns a json list with the instruments assigned to the method
with the following structure:
... | elf, 'portal_catalog')
method = bsc(portal_type='Method', UID=self.request.get("uid", '0'))
if method and len(method) == 1:
method = method[0].getObject()
for i in method.getInstruments():
instrument = { 'uid' : i.UID(),
'title': i.T... | 'url': i.absolute_url_path(),
'outofdate': i.isOutOfDate(),
'qcfail': not i.isQCValid(),
'isvalid': i.isValid()}
instruments.append(instrument)
return json.dumps(instruments)
class a... |
sbesson/zeroc-ice | rb/allTests.py | Python | gpl-2.0 | 1,545 | 0.003883 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | "Ice/location", ["core"]),
("Ice/objects", ["core"]),
("Ice/proxy", ["core"]),
("Ice/properties", ["once", "nowin32"]),
("Ice/operations", ["core"]),
("Ice/retry", ["core"]),
("Ice/timeout", ["core"]),
("Ice/slicing/exceptions", ["core"]),
("Ice/slicing/objects", ["core"]),
| ("Ice/defaultValue", ["core"]),
("Ice/optional", ["core"]),
("Ice/enums", ["core"])
]
if __name__ == "__main__":
TestUtil.run(tests)
|
devs1991/test_edx_docmode | lms/djangoapps/discussion_api/tests/utils.py | Python | agpl-3.0 | 13,936 | 0.001435 | """
Discussion API test utilities
"""
import json
import re
import httpretty
def _get_thread_callback(thread_data):
"""
Get a callback function that will return POST/PUT data overridden by
response_overrides.
"""
def callback(request, _uri, headers):
"""
Simulate the thread creati... | "
def callback(request, _uri, headers):
"""
Simulate the comment creation or update endpoint as described above.
"""
response_data = make_minimal_cs_comment(comment_data)
# thread_id and parent_id are not included in request | payload but
# are returned by the comments service
response_data["thread_id"] = thread_id
response_data["parent_id"] = parent_id
for key, val_list in request.parsed_body.items():
val = val_list[0]
if key in ["anonymous", "anonymous_to_peers", "endorsed"]:
... |
marcinn/restosaur | restosaur/context.py | Python | bsd-2-clause | 7,771 | 0 | import collections
import email
import types
import urllib
import urlparse
import responses
import times
# todo: implement own conversion utility
from django.utils.encoding import force_bytes
from .loading import load_resource
def parse_http_date(header, headers):
if header in headers and headers[header]:
... | .
`.items()` method returns a list of (key, value) tuples, where value is
a single value from a key's values list. This means that key may not be
unique. This representation is compatible with `urllib.urlencode()`.
`.keys()` returns unique key names, same as for pure `dict`.
`.values()` returns l... |
`.lists()` returns internal representation as list of lists.
"""
def __init__(self, initial=None):
self._data = {}
self.update(initial)
def update(self, data):
if data is None:
return
else:
try:
data = data.items()
ex... |
viswimmer1/PythonGenerator | data/python_files/33000414/test_rendering.py | Python | gpl-2.0 | 1,936 | 0.001033 | import unittest
import warnings
from pyramid.tests.test_config import dummyfactory
cla | ss TestRenderingConfiguratorMixin(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.config import Configurator
config = Configurator(*arg, **kw)
return config
def test_set_renderer_globals_factory(self):
from pyramid.interfaces import IRendererGlobalsFactory
... | gs('ignore')
config.set_renderer_globals_factory(factory)
self.assertEqual(
config.registry.getUtility(IRendererGlobalsFactory),
factory)
def test_set_renderer_globals_factory_dottedname(self):
from pyramid.interfaces import IRendererGlobalsFactory
config... |
revanthkolli/osf.io | website/addons/dataverse/views/hgrid.py | Python | apache-2.0 | 2,011 | 0.000497 | # -*- coding: utf-8 -*-
from website.addons.dataverse.client import get_dataset, get_files, \
get_dataverse, connect_from_settings
from website.project.decorators import must_be_contributor_or_public
from website.project.decorators import must_have_addon
from website.util import rubeus
def dataverse_hgrid_root(... | ls = {
'publish': node.api_url_for('dataverse_publish_dataset'),
'publishBoth': node.api_url_for('dataverse_publish_both')
}
return [rubeus.build_addon_root(
node_addon,
node_addon.dataset,
u | rls=urls,
permissions=permissions,
dataset=node_addon.dataset,
doi=dataset.doi,
dataverse=dataverse.title,
hasPublishedFiles=bool(published_files),
dataverseIsPublished=dataverse.is_published,
version=version,
)]
@must_be_contributor_or_public
@must_have_add... |
Anachronos/teslabot | teslabot/plugins/xdcc/__init__.py | Python | mit | 20 | 0 | _ | _author_ | _ = 'Xach'
|
hasteur/advent_of_code | 2015/puzzle16.py | Python | gpl-2.0 | 2,024 | 0.027668 | import re
class Aunt:
name = ''
def __init__(self, name):
self.name = name
self.count = {'children':-1,
'cats' : -1,
'samoyeds' : -1,
'pomeranians' : -1,
'akitas' : -1,
'vizslas' : -1,
... | elf.count[key] == -1:
return True
else:
return self.count[key] == value
def filterCalib(self, key, value):
if self.count[key] == -1:
return True
else:
if key in ('cats', 'trees'):
return self.count[key] > value
if key in ('pomeranians','goldfish'):
return self.co... | e
def filterRule(AuList, key, val):
RetAu = []
for Aun in AuList:
if Aun.filterCalib(key, val):
RetAu.append(Aun)
return RetAu
AuntList = []
fh = open('puzzle16.txt','r')
match_rule = re.compile('(?P<Name>Sue [0-9]{1,3}): (?P<attrib>.+)$')
for line in fh:
matches = match_rule.match(line) ... |
sam-m888/gprime | gprime/proxy/referencedbyselection.py | Python | gpl-2.0 | 23,926 | 0.000293 | #
# gPrime - A web-based genealogy program
#
# Copyright (C) 2010 Doug Blank <doug.blank@gmail.com>
# Copyright (C) 2011 Tim G L Lyons
#
# 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 Foundatio... | f_citations,
},
'Event':
{
"handle_func": self.get_event_from_handle,
| "gid_func": self.get_event_from_gid,
"class_func": Event,
"cursor_func": self.get_event_cursor,
"handles_func": self.get_event_handles,
"iter_func": self.iter_events,
"count_func": self.get_number_of_events,
},
... |
dennisobrien/bokeh | examples/app/taylor.py | Python | bsd-3-clause | 2,101 | 0.004284 | import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column, widgetbox
from bokeh.models import ColumnDataSource, Legend, LegendItem, Slider, TextInput, PreText
from bokeh.plotting import figure
xs = sy.Symbol('x')
expr = sy.exp(-xs)*sy.si... | xpr), renderers=[line_t]),
]
p.add_layout(legend)
def update():
try:
expr = sy.sympify(text.value, dict(x=xs))
exc | ept Exception as exception:
errbox.text = str(exception)
else:
errbox.text = ""
x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)
p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr)
legend.items[0].label = value("%s" % expr)
legend.i... |
andysim/psi4 | psi4/driver/procrouting/proc_table.py | Python | gpl-2.0 | 10,293 | 0.014864 | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | 'sapt2+(ccd)' : proc.run_sapt,
'sapt2+(3)(ccd)': proc.run_sapt,
'sapt2+3(ccd)' : proc.run_sapt,
'sapt2+dmp2' : proc.run_sapt,
'sapt2+(3)dmp2' : proc.run_sapt,
'sapt2+3dmp2' : proc | .run_sapt,
'sapt2+(ccd)dmp2' : proc.run_sapt,
'sapt2+(3)(ccd)dmp2' : proc.run_sapt,
'sapt2+3(ccd)dmp2' : proc.run_sapt,
'sapt0-ct' : proc.run_sapt_ct,
'sapt2-ct' : proc.run_sapt_ct,
'sapt2+-ct' : proc.run_sapt_ct,
'sapt2+(... |
cutoffthetop/zeitnow | bootstrap.py | Python | bsd-2-clause | 4,121 | 0.003155 | ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | )
# if -c was provided, we push it back into args for buildout' main function
if options.confi | g_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
to_reload = False
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
... |
webbers/pyhammer | pyhammer/tasks/helpers/makenugetpackagetask.py | Python | mit | 1,540 | 0.012338 | # -*- coding: utf-8 -*-
import os
import ntpath
import glob
from | pyhammer.tasks.taskbase import TaskBase
from pyhammer.utils import execProg
class MakeNugetPackageTask(TaskBase):
"""Make Nuget Package Task"""
def __init__( self, csProjectPath, solutionDir, tempDir, publishDir, visualStudioVersion = "12.0" ):
super(MakeNugetPackageTask, self).__init__()
sel... | ojectPath = csProjectPath
self.solutionDir = solutionDir
self.tempDir = tempDir
self.publishDir = publishDir
self.visualStudioVersion = visualStudioVersion
def do( self ):
self.reporter.message( "MAKING NUGET PACKAGE FROM: %s" % ntpath.basename(self.csProjectPath) )
... |
rwl/PyCIM | CIM14/IEC61970/Dynamics/MetaBlockState.py | Python | mit | 2,325 | 0.00172 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permissio | n is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the S... | be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRI... |
bankonme/www.freedomsponsors.org | djangoproject/core/migrations/0046_auto__add_field_issue_status.py | Python | agpl-3.0 | 20,741 | 0.007907 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Issue.status'
db.add_column('core_issue', 'status',
self.gf('django.db... | go.db.models.fields.TextField', [], {'nul | l': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_feedback': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_public_suggestion': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
... |
stackforge/monasca-api | monasca_api/tests/policy/base.py | Python | apache-2.0 | 3,063 | 0 | # Copyright 2017 OP5 AB
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... | r agreed to in writing, software
# distributed under the License i | s 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.
"""Base classes for policy unit tests."""
import os
import fixtures
from oslo_config import cf... |
katakumpo/nicedjango | tests/test_compact_csv_reader.py | Python | mit | 1,175 | 0 | from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = | b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), p | reserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\... |
opmuse/opmuse | opmuse/test/test_security.py | Python | agpl-3.0 | 1,210 | 0 | # Copyright 2012-2015 Mattias Fliesberg
#
# This file is part of opmuse.
#
# opmuse is free so | ftware: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# opmuse is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; ... | License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with opmuse. If not, see <http://www.gnu.org/licenses/>.
from . import setup_db, teardown_db
from opmuse.security import User, hash_password
class TestSecurity:
def setup_method(self):
setup_db... |
Ksynko/django-crm | sample_project/external_apps/crm/views.py | Python | bsd-3-clause | 23,073 | 0.00234 | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# $Id: views.py 425 2009-07-14 03:43:01Z tobias $
# ----------------------------------------------------------------------------
#
# Copyright (C) 2008-2009 Caktus Consulting Group, LLC
#
# This file is part of ... | %s.' % contact
)
view_person_url = reverse('view_person', args=[contact.id])
return HttpResponseRedirect(view_person_url)
else:
form = crm_forms.EmailContactForm(recipients=[contact.email])
return {
'form': form,
'contact': | contact,
}
@login_required
@transaction.commit_on_success
@render_with('crm/person/create_edit.html')
def create_edit_person(request, person_id=None):
if person_id:
profile = get_object_or_404(crm.Contact, pk=person_id)
try:
location = profile.locations.all()[0]
except Ind... |
andrewklau/openshift-tools | ansible/roles/lib_openshift_3.2/library/oc_version.py | Python | apache-2.0 | 33,153 | 0.002624 | #!/usr/bin/env python # pylint: disable=too-many-lines
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
# | |) | (_) ... | .namespace]
if selector:
cmd.append('--selector=%s' % selector)
return self.openshift_cmd(cmd)
def _process(self, template_name, crea | te=False, params=None, template_data=None):
'''return all pods '''
cmd = ['process', '-n', self.namespace]
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ["%s=%s" % (key, value) for key, value i... |
googleapis/python-bigquery | samples/tests/test_client_query_w_array_params.py | Python | apache-2.0 | 792 | 0 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Versio | n 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 writing, software
# distributed under the License is distributed on an "AS IS" BAS... | he License for the specific language governing permissions and
# limitations under the License.
from .. import client_query_w_array_params
def test_client_query_w_array_params(capsys,):
client_query_w_array_params.client_query_w_array_params()
out, err = capsys.readouterr()
assert "James" in out
|
Petraea/jsonbot | jsb/lib/periodical.py | Python | mit | 8,994 | 0.005003 | # gozerbot/periodical.py
#
#
""" provide a periodic structure. """
__author__ = "Wijnand 'tehmaze' Modderman - http://tehmaze.com"
__license__ = "BSD License"
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.utils.trace import calledfrom, whichmodule
from jsb.utils.locking import lockdec
fro... |
return self.group == group
def do(self):
""" try the callback. """
try: self.func(*self.args, **self.kw)
except Exception, ex: handle_exception()
class JobAt(Job):
""" job to run at a specific time/interval/repeat. """
def __init__(self, start, interval, repeat, func, *a... |
self.kw = kw
self.repeat = repeat
self.description = ""
self.counts = 0
if type(start) in [types.IntType, types.FloatType]: self.next = float(start)
elif type(start) in [types.StringType, types.UnicodeType]:
d = strtotime(start)
if d and d > time.... |
JoeJasinski/evesch | evesch/euser/urls.py | Python | gpl-2.0 | 878 | 0.018223 | from django.conf.urls import patterns, include, url
from evesch.euser.views import *
urlpatterns = patterns('',
url('^(?P<username>\w{1,30})/$', 'evesch.euser.views.user_view', {'template_name':'euser/user_view.html'}, name='euser_user_view'),
url('^ajax/lookup_users/$', 'evesch.euser.views.lookup_users', ... | _feed_hash>\w{1,24}).ics$', 'evesch.core.feed.views.user_ics', {}, name='core_feed_user_ics'),
url('^(?P<username>\w{1,30})/feed_(?P<user_feed_hash>\w{1,24}).rss$', 'e | vesch.core.feed.views.user_rss', {}, name='core_feed_user_rss'),
)
|
lewisodriscoll/sasview | src/sas/sasgui/perspectives/calculator/resolution_calculator_panel.py | Python | bsd-3-clause | 58,547 | 0.002238 | # pylint: disable=attribute-defined-outside-init
"""
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation.
See the license text in license.txt
copyright 2008, 2009, 2010 Univer... | lts
self.qx = []
self.qy = []
# dQ defaults
self.sigma_r = None
self.sigma_phi = None
self.sigma_1d = None
# monchromatic or polychromatic
self.wave_color = 'mono'
self.num_wave = 10
self.spectrum_dic = {}
# dQ 2d image
self... | mas
self.sigma_strings = ' '
#Font size
self.SetWindowVariant(variant=FONT_VARIANT)
# Object that receive status event
self.resolution = ResolutionCalculator()
# Source selection dic
self.source_mass = _SOURCE_MASS
#layout attribute
self.hint_sizer... |
Lorquas/subscription-manager | src/rhsmlib/facts/collector.py | Python | gpl-2.0 | 4,009 | 0.000499 | from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... | FactsCollection(facts_dict=facts_dict)
return facts_collection
def get_all(self):
# try each hardware method, and try/except around, since
# these tend to be fragile
all_hw_info = {}
for hardware_method in self.hardw | are_methods:
info_dict = {}
try:
info_dict = hardware_method()
except Exception as e:
log.warn("Hardware detection [%s] failed: %s" % (hardware_method.__name__, e))
all_hw_info.update(info_dict)
return all_hw_info
class StaticFa... |
GoogleCloudPlatform/guest-test-infra | container_images/pytest/example/src/application/main_test.py | Python | apache-2.0 | 688 | 0.001453 | # Copyright 2020 Google 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 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... | s under the License.
from main import three_plus_four
def test_three_plus_four():
assert three_plus_four() == 7
|
tankywoo/simiki | simiki/generators.py | Python | mit | 15,605 | 0.000064 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert Markdown file to html, which is embeded in html template.
"""
from __future__ import (print_function, with_statement, unicode_literals,
absolute_import)
import os
import os.path
import io
import copy
import re
import traceback
import war... | ath.exists(_template_path):
raise Exception("Theme `{0}' not exists".format(_template_path))
self.env = Environment(
loader=FileSystemLoader(_template_path)
)
self._jinja_load_exts()
def _jinja_load_exts(self):
"""Load jinja custom filters and extensions"""
... | self.env.filters[_filter] = getattr(jinja_exts, _filter)
def get_template(self, name):
"""Return the template by layout name"""
if name not in self._templates:
try:
self._templates[name] = self.env.get_template(name + '.html')
except TemplateError... |
fuziontech/svb | svb/test/test_requestor.py | Python | mit | 15,897 | 0.000126 | import datetime
import unittest2
import urlparse
from mock import Mock, ANY
import svb
from svb.six.moves.urllib import parse
from svb.test.helper import SvbUnitTestCase
VALID_API_METHODS = ('get', 'post', 'delete', 'patch')
class GMT1(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timed... | 't know the local time of your system,
# we just check that naive encodings are within 24 hours of correct.
self.assertTrue(60 * 60 * 24 > abs(stk[0][1] - 1356994800))
def test_param_encoding(self):
self.mock_response('{}', 200)
self.requestor.request('get', '', | self.ENCODE_INPUTS)
expectation = []
for type_, values in self.ENCODE_EXPECTATIONS.iteritems():
expectation.extend([(k % (type_,), str(v)) for k, v in values])
self.check_call('get', QueryMatcher(expectation))
def test_dictionary_list_encoding(self):
params = {
... |
skyfsza/Logos | resources/lib/plugin_content.py | Python | gpl-2.0 | 15,952 | 0.002696 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
script.skin.helper.service
Helper service and scripts for Kodi skins
plugin_content.py
Hidden plugin entry point providing some helper features
'''
import xbmc
import xbmcplugin
import xbmcgui
import xbmcaddon
from simplecache import SimpleCache
from utils... | lly seek because passing resume to the player json cmd doesn't seem to work
if recording["resume"].get("position"):
for i in range(50):
if getCondVisibility("Player.HasVideo"):
break
xbmc.sleep(50)
xbmc.Pla | yer().seekTime(recording["resume"].get("position"))
def launch(self):
'''launch any builtin action using a plugin listitem'''
if "runscript" in self.params["path"]:
self.params["path"] = self.params["path"].replace("?", ",")
xbmc.executebuiltin(self.params["path"])
def play... |
sosilent/euca | clc/eucadmin/eucadmin/utils.py | Python | gpl-3.0 | 2,194 | 0.002279 | # Copyright (c) 2011, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software 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, t... | Y THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Mitch Garnaat mgarnaat@eucalyptus.com
import os
def _walk_recursive(paths, fn, *params):
... | ths:
fn(path, *params)
for dirpath, dirs, files in os.walk(path):
for d in dirs:
fullpath = os.path.join(dirpath, d)
if os.path.islink(fullpath):
symlinks.append(fullpath)
else:
fn(fullpath, *params)
... |
LaetitiaPapaxanthos/UnionCom | test.py | Python | mit | 1,911 | 0.028781 | import os
import random
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import numpy as np
import scipy.sparse as sp
from sklearn.neighbors import NearestNeighbors, KNeighborsClassifier
def align_fraction(data1, data2, params):
row1, col1 = np.shape(data1)
row2, col2... | ]).float().to(device))
# print("saving integrated data...")
data = []
integrated_data = []
for i in range(len(dataset_test)):
data.append(Project(dataset_test[i], i))
data[i] = data[i].detach().cpu().numpy()
|
permutation = np.argsort(change)
for i in permutation:
integrated_data.append(data[i])
# np.savetxt('integrated_data{}.txt'.format(change[i]),data[i])
if test:
for i in range(len(dataset_test)-1):
# fraction = align_fraction(data[i], data[-1], params)
# print("average fraction:")
# print(fr... |
appu1232/Discord-Selfbot | cogs/utils/menu.py | Python | gpl-3.0 | 5,866 | 0.00733 | import asyncio
class Menu:
"""An interactive menu class for Discord."""
class Submenu:
"""A metaclass of the Menu class."""
def __init__(self, name, content):
self.content = content
self.leads_to = []
self.name = name
def get_te... | ent="```" + output + "```")
break
output | += "\n" + current.get_text() + "\n"
output += "Enter a number."
if not menu_msg:
menu_msg = await ctx.send("```" + output + "```")
else:
await menu_msg.edit(content="```" + output + "```")
... |
varenius/salsa | USRP/usrp_gnuradio_dev/testold.py | Python | mit | 2,198 | 0.015469 | import matplotlib.pyplot as plt
import numpy as np
import sys
import time
import scipy.interpolate as ip
infile = sys.argv[1]
indata = np.load(infile)
spec = indata[0]
samp_rate = indata[1]
fftsize = indata[2]
center_freq = 1419.4 # MHz
halffft = int(0.5*fftsize)
freqs = 0.5*samp_rate*np.array(range(-halffft,halffft)... | np.size(RFI_part)
spl = ip.UnivariateSpline(xdata,RFI_part, k=1, s=0)
interpdata = spl(range(ind_low, ind_high))
print interpdata
spec[ind_low:ind_high] = interpdata[:]
plt.figure | ()
plt.plot(RFI_part)
plt.plot(interpdata)
#plt.figure()
#plt.plot(freqs, spec)
#for flag in flags:
#
# Calculate flag indices
# For each flag, interpolate flagged values (splines)
# when all flaggs are applied and interpolated, proceed with convolve!
#plt.figure()
#convspec = np.convolve(spec, [1,1... |
jlesquembre/autopilot | tests/pypi_test.py | Python | gpl-2.0 | 1,650 | 0.001818 | import os
from urllib.error import URLError
import pytest
from distlib.index import PackageIndex
from autopilot import pypi
def test_restore_cwd(fake_project_dir):
cwd = os.getcwd()
with pypi.generate_dist(fake_project_dir.as_posix()) as (metadata, dist_files):
pass
assert cwd == os.getcwd()
... | ps=False, dist_dir=fake_project_dir.as_posix())
files = [f.name for f in local_dir.iterdir()]
assert len(files) == 2
assert 'fake_project-1.0. | 0-py2.py3-none-any.whl' in files
assert 'fake_project-1.0.0.tar.gz' in files
|
gencer/python-phonenumbers | python/phonenumbers/shortdata/region_SX.py | Python | apache-2.0 | 548 | 0.009124 | """Auto-ge | nerated file, do not edit by hand. SX metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_SX = PhoneMetadata(id='SX', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='9\\d{2}', possible_length=(3,)),
emergency=Ph... | xample_number='919', possible_length=(3,)),
short_data=True)
|
cglewis/wharf | wharf/favicon.py | Python | apache-2.0 | 274 | 0.007299 | from wharf import app
from flask import send_from_directory
from os | import | path
@app.route('/favicon.ico')
def favicon():
return send_from_directory(path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
|
henriquegemignani/randovania | randovania/game_description/item/item_database.py | Python | gpl-3.0 | 2,456 | 0.000407 | from dataclasses import dataclass
from typing import Dict, Tuple, Union
from randovania.game_description.item import migrations
from randovania.game_description.item.ammo import Ammo
from randovania.game_description.item.item_category import ItemCategory
from randovania.game_description.item.major_item import MajorIte... | ammo = {
name: Ammo.from_json(name, value, game, item_categories)
for name, value in database_data["ammo"].items()
}
default_items = {
item_categories[category_name]: tuple | (major_items[item_name] for item_name in value)
for category_name, value in database_data["default_items"].items()
}
return ItemDatabase(item_categories, major_items, ammo, default_items)
def write_database(database: ItemDatabase) -> Dict:
"""
:param database:
:return:
"""
item_c... |
ContinuumIO/odo | odo/backends/bcolz.py | Python | bsd-3-clause | 3,424 | 0.000876 | from __future__ import absolute_import, division, print_function
import os
from bcolz import ctable, carray
import numpy as np
from toolz import keyfilter
import datashape
from datashape import discover
import shutil
from ..numpy_dtype import dshape_to_numpy
from ..append import append
from ..convert import convert, o... | .Fixed)
else None)
if datashape.predicates.isrecord(dshape.measure):
return ctable(x, rootdir=uri, expectedlen=expectedlen, **kwargs)
else:
return carra | y(x, rootdir=uri, expectedlen=expectedlen, **kwargs)
@drop.register((carray, ctable))
def drop_bcolz(b, **kwargs):
b.flush()
shutil.rmtree(b.rootdir)
ooc_types |= set((carray, ctable))
|
yvaucher/vertical-ngo | __unported__/transport_plan/__openerp__.py | Python | agpl-3.0 | 1,727 | 0.001738 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joël Grand-Guillaume
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as pu... | CULAR PURPOSE. See the
# GNU Affero General Public License for more description.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################... | normal",
"images" : [],
"website": "http://www.camptocamp.com",
"description": """
This module allows you to manage your transport
===============================================
A transport plan represent a kind of "contract" with your carrier.
""",
"depends" : ["sale",
"purchase",
"st... |
theodox/mGui | mGui/events.py | Python | mit | 8,231 | 0.001701 | """
events.py
Defines a simple event handler system similar to that used in C#. Events allow
multicast delegates and arbitrary message passing. They use weak references so
they don't keep their handlers alive if they are otherwise out of scope.
"""
import weakref
import maya.utils
from functools import partial, wrap... | or handler in self._handlers:
try:
handler(*args, **self.metadata(kwargs))
except DeadReferenceError:
delenda.append(handler)
self._handlers = self._handlers.difference(set(delenda))
def _handler_count(self):
"""
Returns the count of t... | # hook up the instance methods to the base methods
# doing it this way allows you to override more neatly
# in derived classes
__call__ = _fire
__len__ = _handler_count
__iadd__ = _add_handler
__isub__ = _remove_handler
def __del__(self):
print 'event expired'
class MayaEvent(Ev... |
felixmatt/shyft | shyft/api/__init__.py | Python | lgpl-3.0 | 15,456 | 0.00744 | import inspect
import traceback
import warnings
import functools
from shyft.api._api import *
import numpy as np
from math import sqrt
def deprecated(message: str = ''):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the funct... | .values")
TimeSeries.kling_gupta = lambda self, oth | er_ts, s_r=1.0, s_a=1.0, s_b=1.0: kling_gupta(self, other_ts,
self.get_time_axis(), s_r, s_a,
s_b)
TimeSeries.kling_gupta.__doc__ = \
"""
... |
TE-ToshiakiTanaka/bantorra.old | util/cmd.py | Python | mit | 1,792 | 0.005022 | import sys
import os
import time
import imp
import subprocess
import multiprocessing
from bantorra.util import define
from bantorra.util.log import LOG as L
TIMEOUT = 30
class Process(multiprocessing.Process):
def __init__(self, command, queue):
self.command = command
self.queue = queue
m... | 'stdout' : subprocess.PIPE,
'stderr' : subprocess.PIPE,
}
try:
proc = subprocess.Popen(args, **subproc_ar | gs)
except OSError:
L.info("Failed to execute command: %s" % args[0])
sys.exit(1)
(stdout, stderr) = proc.communicate()
code = proc.wait()
L.debug("Command Resturn Code: %d" % code)
self.queue.put(stdout)
def kill(self):
L.debug("Kill This Pro... |
lesiavl/selenium_perfomance_tests | pzo_load/load_test_file.py | Python | apache-2.0 | 5,242 | 0.001336 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from page_objects import *
from selenium import webdriver
import datetime
import time
import Queue
import threading
import traceback
tenders = Queue.Queue()
tenders_ids = []
tenders_threads = 2
bids = Queue.Queue()
bids_failed = {}
runs = Queue.Queue()
class CreateT... | f.write('{} failed \n'.format(bids_failed))
f.close()
# Start making by clicking simultaneously
print('Start running bids...')
for driver in drivers.keys():
c = RunTenderBids(runs, drivers[driver], driver)
c.setDaemon(True)
c.start()
|
for driver in drivers:
runs.put(True)
runs.join()
print('Runs performed')
print("Elapsed Time: %s" % (time.time() - start))
for driver in drivers:
drivers[driver].close()
|
mozilla/bztools | auto_nag/scripts/defect_with_please_or_enable.py | Python | bsd-3-clause | 1,009 | 0.000991 | # This Source Code Form is subjec | t 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/.
from auto_nag.bzcleaner import BzCleaner
class DefectWithPlease(BzC | leaner):
def __init__(self):
super(DefectWithPlease, self).__init__()
def description(self):
return (
"Defect with description starting with 'Please', 'Enable', 'Disable', etc"
)
def ignore_date(self):
return True
def get_bz_params(self, date):
days... |
protonn/Electrum-Cash | lib/tests/test_simple_config.py | Python | mit | 11,045 | 0.00498 | import ast
import sys
import os
import unittest
import tempfile
import shutil
import json
from StringIO import StringIO
from lib.simple_config import (SimpleConfig, read_system_config,
read_user_config)
class Test_SimpleConfig(unittest.TestCase):
def setUp(self):
super(Tes... | _portable(self):
"""If electrum is started with the "portable" flag, system
configuration is completely ignored."""
fake_read_system = lambda : {"some_key": "some_value"}
fake_read_user = lambda _: {}
read_user_dir = lambda : s | elf.user_dir
config = SimpleConfig(options={"portable": True},
read_system_config_function=fake_read_system,
read_user_config_function=fake_read_user,
read_user_dir_function=read_user_dir)
self.assertEqual(config.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.