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 |
|---|---|---|---|---|---|---|---|---|
endlessm/chromium-browser | tools/swarming_client/third_party/pyasn1/pyasn1/compat/dateandtime.py | Python | bsd-3-clause | 482 | 0 | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2019, Ilya Etingof <[email protected]>
# License: http://snmplabs.com/pyasn1/li | cense.html
#
import time
from datetime import datetime
from sys import version_info
__all__ = ['strptime']
if version_info[:2] <= (2, 4):
def strptime(text, dateFormat):
return datetime(*(time.strptime(text, dateFormat)[0:6]))
else:
def strptime(text, date | Format):
return datetime.strptime(text, dateFormat)
|
symbolicdata/code | src/sdeval/classes/MachineSettingsFromXMLBuilder_test.py | Python | gpl-3.0 | 3,258 | 0.008287 | import unittest
import MachineSettingsFromXMLBuilder as MSFXMLB
import MachineSettings as MS
class TestMachineSettingsFromXMLBuilder(unittest.TestCase):
"""
Tests for the class MachineSettingsFromXMLBuilder
.. moduleauthor:: Albert Heinle <[email protected]>
"""
def setUp(self):
... | 2) Invalid input for Machine Settings XML
"""
#1)
testPassed = 1
try:
temp = builder.build("")
testPassed = 0
except:
pass
if testPassed == 0:
self.fail("Could build Machine Settings from the | empty string.")
try:
temp = builder.build("<xml></xml>")
testPassed = 0
except:
pass
if (testPassed == 0):
self.fail("Could build Machine Settings from empty xml.")
try:
temp = builder.build("!@#$%^&*()_+")
testPass... |
zjj/trac_hack | trac/versioncontrol/admin.py | Python | bsd-3-clause | 16,185 | 0.001792 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of vo... | _sync_feedback(self, rev):
sys.stdout.write(' [%s]\r' % rev)
sys.stdout.flush()
def _do_resync(self, reponame, rev=None):
self._sync(reponame, rev, clean=True)
def _do_sync(self, reponame, rev=None):
self._sync(reponame, rev, clean=False)
# IPermissionRequestor methods
... | 'FILE_VIEW', 'LOG_VIEW'])]
class RepositoryAdminPanel(Component):
"""Web admin panel for repository administration."""
implements(IAdminPanelProvider)
allowed_repository_dir_prefixes = ListOption('versioncontrol',
'allowed_repository_dir_prefixes', '',
... |
cernops/CloudMan | export/export.py | Python | apache-2.0 | 11,272 | 0.011888 | from cloudman.cloudman.models import TopLevelAllocationByZone,TopLevelAllocation,TopLevelAllocationAllowedResourceType
from cloudman.cloudman.models import ProjectAllocation,Project,ProjectMetadata,ProjectAllocationMetadata,GroupAllocation
from cloudman.cloudman.models import GroupAllocationMetadata
from cloudman.cloud... | = str(alloc.group.name)
project_name = alloc.project.name
if showprojectinfo:
attribute['PROJECT'] = genProject(project_name)
attribute['PROJECT_ALLOCATION_METADATA'] = genProjectAllocMetaData(alloc_name)
hepspec = alloc.hepspec
tp_alloc_hepspec = alloc.top_leve... | e['HS06'] = str(hepspec)
attribute['HS06PERCENT'] = str(hepspec_percent)
attribute['MEMORY'] = str(alloc.memory)
attribute['STORAGE'] = str(alloc.storage)
attribute['BANDWIDTH'] = str(alloc.bandwidth)
child = {'PROJECT_ALLOCATION':attribute}
gp_alloc_list = genGroupAlloc(... |
alchemy-fr/Phraseanet-Docs | config/all.py | Python | gpl-3.0 | 7,172 | 0.007669 | # Global configuration information used across all the
# translations of documentation.
#
# -- General configuration ----------------------------- | ------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo','sphinx.ext.autosummar... | urce files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Phraseanet'
copyright = u'2004-2021, <a href="http://www.alchemy.fr" target="_blank">Alchemy</a>'
# The version info for the project you're documenting, acts as replacem... |
silly-wacky-3-town-toon/SOURCE-COD | toontown/ai/DistributedWinterCarolingTargetAI.py | Python | apache-2.0 | 312 | 0.012821 | from direct.directnotify import DirectNotifyGlobal
from toont | own.ai.DistributedScavengerHuntTargetAI import DistributedScavengerHuntTargetAI
class DistributedWinterCarolingTargetAI(DistributedScavengerHuntTargetAI):
notify = DirectNotifyGlobal.dire | ctNotify.newCategory("DistributedWinterCarolingTargetAI")
|
bitmazk/django-hero-slider | hero_slider/south_migrations/0002_auto__add_field_slideritemtitle_is_published.py | Python | mit | 8,315 | 0.007937 | # flake8: noqa
# -*- 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 'SliderItemTitle.is_published'
db.add_column('hero_slider_slideritemtitle', 'i... | 'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.d... | go.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff... |
georgesterpu/pyVSR | pyVSR/ouluvs2/scripts/create_labels.py | Python | gpl-3.0 | 1,947 | 0.002054 | from os import path
|
s1 = 'one seven three five one six two six six seven'
s2 = 'four zero two nine one eight five nine zero four'
s3 = 'one nine zero seven eight eight zero three two eight'
s4 = 'four nine one two one one eight five five one'
s5 = 'eight six three five four zero two one one two'
s6 = 'two t | hree nine zero zero one six seven six four'
s7 = 'five two seven one six one three six seven zero'
s8 = 'nine seven four four four three five five eight seven'
s9 = 'six three eight five three nine eight five six five'
s10 = 'seven three two four zero one nine nine five zero'
digits = [s1, s2, s3, s4, s5, s6, s7, s8, ... |
modelbrouwers/modelbouwdag.nl | src/modelbouwdag/wsgi/production.py | Python | mit | 1,508 | 0.000663 | """
WSGI config for modelbouwdag project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level varia | ble
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to rep | lace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import site
import sys
from .base import setupenv
setupenv()
# We defer to ... |
DrewMeyersCUboulder/UPOD_Bridge | Server/AbstractDb.py | Python | mit | 383 | 0.002611 | """
Ab | stract class for Db classes
"""
from abc import ABCMeta, abstractmethod
class AbstractDb(object):
""" AbstractDb """
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def write(self, data):
pass
@abstractmethod
def query(self, condition):
pass
... | y):
pass
|
Zouyiran/ryu | ryu/app/chapter_2/pre_install_app.py | Python | apache-2.0 | 12,687 | 0.005833 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import networkx as nx
import copy
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3... | instructions=inst)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst)
datapath.send_msg(mod)
def pre_install(self):
while True:
| hub.sleep(self.SLEEP_PERIOD)
self.pre_adjacency_matrix = copy.deepcopy(self.adjacency_matrix)
self._update_topology()
self._update_hosts()
if self.pre_adjacency_matrix != self.adjacency_matrix:
self.logger.info('***********discover_topology thread: TOPO ... |
dparks1134/STAMP | createExeWindows.py | Python | gpl-3.0 | 3,184 | 0.039259 | from distutils.core import setup
import py2exe
import os
import matplotlib as mpl
# delete all pyc files
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for each_file in filenames:
if each_file.endswith('.pyc'):
if os.path.exists(os.path.join(dirpath, each_file)):
os.remove(os.path.join(dirpa... | roups/plots/configGUI','/groups/statisticalTests',
'/multiGroups', '/multiGroups/effectSizeFilters','/multiGroups/plots','/multiGroups/plots/configGUI', '/multiGroups/postHoc','/multiGroups/statisticalTests',
'/samples','/samples/confidenceIntervalMethods','/samples/effectSizeFilters','/samples/plots','/sam... | '/samples/statisticalTests/additional','/samples/plots/examples']
plugin_files = []
for directory in plugin_directories:
for files in os.listdir("./stamp/plugins" + directory):
f1 = "./stamp/plugins" + directory + "/" + files
if os.path.isfile(f1): # skip directories
f2 = "library/stamp/plugins" + director... |
stephane-martin/salt-debian-packaging | salt-2016.3.3/salt/wheel/key.py | Python | apache-2.0 | 3,278 | 0.00061 | # -*- coding: utf-8 -*-
'''
Wheel system wrapper for key system
'''
from __future__ import absolute_import
# Import python libs
import os
import hashlib
# Import salt libs
import salt.key
import salt.crypt
__func_alias__ = {
'list_': 'list'
}
def list_(match):
'''
List all the keys under a named status... | code-block:: python
{
'minions_pre' | : [
'jerry',
'stuart',
'bob',
],
}
'''
skey = salt.key.Key(__opts__)
return skey.accept(match_dict=match)
def delete(match):
'''
Delete keys based on a glob match
'''
skey = salt.key.Key(__opts__)
return skey.delete_ke... |
matthewearl/photo-a-day-aligner | pada/landmarks.py | Python | mit | 2,163 | 0.002774 | # Copyright (c) 2016 Matthew Earl
#
# 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 Soft | ware without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this pe... | MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM,... |
novafloss/django-json-dbindex | json_dbindex/pgcommands.py | Python | bsd-3-clause | 3,263 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Rodolphe Quiédeville <[email protected]>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,... | ing.info("%s doesn't exists" % index['name'])
return res
def create_index(index, database='default'):
"""
Create an index
index (dict) : index description
{"name": "foo",
"database": "default",
"cmd": "CREATE INDEX foo_idx ON table (column)"
}
"""
if 'database' i... | s = 1
else:
logging.info("Will create %s" % index['name'])
res = execute_raw(index['cmd'], database)
logging.info("%s created" % index['name'])
return res
def create_extensions(extensions, database='default'):
"""
Create all extensions
"""
for extension in extensions:
... |
e-koch/VLA_Lband | 14B-088/HI/analysis/uv_plots/channel_1000_uvplot.py | Python | mit | 813 | 0 |
import os
import matplotlib.pyplot as plt
import numpy as np
from plotting_styles import onecolumn_figure, default_figure
from paths import paper1_figures_path
'''
Make a UV plot of the 1000th HI channel.
'''
uvw = np.load("/mnt/M | yRAID/M33/VLA/14B-088/HI/"
| "14B-088_HI_LSRK.ms.contsub_channel_1000.uvw.npy")
onecolumn_figure()
fig = plt.figure()
ax = fig.add_subplot(111) # , rasterized=True)
# plt.hexbin(uvw[0], uvw[1], bins='log', cmap='afmhot_r')
ax.scatter(uvw[0], uvw[1], s=0.1, color='k', rasterized=True)
plt.xlabel("U (m)")
plt.ylabel("V (m)")
plt.xlim(... |
nict-isp/uds-sdk | uds/utils/dict.py | Python | gpl-2.0 | 789 | 0.001267 | # -*- coding: utf-8 -*-
"""
uds.utils.dict
~~~~~~~~~~~~~~
Utility functions to parse string and others.
:copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved.
:license: GPL2, see LICENSE for more details.
"""
import copy
def override_dict(new, old):
... | ict):
| merged = copy.deepcopy(old)
for key in new.keys():
if key in old:
merged[key] = override_dict(new[key], old[key])
else:
merged[key] = new[key]
return merged
else:
return new
|
FOSSRIT/PyCut | game/objects/slice.py | Python | mpl-2.0 | 124 | 0.008065 | import py | game
class Slice():
"""docstring for Slice"""
def __init__(self, context):
| self.context = context
|
FDio/vpp | test/test_abf.py | Python | apache-2.0 | 10,057 | 0 | #!/usr/bin/env python3
from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
import unittest
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsLabel, \
VppIpTable, FibPathProto
from vpp_acl import AclRule, VppAcl
from scapy... |
def add_vpp_config(self):
self._test.vapi.abf_policy_add_del(
1,
{'policy_id': self.policy_id,
'acl_index': self.acl.acl_index,
'n_paths': len(self.paths),
'paths': self.encoded_paths})
self._test.regi | stry.register(self, self._test.logger)
def remove_vpp_config(self):
self._test.vapi.abf_policy_add_del(
0,
{'policy_id': self.policy_id,
'acl_index': self.acl.acl_index,
'n_paths': len(self.paths),
'paths': self.encoded_paths})
def query_v... |
niwinz/django-greenqueue | greenqueue/scheduler/thread_scheduler.py | Python | bsd-3-clause | 449 | 0.002227 | # -*- coding: utf-8 -*-
f | rom threading import Thread, Lock
from time import sleep
from .base import SchedulerMixin
class Scheduler(SchedulerMixin, Thread):
"""
Threading scheduler.
"""
def sleep(self, seconds):
if seconds == 0:
return
sleep(seconds)
def return_callback(self, *args):
... | return self.callback(*args)
def run(self):
self.start_loop()
|
zagfai/webtul | webtul/log.py | Python | mit | 1,135 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Log Config
"""
__author__ = 'Zagfai'
__date__ = '2018-06'
SANIC_LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format':
'%(levelname)s [%(asctime)s %(name)s:%(lineno)d] %(me... | %H:%M:%S',
},
"access": {
"format": "VISIT [%(asctime)s %(host)s]: " +
"%(request)s %(message)s | %(status)d %(byte)d",
'datefmt': '%y%m%d %H:%M:%S',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'default',
},
"access_console": {
"class": "logging.StreamHandler",
"formatter": "acces... |
unreal666/outwiker | src/outwiker/gui/preferences/wikieditorpanel.py | Python | gpl-3.0 | 1,446 | 0 | # -*- coding: utf-8 -*-
import wx
from outwiker.gui.editorstyleslist import EditorStylesList
from outwiker.pages.wiki.wikiconfig import WikiConfig
from outwiker.gui.preferences.baseprefpanel import BasePrefPanel
class WikiEditorPanel(BasePrefPanel):
def __init__(self, parent, application):
super(type(se... | "Link"), self._config.link.value)
self._stylesList.addStyle(_(u"Heading"), self._config.heading.value)
self._stylesList.addStyle(_(u"Command | "), self._config.command.value)
self._stylesList.addStyle(_(u"Comment"), self._config.comment.value)
def Save(self):
self._config.link.value = self._stylesList.getStyle(0)
self._config.heading.value = self._stylesList.getStyle(1)
self._config.command.value = self._stylesList.getStyl... |
urfonline/api | config/wsgi.py | Python | mit | 1,914 | 0 | """
WSGI config for api project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` sett... | roduction"
os.environ.setdefaul | t("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
if os.environ.get('DJANGO_SETTINGS_MODULE') == 'co... |
chrisxue815/leetcode_python | problems/test_0211.py | Python | unlicense | 1,179 | 0 | import unittest
import utils
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
sel | f.root = {}
def addWord(self, word: str) -> None:
curr = self.root
for ch in word:
child = curr.get(ch)
if not child:
c | urr[ch] = child = {}
curr = child
curr['#'] = True
def search(self, word: str) -> bool:
def search(curr, start):
for i in range(start, len(word)):
ch = word[i]
if ch == '.':
for k, v in curr.items():
... |
oemof/reegis-hp | reegis_hp/de21/results.py | Python | gpl-3.0 | 11,607 | 0.000431 | import easygui_qt as easy
import pandas as pd
import numpy as np
import geoplot
from matplotlib import pyplot as plt
import math
from matplotlib.colors import LinearSegmentedColormap
MTH = {'sum': np.sum, 'max': np.max, 'min': np.min, 'mean': np.mean}
class SpatialData:
def __init__(self, result_file=None):
... | rans'] = 3000000
uv = unit_round(s | elf.lines['trans'])
self.lines['trans'] = uv['series']
self.lines['trans'].prefix = uv['prefix']
self.lines['trans'].prefix_long = uv['prefix_long']
return method
def load_geometry(geometry_file=None, region_column='gid'):
if geometry_file is None:
geometry_file = easy.get_... |
agustinhenze/nikola.debian | nikola/data/themes/base/messages/messages_ur.py | Python | mit | 1,784 | 0 | # -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "%d منٹ کا مطالعہ باقی",
"(active)": "(فعال)",
"Also available in:": "ان زبانوں میں بھی دستیاب:",
"Archive": "آرکائیو",
"Categories": "زمرے",
"Comments": "تبصرے",
"LANGUAGE": "اردو",
... | ": "نئی تحاریر",
"Next post": "اگلی تحریر",
"No posts found.": "کوئی تحریر نہیں مل سکی۔",
"Nothing found.": "کچھ نہیں مل سکا۔",
"Older posts": "پرانی تحاریر",
"Original site": "اصلی سائٹ",
"Posted:": "اشاعت:",
"Posts about %s": "%s کے بارے میں تحاریر",
"Posts for year %s": "سال %s کی تحا... | ",
"Previous post": "پچھلی تحریر",
"Publication date": "تاریخِ اشاعت",
"RSS feed": "آر ایس ایس فیڈ",
"Read in English": "اردو میں پڑھیں",
"Read more": "مزید پڑھیں",
"Skip to main content": "مرکزی متن پر جائیں",
"Source": "سورس",
"Subcategories:": "ذیلی زمرے",
"Tags and Categories": "... |
nicoddemus/pytest-xdist | src/xdist/scheduler/each.py | Python | mit | 5,136 | 0 | from py.log import Producer
from xdist.workermanage import parse_spec_config
from xdist.report import report_collection_diff
class EachScheduling:
"""Implement scheduling of test items on all nodes
If a node gets added after the test run is started then it is
assumed to replace a node which got removed ... | l its pending items. The new node will then be
assigned the remaining items from the removed node.
"""
def __init__(self, config, log=None):
self.config = config
self.numnodes = len(parse_spec_config(config))
self.node2collection = {}
self.node2pending = {}
self._st... | self._removed2pending = {}
if log is None:
self.log = Producer("eachsched")
else:
self.log = log.eachsched
self.collection_is_completed = False
@property
def nodes(self):
"""A list of all nodes in the scheduler."""
return list(self.node2pendi... |
sandvine/horizon | openstack_dashboard/api/neutron.py | Python | apache-2.0 | 50,711 | 0.00002 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Cisco Systems, Inc.
# Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use... | min'],
| 'to_port': sgr['port_range_max'],
}
cidr = sgr['remote_ip_prefix']
rule['ip_range'] = {'cidr': cidr} if cidr else {}
group = self._get_secgroup_name(sgr['remote_group_id'], sg_dict)
rule['group'] = {'name': group} if group else {}
super(SecurityGroupRule, self).__init_... |
samastur/flexlayout | flex/settings.py | Python | mit | 5,343 | 0.00131 | import os
gettext = lambda s: s
DATA_DIR = os.path.dirname(os.path.dirname(__file__))
"""
Django settings for flex project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settin... | on_fallback': True,
# },
#],
}
'''
CMS_TEMPLATES = (
# | # Customize this
('fullwidth.html', 'Fullwidth'),
('sidebar_left.html', 'Sidebar Left'),
('sidebar_right.html', 'Sidebar Right')
)
CMS_CACHE_DURATIONS = {
'default': 1,
'menus': 1,
'permissions': 1
}
CMS_PERMISSION = False
CMS_PLACEHOLDER_CACHE = False
CMS_PLACEHOLDER_CONF = {
'page_layo... |
adamredfern92/PlexDownload | plexapi/playqueue.py | Python | mit | 3,815 | 0.002621 | # -*- coding: utf-8 -*-
from plexapi import utils
from plexapi.base import PlexObject
class PlayQueue(PlexObject):
""" Control a PlayQueue.
Attributes:
key (str): This is only added to support playMedia
identifier (str): com.plexapp.plugins.library
initpath (str): Rela... | self.mediaTagVersion = data.attrib.get('mediaTagVersion')
self.playQueueID = data.attrib.get('playQ | ueueID')
self.playQueueSelectedItemID = data.attrib.get('playQueueSelectedItemID')
self.playQueueSelectedItemOffset = data.attrib.get('playQueueSelectedItemOffset')
self.playQueueSelectedMetadataItemID = data.attrib.get('playQueueSelectedMetadataItemID')
self.playQueueShuffled = utils.ca... |
30loops/django-sphinxdoc | setup.py | Python | bsd-3-clause | 1,150 | 0 | #! /usr/bin/env python
from distutils.core import setup
import sys
reload(sys).setdefaultencoding('Utf-8')
setup(
name='django-sphinxdoc',
version='1.0',
author='Stefan Scherfke',
author_email='stefan at sofa-rockers.org',
description='Easily integrate Sphinx documentation into your website.',
... | mplates/sphinxdoc/*'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
| 'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
],
)
|
ikargis/horizon_fod | horizon/messages.py | Python | apache-2.0 | 2,969 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Nebula, 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
#
#... | '', fail_silently=False):
"""Adds a message with the ``DEBUG`` level."""
add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def info(request, message, extra_tag | s='', fail_silently=False):
"""Adds a message with the ``INFO`` level."""
add_message(request, constants.INFO, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def success(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``SUCCESS`` level."""
... |
SiCKRAGETV/SickRage | sickrage/providers/torrent/hdtorrents.py | Python | gpl-3.0 | 6,494 | 0.002156 | # Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation... | except Exception: |
sickrage.app.log.debug("No data returned from provider")
return results
def parse(self, data, mode, **kwargs):
"""
Parse search results from data
:param data: response data
:param mode: search mode
:return: search results
"""
re... |
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx/main/tests/factories/__init__.py | Python | apache-2.0 | 486 | 0 | from .tower import (
create_instance,
create_instance_group,
create_organization,
create_job_template,
create_notification_template,
create_survey_spec,
cr | eate_workflow_job_template,
)
from .exc import (
NotUnique,
)
__all__ = [
'create_instance',
'create_instance_group',
'create_organization',
'create_job_template',
'cre | ate_notification_template',
'create_survey_spec',
'create_workflow_job_template',
'NotUnique',
]
|
JohnLZeller/dd-agent | checks.d/elastic.py | Python | bsd-3-clause | 23,162 | 0.005008 | # stdlib
from collections import namedtuple
import socket
import subprocess
import time
import urlparse
# 3p
import requests
# project
from checks import AgentCheck
from config import _is_affirmative
from util import headers, Platform
class NodeNotFound(Exception): pass
ESInstanceConfig = namedtuple(
'ESInsta... | v: float(v)/1000),
"elasticsearch.flush.total": ("gauge", "indices.flush.total"),
"elasticsearch.flush.total.time": ("gauge", "indices.flush.total_time_in_millis", lambda v: float(v)/1000),
"elasticsearch.process.open_fd": ("gauge", "process.open_file_descriptors"),
"elasticsearch.transp... |
"elasticsearch.transport.rx_size": ("gauge", "transport.rx_size_in_bytes"),
"elasticsearch.transport.tx_size": ("gauge", "transport.tx_size_in_bytes"),
"elasticsearch.transport.server_open": ("gauge", "transport.server_open"),
"elasticsearch.thread_pool.bulk.active": ("gauge", "thread_p... |
vlkv/reggata | reggata/data/commands.py | Python | gpl-3.0 | 40,730 | 0.004444 | '''
Created on 23.07.2012
@author: vlkv
'''
from sqlalchemy.orm import contains_eager, joinedload_all
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import ResourceClosedError
import shutil
import datetime
import logging
import os.path
import reggata.errors as err
import reggata.helpers as hlp
import ... | emsByParseTree(self, query_tree, limit, page, order_by):
order_by_1 = ""
order_by_2 = ""
for col, direction in order_by:
if order_by_1:
order_by_1 += ", "
if order_by_2:
order_by_2 += ", "
order_by_2 += col + " " + direction + "... | direction + " "
if order_by_1:
order_by_1 = " ORDER BY " + order_by_1
if order_by_2:
order_by_2 = " ORDER BY " + order_by_2
sub_sql = query_tree.interpret()
if page < 1:
raise ValueError("Page number cannot be negative or zero.")
if limit <... |
PyFilesystem/pyfilesystem2 | examples/upload.py | Python | mit | 523 | 0 | """
Upload a file to a server (or o | ther filesystem)
Usage:
| python upload.py FILENAME <FS URL>
example:
python upload.py foo.txt ftp://example.org/uploads/
"""
import os
import sys
from fs import open_fs
_, file_path, fs_url = sys.argv
filename = os.path.basename(file_path)
with open_fs(fs_url) as fs:
if fs.exists(filename):
print("destination exists! ab... |
zhuangjun1981/retinotopic_mapping | retinotopic_mapping/examples/signmap_analysis/scripts/script_analysis.py | Python | gpl-3.0 | 1,015 | 0.003941 | __author__ = 'junz'
import os
import matplotlib.pyplot as plt
import retinotopic_mapping.RetinotopicMapping as rm
from tools import FileTools as ft
trialName = "160211_M214522_Trial1.pkl"
isSave = True
params = {'phaseMapFilterSigma': 1.,
'signMapFilterSigma': 9.,
'signMapThr': 0.3,
'e... | nerateTrialDict()
trial.plotTrial(isSave=isSave,saveFolder=currFolder)
plt.show()
if i | sSave:
ft.saveFile(trial.getName()+'.pkl',trialDict)
|
dakcarto/QGIS | python/plugins/processing/modeler/ModelerParametersDialog.py | Python | gpl-2.0 | 27,476 | 0.001237 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ModelerParametersDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************... | self.verticalLayout2 = QVBoxLayout()
self.verticalLayout2.setSpacing(2)
self.verticalLayout2.setMargin(0)
self.tabWidget = QTabWidget()
self.tabWidget.setMinimumWidth(300)
self.paramPanel = QWidget()
self.paramPanel.setLayout(sel | f.verticalLayout)
self.scrollArea = QScrollArea()
self.scrollArea.setWidget(self.paramPanel)
self.scrollArea.setWidgetResizable(True)
self.tabWidget.addTab(self.scrollArea, self.tr('Parameters'))
self.webView = QWebView()
html = None
url = None
isText, he... |
sebrandon1/nova | nova/tests/unit/virt/xenapi/stubs.py | Python | apache-2.0 | 14,212 | 0.000141 | # Copyright (c) 2010 Citrix Systems, 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 la... | xception raised by fake _attach_disks")
stubs.Set(vmops.VMOps, '_attach_disks', f)
def _make_fake_vdi():
sr_ref = fake.get_all('SR')[0]
vdi_ref = fake.create_vdi('', sr_ref)
vdi_rec = fake.get_record('VDI', vdi_ref)
return | vdi_rec['uuid']
class FakeSessionForVMTests(fake.SessionBase):
"""Stubs out a XenAPISession for VM tests."""
_fake_iptables_save_output = ("# Generated by iptables-save v1.4.10 on "
"Sun Nov 6 22:49:02 2011\n"
"*filter\n"
... |
INCF/pybids | bids/conftest.py | Python | mit | 1,063 | 0.003763 | """
This module allows you to mock the config file as needed.
A default fixture that simply returns a safe-to-modify copy of
the default value is provided.
This can be overridden by parametrizing over the option you wish to
mock.
e.g.
>>> @pytest.mark.parametrize("extension_initial_dot", (True, False))
... def test_f... | dict('bids.config._settings'):
bids.config._settings['co | nfig_paths'] = config_paths
bids.config._settings['extension_initial_dot'] = extension_initial_dot
yield
|
karimbahgat/PyAgg | __private__/temp_dev/rendererclass3orrevert.py | Python | mit | 12,788 | 0.014154 |
# Check dependencies
import PIL, PIL.Image, PIL.ImageTk
import aggdraw
import affine
import itertools
def grouper(iterable, n):
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=None, *args)
# Main class
class AggRenderer:
"""
This class is used to draw each feature with aggdra... | # add rgb color to each pixel
pass
# Drawing
def coordinate_space(self, bbox=None, center=None, width=None, height=None, lock_ratio=False):
"""
Defines which areas of the screen represent which areas in the
| given drawing coordinates. Default is to draw directly with
screen pixel coordinates. Call this method with no arguments to
reset to this default. The screen coordinates can be specified in
two ways: with a bounding box, or with a coordinate point to center
the view on. WARNING: Curre... |
baverman/cachel | cachel/offload.py | Python | mit | 8,287 | 0.000724 | import logging
from functools import wraps
from collections import deque
from threading import Thread
from time import time, sleep
from .base import make_key_func, get_serializer, get_expire
from .compat import PY2, listitems
log = logging.getLogger('cachel')
class OffloadCacheWrapper(object):
def __init__(self... |
dumps = self.dumps
dumps2 = self.dumps2
fresult = self.func(ids, *args, **kwargs)
if fresult:
to_cache_pairs = listitems(fresult)
to_cache_ids, to_cache_values = zip(*to_cache_pairs)
keys = self. | keyfunc(to_cache_ids, *args, **kwargs)
values = [dumps(r) for r in to_cache_values]
evalues = [dumps2(r, now) for r in values]
self.cache1.mset(zip(keys, values), self.ttl1)
self.cache2.mset(zip(keys, evalues), self.ttl2)
nonexisting_ids = set(ids) - set(fresult)... |
kephale/TuftsCOMP135_Spring2016 | Lecture18/notebooks/Lecture18.py | Python | apache-2.0 | 9,270 | 0.01068 | %matplotlib inline
import itertools
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import scipy
import scipy.spatial
from scipy import linalg
from sklearn.cluster import KMeans
from sklearn import mixture
from scipy.io import arff
from sklearn import datasets
from sklearn import svm
from s... | separating hyperplane that pass through the
# support vectors
b = clf.support_vectors_[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])
# plot the line, the points, and the nearest vectors to the plane
plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(... | :, 1],
s=150, facecolors='none')
#plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.scatter( nX1, nX2, c=colors, s=areas )
ax=plt.gca()
ax.set_xlabel('sepal length')
ax.set_ylabel('sepal width')
plt.axis('tight')
plt.show()
# Plotting kernels for Iris
# Our dataset and targets
nX = preprocessin... |
peterwilletts24/Monsoon-Python-Scripts | rain/land_sea_diurnal/rain_mask_save_lat_lon_west_southern_indian_ocean.py | Python | mit | 7,070 | 0.019378 | import os, sys
import datetime
import iris
import iris.unit as unit
import iris.analysis.cartography
import numpy as np
from iris.coord_categorisation import add_categorised_coord
diag = 'avg.5216'
cube_name_explicit='stratiform_rainfall_rate'
cube_name_param='convective_rainfall_rate'
pp_file_path='/projects/casc... | = cube.coord('grid_latitude').points
lon = cube.coord('grid_longitude').points
|
cs = cube.coord_system('CoordSystem')
if isinstance(cs, iris.coord_systems.RotatedGeogCS):
print ' %s - %s - Unrotate pole %s' % (diag, experiment_id, cs)
lons, lats = np.meshgrid(lon, lat)
lons,lats = iris.analysis.cartography.unrotate_pole(lons,lats, cs.grid_north_pole_longitud... |
meyersj/geotweet | geotweet/tests/unit/mapreduce/utils/lookup_tests.py | Python | mit | 3,949 | 0.003798 | import unittest
import os
from os.path import dirname
import sys
import json
from rtree import index
from . import ROOT
from geotweet.mapreduce.utils.lookup import project, SpatialLookup
testdata = os.path.join(dirname(os.path.abspath(__file__)), 'testdata')
def read(geojson):
return json.loads(open(os.path.joi... | self.location.get_object(point, buffer_size=100000)
self.assertIsNotNone(found, "get_object failed to return object")
error = "get_object failed to return object with id=polygon1: Actual | < {0} >"
self.assertEqual('polygon1', found['id'], error.format(found['id']))
if __name__ == "__main__":
unittest.main()
|
naver/hubblemon | redis_mon/redis_view.py | Python | apache-2.0 | 2,771 | 0.024901 |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# U... | der the License.
#
import os, socket, sys, time
import data_loader
from datetime import datetime
hubblemon_path = os.path.join(os. | path.dirname(__file__), '..')
sys.path.append(hubblemon_path)
import common.core
redis_preset = [['memory', 'memory_human', 'memory_lua', 'memory_rss'], 'mem_frag', ['cpu_user', 'cpu_sys', 'cpu_user_children', 'cpu_sys_children'],
'connections', (lambda x : x['keyspace_hits'] / (x['keyspace_hits'] + x['keyspace_mi... |
Nexenta/s3-tests | virtualenv/lib/python2.7/site-packages/isodate/tests/test_time.py | Python | mit | 6,554 | 0.001984 | ##############################################################################
# Copyright 2009, Gerhard Weis
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code ... | pectation)
def test_format(self):
'''
Take time object and create ISO string from it.
This is the reverse test to test_parse.
'''
if expectation is None:
self.assertRaises(AttributeError,
time_isoforma | t, expectation, format)
elif format is not None:
self.assertEqual(time_isoformat(expectation, format),
timestring)
return unittest.TestLoader().loadTestsFromTestCase(TestTime)
def test_suite():
'''
Construct a TestSuite instance for all test ca... |
miptliot/edx-platform | lms/djangoapps/course_api/tests/test_views.py | Python | agpl-3.0 | 8,978 | 0.002673 | """
Tests for Course API views.
"""
from hashlib import md5
from django.core.urlresolvers import reverse
from django.test import RequestFactory
from nose.plugins.attrib import attr
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase
from ..views import CourseDetailView
f... | e)
def test_as_honor(self):
self.setup_user(self.honor_user)
self.verify_response(params={'username': self.honor_user.username})
def test_as_honor_for_staff(self):
self.setup_user(self.honor_user)
self.verify_response(expected_status_code=403, params={'username': self.staff_use... | elf.staff_user.username})
def test_as_staff_for_honor(self):
self.setup_user(self.staff_user)
self.verify_response(params={'username': self.honor_user.username})
def test_as_anonymous_user(self):
self.verify_response(expected_status_code=200)
def test_as_inactive_user(self):
... |
spikeekips/ampy | ampy/async.py | Python | mit | 7,935 | 0.004789 | """
Asyncore-based implementation of the AMP protocol.
"""
import socket
import threading
import asyncore, asynchat, socket, struct, sys
import defer, ampy
class AMP_Server(asyncore.dispatcher):
def __init__(self, port, bindHost="0.0.0.0"):
self.port = port
self.bindHost = bindHost
asyncor... | AD, VAL_LEN_READ, VAL_DATA_READ = range(4)
class AMP_Protocol(asynchat.async_chat):
current_key = None
counter = 0
box = None
responders = {}
def __init__(self, conn, addr):
asynchat.async_chat.__init__(self, conn)
self.addr = addr
self.ibuffer = []
self.obuffer =... | gisterResponder(self, command, responder):
self.responders[command.commandName] = (command, responder)
def collect_incoming_data(self, data):
"""Buffer the data"""
self.ibuffer.append(data)
def found_terminator(self):
# handle buffered data and transition state
if self... |
vanceeasleaf/aces | aces/runners/phonopy.py | Python | gpl-2.0 | 19,132 | 0 | # -*- coding: utf-8 -*-
# @Author: YangZhou
# @Date: 2017-06-16 20:09:09
# @Last Modified by: YangZhou
# @Last Modified time: 2017-06-27 16:02:34
from aces.tools import mkdir, mv, cd, cp, mkcd, shell_exec,\
exists, write, passthru, toString, pwd, debug, ls, parseyaml
import aces.config as config
from aces.bina... | nts)),
toString(m.premitive.flatten()))
mesh = mesh.replace(r'^\s+', '')
write(mesh, 'v.conf')
def generate_qconf(self, q):
# g | enerate q.conf
m = self.m
mesh = """DIM = %s
ATOM_NAME = %s
FORCE_CONSTANTS = READ
EIGENVECTORS=.TRUE.
QPOINTS=.TRUE.
PRIMITIVE_AXIS = %s
""" % (m.dim, ' '.join(m.elements), toString(m.premitive.flatten()))
mesh = mesh.replace(r'^\s+', '')
... |
eigoshimizu/Genomon | scripts/genomon_pipeline/dna_resource/markduplicates.py | Python | gpl-2.0 | 742 | 0.004043 | #! /usr/bin/env python
from genomon_pipeline.stage_task import *
class Markduplicates(Stage_task):
task_name = "markduplicates"
script_template = """
#!/bin/bash
#
# Set SGE
#
#$ -S /bin/bash # set shell in UGE
#$ -cwd # execute at the submitted dir
pwd # print cu... | t -o pipefail
{bioba | mbam}/bammarkduplicates M={out_prefix}.metrics tmpfile={out_prefix}.tmp markthreads=2 rewritebam=1 rewritebamlevel=1 index=1 md5=1 {input_bam_files} O={out_bam}
"""
def __init__(self, qsub_option, script_dir):
super(Markduplicates, self).__init__(qsub_option, script_dir)
|
avinash-n/work-1 | python_program/day_3/tic_tac_toe.py | Python | gpl-3.0 | 2,433 | 0.085902 | import os
print "Tic Tac Toe".center(50,'-')
l = [['_','_','_'],['_','_','_'],[ | '_','_','_']]
def show(l) :
os.system("clear")
for i in range(0,3) :
for j in range(0,3) :
print l[i][j]," ",
print "\n"
def base() :
print "provided numbers for provided positions"
num = 0
for i in range (0,3) :
for j in range(0,3) :
print num," ",
num += 1
print "\n"
count = 1
while count<... | Its already filled"
pos = input("Enter required position you want to place")
i = pos/3
j = pos%3
l[i][j] = 1
check = 0
for t in range(0,3) :
if l[t][j] == 1 :
check+=1
if check == 3 :
show(l)
print "player 1 won"
exit()
check = 0
for t in range(0,3) :
if l[i][t] == 1 :
check+=1
if check == ... |
velp/nocexec | setup.py | Python | mit | 1,793 | 0.001115 | # -*- coding: utf-8 -*-
"""
NOCExec
-----------------------
Library for automation of management and configuration of network devices
"""
import sys
import os
from setuptools import setup
if sys.version_info < (2, 7):
raise Exception("NOCExec requires Python 2.7 or higher.")
# Hard linking doesn't work inside Vir... | s': ["Sphinx>=1. | 2.3", "alabaster>=0.6.3"]}
) |
unaguil/hyperion-ns2 | experiments/measures/graphsearch/StartedCompositions.py | Python | apache-2.0 | 448 | 0.029018 | from measures.generic.GenericMeasure import GenericMeasure
import measures.generic.Units as Units
class StartedCompositions(GenericMeasure):
"""Total number of started searches"""
def __init__(self, period, simulationTime):
G | enericMeasure.__init__(self, r'DEB | UG .*? - Peer [0-9]+ started composition search \(.*?\).*?([0-9]+\,[0-9]+).*?', period, simulationTime, Units.COMPOSITIONS)
def parseLine(self, line):
self.parseInc(line)
|
catholabs/esengine | esengine/mapping.py | Python | mit | 4,930 | 0 | import collections
class Mapping(object):
"""
Used to generate mapping based in document field definitions
>>> class Obj(Document):
... name = StringField()
And you can use a Mapping to refresh mappings
(use in cron jobs or call periodically)
obj_mapping = Mapping(Obj)
obj_mappi... | ng(
doc_type=self.document_class._doctype,
index=self.document_class._index,
body=self.generate()
)
def build_configuration(self, models_to_mapping, custom_settings, es=None):
"""
Build request body to add custom settings (filters, analize... | rgs:
models_to_mapping: A list with the esengine.Document objects that
we want generate mapping.
custom_settings: a dict containing the configuration that will be
sent to elasticsearch/_settings (www.elastic.co/guide/en/
elasticsearch/reference/current/in... |
VerticalMediaProjects/cmsplugin-photologue-pro | cmsplugin_photologue_pro/sitemaps.py | Python | bsd-3-clause | 464 | 0 | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.contrib.sitemaps import | Sitemap
from photologue.models import Gallery
class AlbumSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
return Gallery.objects.filter(is_public=True)
def lastmod(self, obj):
return obj.date_added
def location(self, obj):
| return reverse('photologue_album', kwargs={'album': obj.pk})
|
makielab/django-oscar | sites/sandbox/apps/offers.py | Python | bsd-3-clause | 584 | 0 | from oscar.apps.offer import models
class ChangesOwnerName(models.Benefit):
class Meta:
proxy = True
def apply(self, basket, condition, offer=None):
condition.consume_items(basket, ())
| return models.PostOrderAction(
"You will have your name changed to Barry!")
def apply_deferred(self, basket):
if basket.owner:
basket.owner.first_name = "Barry"
basket.owner.save()
return "Your name has bee | n changed to Barry!"
@property
def description(self):
return "Changes owners name"
|
concentricsky/badgecheck | openbadges/verifier/actions/utils.py | Python | apache-2.0 | 67 | 0 | import uuid
d | ef generate_task_key():
return uui | d.uuid4().hex
|
srivatsan-ramesh/HDMI-Source-Sink-Modules | hdmi/cores/primitives/dram16xn.py | Python | mit | 2,112 | 0.00142 | from myhdl import block
from hdmi.cores.primitives import ram16x1d
inst_count = 0
@block
def dram16xn(data_in, address, address_dp, write_enable, clock,
o_data_out, o_data_out_dp, data_width=30):
"""
Implements a Distributed SelectRAM with Dual port 16 x N-bit.
It will be replaced by a ve... | _dp: Dual port address
write_enable: write enable for the RAM16X1D
clock: write clock
o_data_out: single port output
o_data_out_dp: dual port output
data_width: number of words stored in the DRAM
Returns:
myhdl.instances() : A list of myhdl instances.
"""
g... | += 1
return ram16x1d_inst
dram16xn.verilog_code = """
genvar i_$inst_count;
generate
for(i_$inst_count = 0 ; i_$inst_count < $data_width ; i_$inst_count = i_$inst_count + 1) begin : dram16s_$inst_count
RAM16X1D i_RAM16X1D_U_$inst_count(
.D($data_in[i_$inst_count]), //insert input signal
... |
dorey/pyxform | pyxform/instance.py | Python | bsd-2-clause | 3,121 | 0.00769 | from xform_instance_parser import parse_xform_instance
class SurveyInstance(object):
def __init__(self, survey_object, **kwargs):
self._survey = survey_object
self.kwargs = kwargs #not sure what might be passed to this
#does the survey object provide a way to get the key dicts?
s... | self._name,
'id': self._id,
'children': child | ren
}
def to_xml(self):
"""
A horrible way to do this, but it works (until we need the attributes pumped out in order, etc)
"""
open_str = """<?xml version='1.0' ?><%s id="%s">""" % (self._name, self._id)
close_str = """</%s>""" % self._name
vals = ""... |
Julian/giraffe | giraffe/tests/test_core.py | Python | mit | 13,956 | 0.00172 | import unittest
import giraffe as c
import giraffe.exceptions as exc
def make_graph_tst(cls):
class Test(unittest.TestCase):
def test_eq_ne(self):
g = cls()
g2 = cls()
self.assertEqual(g, g2)
self.assertEqual(g2, g)
g.add_vertex(1)
... | e(1, 2)
self.assertEqual(g, g2)
self.assertEqual(g2, g)
def te | st_le_lt_gt_ge(self):
g = cls()
g2 = cls()
self.assertLessEqual(g, g2)
self.assertLessEqual(g2, g)
self.assertGreaterEqual(g, g2)
self.assertGreaterEqual(g2, g)
g.add_vertices({1, 2, 3})
g.add_edges({(1, 2), (2, 3)})
... |
SeerLabs/PDFMEF | src/extractor/run_extraction.py | Python | apache-2.0 | 2,199 | 0.003183 | from extraction.core import ExtractionRunner
from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult
import os
import sys
import extractor.csxextract.extractors.grobid as grobid
import extractor.csxextract.extractors.pdfbox as pdfbox
import extractor.csxextract.extractors.tei as tei
import ex... | ""folders = []
files = []
prefixes = []"""
if file[-4:] == '.pdf':
files.append(path + file)
folders.append(outputDir + file[:-4])
| prefixes.append(file[:-4])
#print dir
print file
runner.run_from_file_batch(files, folders, num_processes=8, file_prefixes=prefixes)
print 'done'
"""argc = len(sys.argv)
if argc == 2:
file_name = os.path.splitext(os.path.basename(sys.argv[1]))[0]
runner.run_from_file(s... |
sserrot/champion_relationships | venv/Lib/site-packages/cffi/__init__.py | Python | mit | 513 | 0 | __all__ = ['FFI', 'VerificationEr | ror', 'VerificationMissing', 'CDefError | ',
'FFIError']
from .api import FFI
from .error import CDefError, FFIError, VerificationError, VerificationMissing
from .error import PkgConfigError
__version__ = "1.14.2"
__version_info__ = (1, 14, 2)
# The verifier module file names are based on the CRC32 of a string that
# contains the following versio... |
BlackHole/enigma2-obh10 | lib/python/Screens/SoftwareUpdate.py | Python | gpl-2.0 | 19,545 | 0.021949 | from boxbranding import getImageVersion, getImageBuild, getImageDevBuild, getImageType, getImageDistro, getMachineBrand, getMachineName, getMachineBuild
from os import path
from gettext import dgettext
from enigma import eTimer, eDVBDB
import Components.Task
from Components.OnlineUpdateCheck import feedsstatuscheck, ... | ocheck time too.
#
from time import time
config.softwareupdate.updatelastcheck.setValue(int(time()))
config.softwareupdate.updatelastcheck.save()
from Components.OnlineUpdateCheck import onlineupdatecheckpoller
onlineupdatecheckpoller.start()
def isProtected(self):
return config.ParentalControl.setuppinac... | not config.ParentalControl.config_sections.configuration.value or hasattr(self.session, 'infobar') and self.session.infobar is None) and\
config.ParentalControl.config_sections.software_update.value
def doActivityTimer(self):
self.activity += 1
if self.activity == 100:
self.activity = 0
self.activityslid... |
samuelcolvin/aiohttp-devtools | aiohttp_devtools/runserver/__init__.py | Python | mit | 97 | 0 | # flake8: noqa |
from .config import INFER_HOST
f | rom .main import run_app, runserver, serve_static
|
napalm-automation/napalm-yang | napalm_yang/models/openconfig/components/component/transceiver/physical_channels/channel/state/__init__.py | Python | apache-2.0 | 34,214 | 0.001257 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | n",
is_config=False,
)
self.__target_output_power = YANGDynClass(
base=RestrictedPrecisionDecimalType(precision=2),
is_leaf=True,
yang_name="target-output-power",
| parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/platform/transceiver",
defining_module="openconfig-platform-transceiver",
yang_type="decimal64",
i... |
EthanBlackburn/flanker | flanker/mime/message/headers/headers.py | Python | apache-2.0 | 4,810 | 0.000208 | from webob.multidict import MultiDict
from flanker.mime.message.headers import encodedword
from flanker.mime.message.headers.parsing import normalize, parse_stream
from flanker.mime.message.headers.encoding import to_mime
from flanker.mime.message.errors import EncodingError
class MimeHeaders(object):
"""Diction... | to_stream(self, stream, prepends_only=False):
"""
| Takes a stream and serializes headers in a mime format.
"""
i = 0
for h, v in self.iteritems(raw=True):
if prepends_only and i == self.num_prepends:
break
i += 1
try:
h = h.encode('ascii')
except UnicodeDecode... |
shlomimatichin/workflow | workflow/ticket/views.py | Python | gpl-3.0 | 10,924 | 0.065727 | from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.views.decorators import cache
from workflow.ticket import forms
from workflow.ticket import models
from workflow.ticket import tickettree
import pp... | try:
result.append( models.Ticket.objects.get( id = id ) )
except:
pass
return result
def | _render( request, template, lastViewedTickets = None, ** kwargs ):
if lastViewedTickets is None:
lastViewedTickets = _lastViewedTickets( request )
kwargs[ 'lastViewedTickets' ] = reversed( lastViewedTickets )
return render.render( request, "ticket/" + template, ** kwargs )
@login_required
@cache.never_cache
@debu... |
Kozea/CairoSVG | test_non_regression/__init__.py | Python | lgpl-3.0 | 796 | 0 | """
Cairo test suite.
"""
import imp
import os
impor | t cairosvg
reference_cairosvg = imp.load_source(
'cairosvg_reference', pathname=os.path.join(
os.path.dirname(__file__), 'cairosvg_reference', 'cairosvg',
'__init__.py'))
cairosvg.features.LOCALE = reference_cairosvg.features.LOCALE = 'en_US'
TEST_FOLDER = os.path.join(os.path.dirname(__file__), ... | viron['CAIROSVG_TEST_FILES'].split(',')
else:
ALL_FILES = os.listdir(TEST_FOLDER)
ALL_FILES.sort(key=lambda name: name.lower())
FILES = [
os.path.join(
os.path.dirname(TEST_FOLDER) if name.startswith('fail')
else TEST_FOLDER, name)
for name in ALL_FILES]
|
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/pylint/checkers/python3.py | Python | apache-2.0 | 38,460 | 0.00169 | # Copyright (c) 2014-2015 Brett Cannon <[email protected]>
# Copyright (c) 2014-2016 Claudiu Popa <[email protected]>
# Copyright (c) 2015 Pavel Roskin <[email protected]>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
... | W1610': ('reduce built-in referenced',
'reduce-builtin',
'Used when the reduce built-in function is referenced '
'(missing from | Python 3)',
{'maxversion': (3, 0)}),
'W1611': ('StandardError built-in referenced',
'standarderror-builtin',
'Used when the StandardError built-in function is referenced '
|
old-paoolo/hokuyo-python-lib | setup.py | Python | mit | 1,228 | 0 | # coding=utf-8
# !/usr/bin/env python
try:
from setuptools import setup
except ImportError:
print('No setuptools installed, use distutils')
from distutils.core import setup
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name='hokuyo-python-lib',
packages=[
... | d-paoolo/hokuyo-python-lib',
keywords=[
'hokuyo'
],
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Environment :: Other Environment',
'Intended Audience :: Developers',
'License :: Other/Proprietary License',
| 'Operating System :: OS Independent',
],
long_description='''\
'''
)
|
BielBdeLuna/idTechX_Python_API | text_file.py | Python | gpl-3.0 | 1,232 | 0.016234 | import utils
class text_file:
lines = []
def gather_lines_from_file( filename ):
with open(filename) as f:
lines = f.readlines()
self.lines = lines
def discard_lines_from_file():
correct_lines = []
comment = False
asterisk = False
data_in_that_... | = 0
data_in_that_line = Fals | e
comment = True
i = i + 1
if comment == False and data_in_that_line == True:
correct_lines_string = ''.join(correct_lines)
correct_lines.append(correct_lines_string)
self.lines = correct_lines
... |
IPMITMO/statan | coala-bears/bears/latex/LatexLintBear.py | Python | mit | 886 | 0 | from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.DistributionRequirement import (
DistributionRequirement)
@li | nter(executable='chktex',
output_format='regex',
output_regex=r'(?P<severity>Error|Warning) \d+ in .+ line '
r'(?P<line>\d+): (?P<message>.*)')
class LatexLintBear:
"""
Ch | ecks the code with ``chktex``.
"""
LANGUAGES = {'Tex'}
REQUIREMENTS = {DistributionRequirement('chktex', zypper='texlive-chktex')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'[email protected]'}
LICENSE = 'AGPL-3.0'
CAN_DETECT = {'Syntax', 'Formatting'}
@staticmetho... |
brownian/frescobaldi | frescobaldi_app/hyphenator.py | Python | gpl-2.0 | 8,884 | 0.001126 | """
This is a Pure Python module to hyphenate text.
It is inspired by Ruby's Text::Hyphen, but currently reads standard *.dic files,
that must be installed separately.
In the future it's maybe nice if dictionaries could be distributed together with
this module, in a slightly prepared form, like in Ruby's Text::Hyphe... | self.patterns.get(prepWord[i:j])
if p:
offset, values = p
s = slice(i + offset, i + offset + len(values))
res[s] = map(max, values, res[s])
positions = [DataInt(i - 1, ref=r) for i, r in enumerate(res) if r % 2]
| self.cache[word] = positions
return positions
class Hyphenator(object):
"""Reads a hyph_*.dic file and stores the hyphenation patterns.
Provides methods to hyphenate strings in various ways.
Parameters:
-filename : filename of hyph_*.dic to read
-left: make the first syllable not shor... |
state-hiu/rogue_geonode | geoshape/views.py | Python | gpl-3.0 | 3,021 | 0.001655 | import logging
from django.conf import settings
from django.http import HttpResponse
from django.http.request import validate_host
from django.utils.http import is_safe_url
from httplib import HTTPConnection, HTTPSConnection
from urlparse import urlsplit
from geonode.geoserver.helpers import ogc_server_settings
logger... | content_type="text/plain"
)
raw_url = request.GET['url']
url = urlsplit(raw_url)
locator = url.path
if url.query != "":
locator += '?' + url.query
if url.fragment != "":
locator += '#' + url.fragment
logger.debug('Incoming headers: {0}'.format... | alse but the host of the path provided "
"to the proxy service is not in the "
"PROXY_ALLOWED_HOSTS setting.",
status=403,
content_type="text/plain"
)
heade... |
vicnet/weboob | modules/regionsjob/__init__.py | Python | lgpl-3.0 | 847 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Bezleputh
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/ | or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This weboob module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied... | e details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this weboob module. If not, see <http://www.gnu.org/licenses/>.
from .module import RegionsjobModule
__all__ = ['RegionsjobModule']
|
openstack/smaug | karbor/services/protection/client_factory.py | Python | apache-2.0 | 3,806 | 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
# d... | eystone_plugin
| @classmethod
def get_client_module(cls, service):
if not cls._factory:
cls._factory = {}
for module in cls._list_clients():
module = importutils.import_module(module)
cls._factory[module.SERVICE] = module
return cls._factory.get(service)
@... |
MSFTOSSMgmt/WPSDSCLinux | Providers/nxOMSAutomationWorker/automationworker/3.x/worker/urllib2httpclient.py | Python | mit | 9,775 | 0.003581 | #!/usr/bin/env python3
# ====================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# ====================================
"""Urllib2 HttpClient."""
import httplib
import socket
import time
import traceback
import urllib2
from httpclient import *
from workerexception import *
P... | temptExceededException(traceback.format_exc())
elif SSL_MODULE_NAME in sys.modules:
if type(exception).__name__ == 'SSLError':
time.sleep(5 + iteration)
| continue
elif isinstance(exception, urllib2.URLError):
if "name resolution" in exception.reason:
time.sleep(5 + iteration)
continue
raise exception
return decorated_func
class Urllib2HttpClient(HttpClient)... |
urisimchoni/samba | third_party/waf/wafadmin/Logs.py | Python | gpl-3.0 | 2,875 | 0.041739 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005 (ita)
import ansiterm
import os, re, logging, traceback, sys
from Constants import *
zones = ''
verbose = 0
colors_lst = {
'USE' : True,
'BOLD' :'\x1b[01;1m',
'RED' :'\x1b[01;31m',
'GREEN' :'\x1b[32m',
'YELLOW':'\x1b[33m',
'PINK' :'\x1b[35m',
'BLUE' :'... | zones
elif not verbose > 2:
return False
return True
class formatter(logging.Formatter):
def __init__(self):
logging.Formatter.__init__(self, LOG_FORMAT, HOUR_FORMAT)
def format(self, rec):
if rec.levelno >= | logging.WARNING or rec.levelno == logging.INFO:
try:
return '%s%s%s' % (rec.c1, rec.msg.decode('utf-8'), rec.c2)
except:
return rec.c1+rec.msg+rec.c2
return logging.Formatter.format(self, rec)
def debug(*k, **kw):
if verbose:
k = list(k)
k[0] = k[0].replace('\n', ' ')
logging.debug(*k, **kw)
d... |
petertodd/timelock | lib/python-bitcoinlib/bitcoin/rpc.py | Python | gpl-3.0 | 16,944 | 0.002833 | # Copyright 2011 Jeff Garzik
#
# RawProxy has the following improvements over python-jsonrpc's ServiceProxy
# class:
#
# - HTTP connections persist for the life of the RawProxy object (if server
# supports HTTP/1.1)
# - sends protocol 'version', per JSON-RPC 1.1
# - sends proper, incrementing 'id'
# - sends Basic HTT... | code': -342, 'message': 'missing HTTP response from server'})
return json.loads(http_response.read().decode('utf8'),
parse_float=decimal.Decimal)
class Proxy(RawProxy):
def __init__(self, service_url=None,
service_port=None,
btc_conf... | **kwargs):
"""Create a proxy to a bitcoin RPC service
Unlike RawProxy data is passed as objects, rather than JSON. (not yet
fully implemented) Assumes Bitcoin Core version >= 0.9; older versions
mostly work, but there are a |
mitsuhiko/celery | celery/serialization.py | Python | bsd-3-clause | 4,714 | 0.000636 | import inspect
import sys
import types
from copy import deepcopy
import pickle as pypickle
try:
import cPickle as cpickle
except ImportError:
cpickle = None
if sys.version_info < (2, 6):
# cPickle is broken in Python <= 2.5.
# It unsafely and incorrectly uses relative instead of absolute imports,
... | urn types.ClassType(name, (parent,), {})
else:
def subclass_exception(name, parent, module):
return type(name, (parent,), {'__m | odule__': module})
def find_nearest_pickleable_exception(exc):
"""With an exception instance, iterate over its super classes (by mro)
and find the first super exception that is pickleable. It does
not go below :exc:`Exception` (i.e. it skips :exc:`Exception`,
:class:`BaseException` and :class:`object`... |
twisted/quotient | xquotient/exmess.py | Python | mit | 95,030 | 0.002041 | # -*- test-case-name: xquotient.test.test_workflow -*-
"""
This module contains the core messaging abstractions for Quotient. L{Message},
a transport-agnostic message metadata representation, and L{MailboxSelector}, a
tool for specifying constraints for and iterating sets of messages.
"""
from os import path
import ... | ibuteCopyingUpgrader, registerUpgrader
from xmantissa import ixmantissa, people, webapp, liveform, webnav
from xmantissa.prefs import PreferenceCollectionMixin
from xmantissa.publicresource import getL | oader
from xmantissa.fragmentutils import PatternDictionary, dictFillSlots
from xmantissa.webtheme import ThemedElement
from xquotient import gallery, equotient, scrubber, mimeutil, mimepart, renderers
from xquotient.actions import SenderPersonFragment
from xquotient.renderers import replaceIllegalChars, ButtonRenderi... |
tfmorris/dedupe | dedupe/variables/exists.py | Python | mit | 1,117 | 0.016115 | from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
... |
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
|
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
|
cyandterry/Python-Study | Ninja/Leetcode/12_Integer_to_Roman.py | Python | mit | 614 | 0.003257 | """
Given an integer, convert it to a roman | numeral.
Input is guaranteed to be within the range from 1 to 3999.
"""
class Solution:
# @return a string
def intToRoman(self, num):
digits = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD' ),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), ... | ]
result = ""
for digit in digits:
while num >= digit[0]:
result += digit[1]
num -= digit[0]
if num == 0:
break
return result
|
GirlsCodePy/girlscode-coursebuilder | modules/search/search.py | Python | gpl-3.0 | 20,482 | 0.000244 | # Copyright 2013 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 ... |
from models import jobs
from models import services
from models import transforms
from modules.dashboard import dashboard
from google.appengine.api import namespace_manager
from google.appengine.api import search
from googl | e.appengine.ext import db
MODULE_NAME = 'Full Text Search'
DEPRECATED = config.ConfigProperty(
'gcb_can_index_automatically', bool, safe_dom.Text(
'This property has been deprecated; it is retained so that we '
'will not generate no-such-variable error messages for existing '
'installation... |
tristeen/RTS-Simulator | rts/mMap.py | Python | mit | 7,527 | 0.031088 | import mUnit
from mUnit import UNIT_NONE, UNIT_SOLDIER, UNIT_BASE, UNIT_WORKER, UNITS, UNIT_RES
from mUnit import NoneUnit
from misc import mTimer
from misc.mLogger import log
from mCamp import Camp
LENGTH, HEIGTH = 20, 20
POPULATION_LIMIT = 20
class mArray(object):
def __init__(self, length, heigth):
self.lengt... | x][dst_y], self.data_[src_x][src_y]
self.index_[self.data_[src_x][src_y].id] = (self.data_[src_x][src_y], (src_x, src_y))
self.index_[self.data_[dst_x][dst_y].id] = (self.data_[dst_x][dst_y], (dst_x, dst_y))
def delete(self, (x, y)):
u = self.data_[x][y]
#if hasattr(u, 'camp_') and u.type not in | (0, 4):
# self.camps_[u.camp_].del_unit(u)
self.index_.pop(u.id)
self.data_[x][y] = NoneUnit
#self.data_[x][y].map_ = u.map_
def get_unit_pos(self, _unit):
if _unit.id in self.index_:
return self.index_[_unit.id][1]
log.warning('get_unit_pos out of index_')
for u, i, j in self:
if u.id == _unit.id... |
tomkralidis/geonode | geonode/base/migrations/0040_merge_20200321_2245.py | Python | gpl-3.0 | 263 | 0 | # | Generated by Django 2.2.11 on 2020-03-21 22:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ba | se', '0038_delete_backup'),
('base', '0039_auto_20200321_1338'),
]
operations = [
]
|
ysig/BioClassSim | source/graph/__init__.py | Python | apache-2.0 | 29 | 0 | from p | roximityGraph import *
| |
fozzysec/tieba-keyword-spider | tieba/items.py | Python | bsd-3-clause | 730 | 0.00274 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TiebaItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
p | ass
class ThreadItem(scrapy.Item):
url = scrapy.Field()
title = scrapy.Field()
preview = scrapy.Field()
author = scrapy.Field()
tieba = scrapy.Field()
date = scrapy. | Field()
keywords = scrapy.Field()
class NoneItem(scrapy.Item):
url = scrapy.Field()
title = scrapy.Field()
preview = scrapy.Field()
author = scrapy.Field()
tieba = scrapy.Field()
date = scrapy.Field()
keywords = scrapy.Field()
|
gibiansky/tensorflow | tensorflow/contrib/rnn/python/ops/rnn_cell.py | Python | apache-2.0 | 52,642 | 0.005813 | # Copyright 2015 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... | lections
import math
from tensorflow.contrib.layers.python.layers import layers
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.pyth | on.ops import array_ops
from tensorflow.python.ops import clip_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import v... |
Mause/resumable | main.py | Python | mit | 673 | 0 | from resumable import split, rebuild
import requests
def get(s):
return s
@rebuild
def example(_):
print('this is a good start')
value = split(requests.get, 'first')('http://ms.mause.me')
print(v | alu | e.text)
value = split(lambda: 'hello', 'second')()
print('hello', value)
split(print, 'derp')()
a, b, c = split(get, 'multiple')('abc')
print(a, b, c)
return split(get)('otherworldly')
def main():
arg = None
for name, func in example.items():
if func.__code__.co_argcount ... |
dcdanko/pyarchy | py_archy/py_archy.py | Python | mit | 1,433 | 0.010468 | # -*- coding: utf-8 -*-
def archy( obj, prefix='', unicode=True):
def chr(s):
chars = {'\u000d' : '\n',
'\u2502' : '|',
'\u2514' : '`',
'\u251c' : '+',
'\u2500' : '-',
'\u252c' : '-'}
if not unicode:
re... | ' + prefix + chr('\u2502') + ' '
def mapNodes(nodes):
out | = []
for i, node in enumerate(nodes):
last = i == len(nodes) -1
more = (type(node) != str) and ('nodes' in node) and len(node['nodes'])
prefix_ = prefix + chr('\u2502') + ' '
if last:
prefix_ = prefix + ' '
outs = (prefix +
... |
turbokongen/home-assistant | tests/components/philips_js/conftest.py | Python | apache-2.0 | 1,756 | 0.001708 | """Standard setup for tests."""
from unittest.mock import Mock, patch
from pytest import fixture
from homeassistant import setup
from homeassistant.components.philips_js.const import DOMAIN
from . import MOCK_CONFIG, MOCK_ENTITY_ID, MOCK_NAME, MOCK_SERIAL_NO, MOCK_SYSTEM
from tests.common import MockConfigEntry, mo... | "
await setup.async_setup_component(hass, "persistent_notifica | tion", {})
@fixture(autouse=True)
def mock_tv():
"""Disable component actual use."""
tv = Mock(autospec="philips_js.PhilipsTV")
tv.sources = {}
tv.channels = {}
tv.system = MOCK_SYSTEM
with patch(
"homeassistant.components.philips_js.config_flow.PhilipsTV", return_value=tv
), patc... |
marcgibbons/drf_signed_auth | tests/settings.py | Python | bsd-2-clause | 275 | 0 | SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.cont | rib.sessio | ns',
'tests',
'tests.unit'
]
ROOT_URLCONF = 'tests.integration.urls'
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
|
seekheart/coder_api | tests/app_test.py | Python | mit | 5,800 | 0 | import base64
import json
import unittest
from app import app
class AppTest(unittest.TestCase):
def setUp(self):
"""Setup method for spinning up a test instance of app"""
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
self.app = app.test_client()
self.... | t_type)
self.assertEquals(result.status_code, 409)
def test_patch_single_use | r(self):
"""Unit test for editing a user"""
self.app.post('/users', data=self.dummy_user,
headers=self.authorization,
content_type=self.content_type)
result = self.app.patch('/users/dummy', data=self.dummy_user,
header... |
jamestwhedbee/diogenes | tests/test_modify.py | Python | mit | 8,979 | 0.012585 | import unittest
import numpy as np
from collections import Counter
from diogenes.utils import remove_cols,cast_list_of_list_to_sa
import utils_for_tests
import unittest
import numpy as np
from numpy.random import rand
import diogenes.read
import diogenes.utils
from diogenes.modify import remove_cols_where
from diog... | e_missing_vals(M, 'constant', constant=-1.0)
self.asser | tTrue(np.array_equal(ctrl, res))
ctrl = M.copy()
ctrl['int'] = np.array([100, 1, -999, 1, -999])
ctrl['float1'] = np.array([100, 1.0, np.nan, np.nan, 2.0])
ctrl['float2'] = np.array([0.1, np.nan, 100, 0.2, np.nan])
res = replace_missing_vals(M, 'constant', missing_val=0, constan... |
marcelometal/holmes-api | holmes/search_providers/noexternal.py | Python | mit | 2,143 | 0.0014 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from holmes.search_providers import SearchProvider
from holmes.models.review import Review
from tornado.concurrent import return_future
class NoExternalSearchProvider(SearchProvider):
def __init__(self, config, db, authnz_wrapper=None, io_loop=None):
self.db... | reviews = Review.get_by_violation_key_name(
db=self.db,
key_id=key_id,
current_page=current_page,
page_size=page_size,
domain_filter=domain.name if domain else None,
page_filter=page_filter,
)
reviews_data = []
for item... | : item.page_uuid,
'url': item.url,
'completedAt': item.completed_date
},
'domain': item.domain_name,
})
callback({
'reviews': reviews_data
})
@return_future
def get_domain_active_reviews(self, domai... |
SwissTPH/openhds-sim | submission.py | Python | gpl-2.0 | 13,836 | 0.006577 | #!/usr/bin/env python
"""Test form submission"""
__email__ = "[email protected]"
__status__ = "Alpha"
from lxml import etree
import urllib2
import uuid
import logging
DEVICE_ID = "8d:77:12:5b:c1:3c"
def submit_data(data, url):
"""Submit an instance to ODKAggregate"""
r = urllib2.Request(url, data=da... | ", cause_of_death], ["dateOfDeath", date_of_death],
["placeOfDeath", place_of_death], ["placeOfDeathOther", place_of_death_other],
]}
return submit_from_dict(form_dict, aggregate_url)
def submit_location_registration(start, hierarchy_id, fieldworker_id, loca... | "fields": [["start", start], ["end", end],
["openhds", [["fieldWorkerId", fieldworker_id], ["hierarchyId", hierarchy_id],
["locationId", location_id]]],
["locationName", location_name], ["tenCellLeader", ten_cell_leader],
... |
Azure/azure-sdk-for-python | sdk/notificationhubs/azure-mgmt-notificationhubs/azure/mgmt/notificationhubs/aio/_configuration.py | Python | mit | 3,400 | 0.004706 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | re.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class Notificatio... | instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subsc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.