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 |
|---|---|---|---|---|---|---|---|---|
DemocracyClub/EveryElection | every_election/apps/election_snooper/migrations/0003_snoopedelection_extra.py | Python | bsd-3-clause | 447 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-14 17:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("election_snooper", "0002_auto_20170314_1754")]
operations = [
migrations.AddField(
... | odel_name="snoopedelection",
name="extra", |
field=models.TextField(blank=True),
)
]
|
Lancher/tornado | maint/test/appengine/common/runtests.py | Python | apache-2.0 | 1,918 | 0 | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import contextlib
import errno
import os
import random
import signal
import socket
import subprocess
import sys
import time
import urllib2
try:
xrange
except NameError:
xrange = range
if __name__ == "__main__":
tornado... | error %d" % err)
time.sleep(0.1)
else:
raise Exception("Server didn't start listening")
resp = urllib2.urlopen("http://localhost:%d/" % port)
print(resp.read())
finally:
# dev_appserver sometimes ignores SIGTERM (especially on 2.5),
# so try a fe... | waitpid(proc.pid, os.WNOHANG)
if res != (0, 0):
break
time.sleep(0.1)
else:
os.waitpid(proc.pid, 0)
|
osDanielLee/SelfThinkingRobot | AchieveData/CollectData.py | Python | bsd-3-clause | 8,610 | 0.038329 | class CollectData():
"""每小时数据收集类
利用微博高级搜索功能,按关键字搜集一定时间范围内的微博。
大体思路:构造URL,爬取网页,然后解析网页中的微博ID。后续利用微博API进行数据入库。本程序只负责收集微博的ID。
登陆新浪微博,进入高级搜索,输入关键字”空气污染“,选择”实时“,时间为”2013-07-02-2:2013-07-09-2“,地区为”北京“,之后发送请求会发现地址栏变为如下:
http://s.weibo.com/wb/%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593&xsort=time®ion=cu... | 果页面
if (j.find('<div class="search_noresult">') > 0):
hasMore = False
## 有结果的页面
else:
page = etree.HTML(j)
dls = page.xpath(u"//dl") #使用xpath解析
for dl in dls: |
mid = str(dl.attrib.get('mid'))
if(mid != 'None' and mid not in mid_filter):
mid_filter.add(mid)
content.write(mid)
content.write('\n')
break
lines = None
## 处理被认为是机器人的情况
if isCaught:
print 'Be Caught!'
self.logger.error('Be Caught Error!')
... |
gioman/QGIS | tests/src/python/test_qgsserver_wfst.py | Python | gpl-2.0 | 12,220 | 0.001227 |
# -*- coding: utf-8 -*-
"""
Tests for WFS-T provider using QGIS Server through qgis_wrapped_server.py.
This is an integration test for QGIS Desktop WFS-T provider and QGIS Server
WFS-T that check if QGIS can talk to and uderstand itself.
The test uses testdata/wfs_transactional/wfs_transactional.qgs and three
initia... | ck features were added
"""
wfs_layer.dataProvider().addFeatures(features)
layer = self._getLayer(layer.name())
self.assertTrue(layer.isValid())
self.assertEqual(layer.featureCount(), len(features))
self.assertEqual(wfs_layer.dataProvider().featureCount(), len(features))
... | """
Check features can be updated
"""
for i in range(len(old_features)):
f = self._getFeatureByAttribute(wfs_layer, 'id', old_features[i]['id'])
self.assertTrue(wfs_layer.dataProvider().changeGeometryValues({f.id(): new_features[i].geometry()}))
self.asse... |
reisub-de/dmpr-simulator | dmprsim/analyze/profile_core.py | Python | mit | 432 | 0 | import cProfile
from pathlib import Path
def main(args, results_dir: Path, scenario_dir: Path):
try:
scenario_dir.mkdir(parents=True)
except FileExistsError:
pass
cProfile.runctx(
'from dmprsim.scenarios.python_pro | file import main;'
'main(args, results_dir, scenario_dir)',
glo | bals=globals(),
locals=locals(),
filename=str(results_dir / 'profile.pstats'),
)
|
Distrotech/scons | test/Entry.py | Python | mit | 1,860 | 0.003226 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnis... |
GuessWhoSamFoo/pandas | pandas/core/indexes/range.py | Python | bsd-3-clause | 24,595 | 0 | from datetime import timedelta
import operator
from sys import getsizeof
import warnings
import numpy as np
from pandas._libs import index as libindex, lib
import pandas.compat as compat
from pandas.compat import get_range_parameters, lrange, range
from pandas.compat.numpy import function as nv
from pandas.util._deco... | types.common import (
is_int64_dtype, is_integer, is_scalar, is_timedelta64_dtype)
from pandas.core.dtypes.generic import (
ABCDataFrame, ABCSeries, ABCTimedeltaIndex)
from pandas.core import ops
import pandas.core.common as com
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Inde... | d_docs
from pandas.core.indexes.numeric import Int64Index
class RangeIndex(Int64Index):
"""
Immutable Index implementing a monotonic integer range.
RangeIndex is a memory-saving special case of Int64Index limited to
representing monotonic ranges. Using RangeIndex may in some instances
improve com... |
ethercrow/ai-challenger | game-rps/paper.py | Python | mit | 95 | 0.010526 | #!/usr/bin/e | nv python
import sys
for _ in ran | ge(101):
print "P\n."
sys.stdout.flush() |
BhallaLab/benchmarks | moose_nrn_equivalence_testing/comparision_with_simple_HH_model/xplot.py | Python | gpl-2.0 | 2,472 | 0.023463 | #!/usr/bin/env python
"""xplot.py:
This program uses matplotlib to plot xplot like data.
Last modified: Thu Jul 23, 2015 04:54PM
"""
__author__ = "Dila | war Singh"
__copyright__ = "Copyright 2013, NCBS Bangalore"
__credits__ = ["NCBS Bangalore", "Bhalla Lab"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@iitb.ac.in"
__status__ = "Development"
import sys |
import pylab
data = {}
def buildData( file ):
global data
with open(file, "r") as f:
xvec = []
yvec = []
for line in f:
if line[0] == ';' or line[0] == '#':
continue
line = line.strip()
if "," in line:
line = line.sp... |
mhmurray/cloaca | setup.py | Python | mit | 696 | 0.018678 | from setuptools import setup
import minify.command
setup(name='cloaca',
version='0.1.0',
url='https://github.com/mhmurray/cloaca',
author='Michael Murray',
author_email='mich | aelhamburgmurray@gmail.com',
license='MIT',
packages=['cloaca'],
zip_safe=False,
include_package_data=True,
scripts=[
'cloaca/cloacaapp.py'
],
install_requires=[
'tornado>=4.3.0',
'tornadis>=0.7.0',
'bcrypt>=2.0.... | 'minify_css' : minify.command.minify_css,
},
)
|
wolverineav/neutron | neutron/agent/metadata/config.py | Python | apache-2.0 | 5,135 | 0 | # Copyright 2015 OpenStack Foundation.
#
# 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... | der with a shared secret to prevent '
'spoof | ing. You may select any string for a secret, '
'but it must match here and in the configuration used '
'by the Nova Metadata Server. NOTE: Nova uses the same '
'config key, but in [neutron] section.'),
secret=True),
cfg.StrOpt('no... |
google-research/google-research | representation_batch_rl/batch_rl/train_eval_online.py | Python | apache-2.0 | 9,735 | 0.006471 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | rl import asac
from representation_batch_rl.batch_rl import awr
from representation_batch_rl.batch_rl import ddpg
from representation_batch_rl.batch_rl import evaluation
from representation_batch_rl.batch_rl import pcl
from representation_batch_rl.batch_rl import sac
from representation_batch_rl.batch_rl import sac_v1
... | ation_batch_rl.twin_sac import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('env_name', 'pixels-dm-cartpole-swingup',
'Environment for training/evaluation.')
flags.DEFINE_integer('seed', 42, 'Fixed random seed for training.')
flags.DEFINE_float('actor_lr', 3e-4, 'Actor learning rate.')
flags.DEF... |
Sjc1000/PyRC | Commands/join.py | Python | gpl-2.0 | 505 | 0.00396 | #!/usr/bin/env python
def run(c, *channels):
server = c['MainWindow'].ui | _plugins['ServerList'].active_server
connection = c['MainWindow'].ui_plugins['ServerList'].servers[server]['connection']
if isinstance(channels, str): |
channels = [channels]
for channel in channels:
if channel.startswith('#') is False:
channel = '#' + channel
channel = channel.replace('\n', '').replace('\r', '')
connection.send('JOIN ' + channel.strip())
return None |
Gustry/QuickOSM | QuickOSM/test/test_saved_query.py | Python | gpl-2.0 | 17,258 | 0.002318 | """Tests for the preset and the history of queries."""
import json
import os
from qgis.core import QgsCoordinateReferenceSystem, QgsRectangle
from qgis.testing import unittest
from QuickOSM.core.utilities.json_encoder import as_enum
from QuickOSM.core.utilities.query_saved import QueryManagement
from QuickOSM.core.ut... | te_points.setText('name')
index = edit_dialog.combo_output_format.findData(Format.Kml)
edit_dialog.combo_output_format.setCurrentIndex(index)
edit_dialog.button_validat | e.click()
self.preset = |
Jumpscale/jumpscale_portal8 | lib/portal/docpreprocessor/DocHandler.py | Python | apache-2.0 | 2,305 | 0.004338 | from JumpScale import j
# import re
import os
# import jinja2
from watchdog.events import FileSystemEventHandler
# The default Observer on Linux (InotifyObserver) hangs in the call to `observer.schedule` because the observer uses `threading.Lock`, which is
# monkeypatched by `gevent`. To work around this, I use `Poll... | self.doc_processor = doc_processor
def on_created(self, event):
print(('Document {} added'.format(event.src_path)))
pat | h = os.path.dirname(event.src_path)
pathItem = event.src_path
docs = []
if pathItem:
lastDefaultPath = ""
if pathItem.endswith('.wiki'):
lastDefaultPath = os.path.join(self.doc_processor.space_path, '.space', 'default.wiki')
elif pathItem.endsw... |
mganeva/mantid | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SingleCrystalDiffuseReduction.py | Python | gpl-3.0 | 21,263 | 0.007149 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | niometer>`")
condition = VisibleWhenProperty("SetGoniometer", PropertyCriterion.IsNotDefault)
self.copyProperties('SetGoniometer', ['Goniometers', 'Axis0', 'Axis1', 'Axis2'])
self.setPropertySettings("Goniometers", condition)
self.setPropertySettings('Axis0', condition)
self.setP... | yProperty('OmegaOffset', [], direction=Direction.Input),
doc="Offset to apply to the omega rotation of the Goniometer. Need to provide one value for every run.")
# Corrections
self.declareProperty(FileProperty(name="LoadInstrument",defaultValue="",action=FileAction.Optional... |
gaoxiaofeng/troubleShooting | src/troubleshooting/framework/output/writehtml.py | Python | apache-2.0 | 9,570 | 0.009613 | # -*- coding: utf-8 -*-
from troubleshooting.framework.modules.manager import ManagerFactory
from troubleshooting.framework.variable.variable import *
from troubleshooting.framework.libraries.baseList import list2stringAndFormat
from troubleshooting.framework.libraries.system import createDir
from troubleshooting.frame... | " style="margin:0px">
"""%i
data += """
<tr>
<th width="5%%">
<b>TestPoint</b>
</th>
<th wid | th="5%%">
<b>Status</b>
</th>
<th width="5%%">
<b>Level</b>
</th>
<th width="15%%" name="nolog">
... |
ptthiem/nose2 | nose2/tests/unit/test_functions_loader.py | Python | bsd-2-clause | 1,464 | 0 | import unittest
from nose2 import events, loader, session
from nose2.plugins.loader import functions
from nose2.tests._common import TestCase
class TestFunctionLoader(TestCase):
def setUp(self):
self.session = session.Session()
self.loader = loader.PluggableTestLoader(self.session)
self.p... | m.test = test
event = events.LoadFromModule | Event(self.loader, m)
self.session.hooks.loadTestsFromModule(event)
self.assertEqual(len(event.extraTests), 1)
assert isinstance(event.extraTests[0], unittest.FunctionTestCase)
def test_ignores_generator_functions(self):
class Mod(object):
pass
def test():
... |
PythonCharmers/orange3 | Orange/src/setup.py | Python | gpl-3.0 | 324 | 0.018519 | from distutils.core import setup
from distutils.extension import Extension
from Cyth | on.Distutils import build_ext
import numpy as np
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("_orange", ["_orange.pyx"],
include_dirs=[np.get_inclu | de()]
)]
)
|
peter-wangxu/python_play | test/A.py | Python | apache-2.0 | 195 | 0.035897 | __autho | r__ = 'wangp11'
AA=1
l1 = [13, 13]
n = 1
def print_l1():
print "id A.py: %d" % id(l1)
print l1
def ex | tend_l1():
l1.extend([1,31,31])
print l1
def print_n():
print n |
lafactura/datea-api | datea_api/apps/follow/migrations/0001_initial.py | Python | agpl-3.0 | 1,483 | 0.004046 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_... | max_length=255)),
('published', models.BooleanField(default=True)),
('client_domain', models.CharField(max_length=100, null=True, verbose_name='CLient Domain', blank=True)),
('content_type', models.ForeignKey(blank=True, to='conte | nttypes.ContentType', null=True)),
('user', models.ForeignKey(related_name='follows', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Follow',
'verbose_name_plural': 'Follows',
},
),
migrations.AlterUniqueTo... |
DistrictDataLabs/science-bookclub | bin/octavo-admin.py | Python | apache-2.0 | 1,356 | 0.004425 | #!/usr/bin/env python
# octavo-admin
# An administrative script for our bookclub
| #
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sun Mar 30 20:26:20 2014 -0400
#
# Copyright (C) 2014 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: octavo-admin.py [] benjamin@bengfort.com $
"""
An administrative script for our bookclub
"""
#######################################... | ####################
## Imports
##########################################################################
import os
import sys
import argparse
##########################################################################
## Command Line Variables
#########################################################################... |
rockymeza/django-local-requests | tests/views.py | Python | bsd-2-clause | 1,217 | 0 | from rest_framework import (
serializers,
viewsets,
)
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Author, Book
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = (
... | ):
serializer_class = AuthorSerializer
queryset = Author.objects.all()
class BookViewSet(viewsets.M | odelViewSet):
serializer_class = BookSerializer
queryset = Book.objects.all()
@api_view(['GET', 'POST'])
def echo(request):
return Response({
'GET': request.GET,
'POST': request.POST,
'META': request.META,
})
@api_view(['POST'])
def upload_file(request):
file = request.FI... |
danhuss/faker | faker/providers/currency/ru_RU/__init__.py | Python | mit | 7,994 | 0.00017 | from .. import Provider as CurrencyProvider
class Provider(CurrencyProvider):
# Format: (code, name)
# See currency names in Russian: https://ru.wikipedia.org/wiki/Список_существующих_валют#Валюты
currencies = (
("AED", "Дирхам ОАЭ"),
("AFN", "Афгани"),
("ALL", "Лек"),
("AM... | ("DJF", "Франк Джибути"),
("DKK", "Датская крона"),
("DOP", "Доминиканское песо"),
("DZD", "Алжирский динар"),
("EGP", "Египетский фунт"),
("ERN", "Накфа"),
("ETB", "Эфиопский быр"),
("EUR", "Евро"),
("FJD", "Доллар Фиджи"),
("FKP", "Фунт Фо... | ("GIP", "Гибралтарский фунт"),
("GMD", "Даласи"),
("GNF", "Гвинейский франк"),
("GTQ", "Кетсаль"),
("GYD", "Гайанский доллар"),
("HKD", "Гонконгский доллар"),
("HNL", "Лемпира"),
("HRK", "Хорватская куна"),
("HTG", "Гурд"),
("HUF", "Форинт"),... |
Epikarsios/RssLEDBackpack | RssLED.py | Python | gpl-3.0 | 1,628 | 0.032555 | import feedparser
import time
# Create display instance on default I2C address (0x70) and bus number.
from Adafruit_LED_Backpack import AlphaNum4
display = AlphaNum4.AlphaNum4()
# Initialize the display. Must be called once before using the display.
display.begin()
#create string(s) with rss address for multiple feed... | s:
#prints title to console
print (i.title)
#reset position to begining
pos = 0
#Change string to Uppercase for readability and add --* buffer to begining and end to distinguish titles
CapString = "---*" + i.t | itle.upper() + "*---"
# Dashed line in console for aesthetics
print("----------------------------------------------------------------")
#Loop for scrolling through title
for x in range(0,len(CapString)-4):
# Print a 4 character string to the display buffer.
display.print_str(CapString[po... |
refeed/coala | coalib/bearlib/aspects/collections.py | Python | agpl-3.0 | 390 | 0 | from coalib.bearlib.aspects.meta import issubaspect, assert_aspect
class aspectlist(list):
"""
List-derived container to hold | aspects.
"""
def __init__(self, seq=()):
super().__init__(map(assert_aspect, seq))
def __contains__(self, aspect):
for item in self:
if issubaspect(aspect, item):
return True
| return False
|
mikewesner-wf/glasshouse | appengine/lib/invoke/vendor/pexpect/__init__.py | Python | apache-2.0 | 78,307 | 0.004572 | """Pexpect is a Python module for spawning child applications and controlling
them automatically. Pexpect can be used for automating interactive applications
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
scripts for duplicating software package installations on different servers. It
can be u... | import struct
import resource
import types
import pty
import tty
import termios
import fcntl
import errno
import traceback
import signal
except ImportError, e:
raise ImportError (str(e) + """
A critical module was not foun | d. Probably this operating system does not
support it. Pexpect is intended for UNIX-like operating systems.""")
__version__ = '2.5.1'
version = __version__
version_info = (2,5,1)
__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which',
'split_command_line', '__version__']
# Exception cl... |
CenterForOpenScience/SHARE | api/formattedmetadatarecords/urls.py | Python | apache-2.0 | 266 | 0.003759 | from rest_framework.routers import SimpleRouter
from api.formattedmetadatarecords import views
router | = SimpleRouter()
router.register(r'formattedmetadatarecords', views.FormattedMetadataRecordViewSet, bas | ename='formattedmetadatarecord')
urlpatterns = router.urls
|
kalaspuff/tomodachi | tomodachi/launcher.py | Python | mit | 12,014 | 0.002164 | import asyncio
import datetime
import importlib
import logging
import os
import platform
import signal
import sys
import time
from typing import Any, Dict, List, Optional, Set, Union, cast
import tomodachi.__version__
import tomodachi.container
import tomodachi.importer
import tomodachi.invoker
from tomodachi.containe... | )
for signame in ("SIGINT", "SIGTERM"):
loop.add_signal_handler(getattr(signal, signame), stop_services)
signal.siginterrupt(signal.SIGTERM, False)
signal.siginterrupt(signal.SIGUSR1, False)
signal.signal(signal.SIGINT, sigintHandler)
signal.signal(signal.SIGTERM, s... | ist, set]) -> None:
cls.restart_services = True
for file in service_files:
try:
ServiceImporter.import_service_file(file)
except (SyntaxError, IndentationError) as e:
logging.getLogger("exception").e... |
tbjoern/adventofcode | Twentythree/reverse.py | Python | mit | 331 | 0.096677 | # a = 7 or | a = 12
b = a
b -= 1
d = a
a = 0
# a += b*d
c = b
a += 1
c -= 1
whi | le c != 0
d -= 1
while d !=0
b -= 1
c = b
# c *= 2
d = c
d -= 1
c += 1
while d != 0
tgl c
c = -16
while b > 1
c = 1
# a += 95*95
c = 95
d = 95
a += 1
d -= 1
while d != 0
c -= 1
while c != 0 |
burakbayramli/classnotes | algs/algs_105_mesquita/test1.py | Python | gpl-3.0 | 7,691 | 0.021194 | import itertools, os
import pandas as pd, sys
import numpy as np, matplotlib.pylab as plt
Q = 1.0 ; T = 1.0
class Game:
def __init__(self,df):
self.df = df.copy()
self.df_orig = self.df.copy()
# dictionaries of df variables - used for speedy access
self.df_capability = df.Capabili... | lf.df.Capability.to_dict()
self.df_position = self.df.Position.to_dict()
self.df_salience = self.df.Salience.to_dict()
self.max_pos = self.df.Position.max()
self.min_pos = self.df | .Position.min()
self.df_orig_position = self.df_orig.Position.to_dict()
offers = [list() for i in range(len(self.df))]
ris = [self.ri(i) for i in range(len(self.df))]
for (i,j) in itertools.combinations(range(len(self.df)), 2 ):
if i==j: continue
eui... |
jordanemedlock/psychtruths | temboo/core/Library/Mixpanel/DataExport/Funnels/FunnelList.py | Python | apache-2.0 | 3,581 | 0.004468 | # -*- coding: utf-8 -*-
###############################################################################
#
# FunnelList
# Gets the names and funnel_ids of your funnels.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use... | f the APISecret input for this Choreo. ((required, string) The API Secret provided by Mixpanel. You can find your Mixpanel API Secret in the project settings dialog in the Mixpanel app.)
"""
super(FunnelListInputSet, self)._set_input('APISecret', value)
def set_Expire(self, value):
"""
... | e request will expire. Defaults to 1.)
"""
super(FunnelListInputSet, self)._set_input('Expire', value)
class FunnelListResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the FunnelList Choreo.
The ResultSet object is used to retrieve the results of a Chore... |
telminov/ansible-manager | core/views/rest.py | Python | mit | 2,316 | 0.003454 | from django.db.models import Count
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication
from prometheus_client import generate_latest
from core import models
from core import serializ... | ks:
continue
success = int(completed_tasks.last().status == consts.COMPLETED)
result += 'ansible_manager_template_last_task_success{id="%s", name="%s"} %s\n' % (
template.pk, template.name, success)
result += '# HELP ansible_manager_tasks_completed_total... | _id', 'template__name', 'status').annotate(count=Count('id'))
for template_id, template_name, status, count in tasks:
result += 'ansible_manager_tasks_completed_total{id="%s", name="%s", status="%s"} %s\n' % (
template_id, template_name, status, count
)
return Ht... |
fluxw42/youtube-dl | youtube_dl/extractor/reverbnation.py | Python | unlicense | 1,627 | 0.000615 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
qualities,
str_or_none,
)
class ReverbNationIE(InfoExtractor):
_VALID_URL = r'^https?://(?:www\.)?reverbnation\.com/.*?/song/(?P<id>\d+).*?$'
_TESTS = [{
'url': 'http://www.reverbnation.com/alkilad... | g/16965047-mona-lisa',
'md5': 'c0aaf339bcee189495fdf5a8c8ba8645',
'info_dict': {
'id': '16965047',
'ext': 'mp3',
'title': 'MONA LISA',
'uploader': 'ALKILADOS' | ,
'uploader_id': '216429',
'thumbnail': r're:^https?://.*\.jpg',
},
}]
def _real_extract(self, url):
song_id = self._match_id(url)
api_res = self._download_json(
'https://api.reverbnation.com/song/%s' % song_id,
song_id,
note=... |
hrishioa/Aviato | flask/Scripts/kartograph-script.py | Python | gpl-2.0 | 364 | 0.005495 | #!C:\Users\SeanSaito\Dev\avi | ato\flask\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'kartograph.py==0.6.8','console_scripts','kartograph'
__requires__ = 'kartograph.py==0.6.8'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('kartograp | h.py==0.6.8', 'console_scripts', 'kartograph')()
)
|
ecaldwe1/zika | website/mixins.py | Python | mpl-2.0 | 1,140 | 0.000877 | #!/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet Zika modeling interface.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE. | txt files in its top-level directory; they are
# available at https://github.com/vecnet/zika
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
import json
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
class LoginRequiredMixin(object):
""" This works: class InterviewListView(LoginRequiredMixin, ListView)
This DOES NOT work: class InterviewListView(ListView, LoginRequiredMixin)
I'm not 100% sure th... |
edagar/censorship-analyser | test.py | Python | bsd-3-clause | 5,035 | 0.000199 | import subprocess
from random import choice, randint
from time import sleep
import yaml
from ooni.otime import timestamp
import const
class Test(object):
def __init__(self, testfile, args=[]):
self.testfile = testfile
self.args = args
self.output = None
self.status = None
... | STest(Test):
def __init__(self, testfile=const.DNS_TEST, target=const.TOR_DOMAIN):
super(DNSTest, self).__init__(testfile=testfile, args=["-t", target])
self.target = target
class Traceroute(Test):
def __init__(self, testfile=const.TRACEROUTE_TEST, target=None):
args = ["-b", target]... | arget
class TestParser(object):
def __init__(self, test):
self.test = test
def loadReport(self):
with open(self.test.reportName, 'r') as f:
entries = yaml.safe_load_all(f)
headers = entries.next()
self.test.report = entries.next()
def parseReport(sel... |
plotly/python-api | packages/python/plotly/plotly/validators/parcats/line/colorbar/_tickcolor.py | Python | mit | 480 | 0.002083 | import _plotly_utils.basevalidators
class TickcolorValidator(_plotly_utils.basevali | dators.ColorValidator):
def __init__(
self, plotly_name="tickcolor", parent_name="parcats.line.colorbar", **kwargs
):
super(TickcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
... | e=kwargs.pop("role", "style"),
**kwargs
)
|
thaim/ansible | lib/ansible/modules/cloud/amazon/lambda.py | Python | mit | 23,103 | 0.002813 | #!/usr/bin/python
# 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.
#
# Ansible is distributed... | da_basic_execution'
handler: 'hello_python.my_ | handler'
vpc_subnet_ids:
- subnet-123abcde
- subnet-edcba321
vpc_security_group_ids:
- sg-123abcde
- sg-edcba321
environment_variables: '{{ item.env_vars }}'
tags:
key1: 'value1'
loop:
- name: HelloWorld
zip_file: hello-code.zip
env_vars:
key1: "first"
... |
esplinr/foodcheck | wsgi/foodcheck_proj/settings.py | Python | agpl-3.0 | 8,249 | 0.003758 | # -*- coding: utf-8 -*-
'''
Django settings for foodcheck project
'''
# Copyright (C) 2013 Timothy James Austen, Eileen Qiuhua Lin,
# Richard Esplin <richard-oss@esplins.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Ge... | .MessageMiddleware',
)
ROOT_URLCONF = 'foodcheck_proj.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'templat... | jango.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'south',
'leaflet',
'foodcheck_app',
)
# A sam... |
jandom/rdkit | rdkit/Chem/PeriodicTable.py | Python | bsd-3-clause | 5,870 | 0.018739 | # $Id$
#
# Copyright (C) 2001-2006 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" periodic table data... | 65.39 2
31 Ga 1.220 1.260 1.870 3 69.723 3
32 Ge 1.170 1.188 1.700 4 72.61 4
33 As 1.210 1.200 1.850 3 74.922 5
34 Se 1.220 1.170 1.900 2 78.96 6
35 Br 1.210 1.167 2.100 1 79.904 7
36 Kr 1.910 1.910 2.020 0 83.80 8
37 Rb 1.470 2.160 1.700 1 85.468 1
38 Sr 1.120 1.910 1.700 2 87.62 2
39 Y 1.780 1.620 ... | 6 92.906 5
42 Mo 1.470 1.300 1.700 6 95.94 6
43 Tc 1.350 1.270 1.700 6 98.0 7
44 Ru 1.400 1.250 1.700 6 101.07 8
45 Rh 1.450 1.250 1.700 6 102.906 9
46 Pd 1.500 1.280 1.630 6 106.42 10
47 Ag 1.590 1.340 1.720 6 107.868 11
48 Cd 1.690 1.480 1.580 6 112.412 2
49 In 1.630 1.440 1.930 3 114.818 3
50 Sn 1.46... |
dreaming-dog/kaldi-long-audio-alignment | scripts/classes/entry.py | Python | apache-2.0 | 326 | 0.04908 | # Copyright 2017 Speech Lab, EE Dept., IITM (Author: Srinivas Venkattaramanu | jam)
class Entry:
def __init__(self, begin_time, end_time, st | atus, word_begin, word_end):
self.begin_time=float(begin_time)
self.end_time=float(end_time)
self.status=status
self.word_begin=int(word_begin)
self.word_end=int(word_end)
|
waprin/gcloud-python | gcloud/logging/test_logger.py | Python | apache-2.0 | 25,904 | 0 | # Copyright 2016 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 a... | logger.log_text(TEXT)
self.assertEqual(api._write_entries_called_with,
(ENTRIES, None, None, None))
def test_log_text_w_default_labels(self):
TEXT = 'TEXT'
DEFAULT_LABELS = {'foo': 'spam'}
ENTRIES = [{
'logName': 'projects/%s/logs/%s' % (
... | 'resource': {
'type': 'global',
},
'labels': DEFAULT_LABELS,
}]
client = _Client(self.PROJECT)
api = client.logging_api = _DummyLoggingAPI()
logger = self._makeOne(self.LOGGER_NAME, client=client,
labels=DEFAULT_LABEL... |
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx/main/migrations/0109_v370_job_template_organization_field.py | Python | apache-2.0 | 3,857 | 0.002074 | # Generated by Django 2.2.4 on 2019-08-07 19:56
import awx.main.utils.polymorphic
import awx.main.fields
from django.db import migrations, models
import django.db.models.deletion
from awx.main.migrations._rbac import (
rebuild_role_parentage, rebuild_role_hierarchy,
migrate_ujt_organization, migrate_ujt_organ... | erations = [
# backwards parents and ancestors caching
migrations.RunPython(migrations.RunPython.noop, rebuild_jt_parents),
# add new organizat | ion field for JT and all other unified jobs
migrations.AddField(
model_name='unifiedjob',
name='tmp_organization',
field=models.ForeignKey(blank=True, help_text='The organization used to determine access to this unified job.', null=True, on_delete=awx.main.utils.polymorphic.S... |
vlegoff/mud | typeclasses/players.py | Python | bsd-3-clause | 4,163 | 0.001681 | """
Player
The Player represents the game "account" and each login has only one
Player object. A Player is what chats on default channels but has no
other in-game-world existance. Rather the Player puppets Objects (such
as Characters) in order to actually participate in the game world.
Guest
Guest players are simpl... | - game object controlled by player. 'character' can also be used.
sessions (list of Sessions) - sessions connected to this player
is_superuser (bool, read-only) - if the connected user is a superuser
* Handlers
locks - lock- | handler: use locks.add() to add new lock strings
db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr
ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data
scripts - script-handler. Add new scripts to... |
google-research/plur | plur/stage_1/code2seq_dataset.py | Python | apache-2.0 | 16,900 | 0.006154 | # Copyright 2021 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 agreed to in writing, ... | ation of code2seq.
We try to mimic the code2seq model by constructing a graph similar to figure
3 in the code2seq paper. An example of such graph is shown in
https://drive.google.com/file/d/1-cH0FzYI | MikgTkUpzVkEZDGjoiqBB9C1/view?usp=sharing.
In short, we build the AST path subtree and connects all AST paths with a
code2seq root node to make it a graph.
"""
_URLS_SMALL = {
'java-small-preprocessed.tar.gz': {
'url': 'https://s3.amazonaws.com/code2seq/datasets/java-small-preprocessed.tar.gz',... |
dwhall/pq | examples/countdown.py | Python | mit | 1,269 | 0.002364 | #!/usr/bin/env python3
import asyncio
import pq
class Countdown(pq.Ahsm):
def __init__(self, count=3):
super().__init__(Countdown.initial)
self.count = count
@pq.Hsm.state
def initial(me, event):
print("initial")
me.te = pq.Tim | eEvent("TIME_TICK")
return me.tran(me, Countdown.counting) |
@pq.Hsm.state
def counting(me, event):
sig = event.signal
if sig == pq.Signal.ENTRY:
print("counting")
me.te.postIn(me, 1.0)
return me.handled(me, event)
elif sig == pq.Signal.TIME_TICK:
print(me.count)
if me.count == 0:
... |
xupingmao/xnote | xutils/dbutil_sortedset.py | Python | gpl-3.0 | 3,154 | 0.013316 | # -*- coding:utf-8 -*-
# @author xupingmao
# @since 2021/12/05 11:25:18
# @modified 2022/01/24 14:47:38
# @filename dbutil_sortedset.py
"""【待实现】有序集合,用于各种需要排名的场景,比如
- 最近编辑的笔记
- 访问次数最多的笔记
如果使用了LdbTable的索引功能,其实就不需要这个了
"""
from xutils.dbutil_base import *
from xutils.dbutil_hash import LdbHashTable
register_table("_ran... | str = self._format_score(score)
key = self.prefix + str(score) + ":" + member
if batch != None:
batch.put(key, member)
else:
put(key, member)
def delete(self, member, score, batch = None):
score_str = self._format_score(score)
key = self.prefix + str... | def list(self, offset = 0, limit = 10, reverse = False):
return prefix_list(self.prefix, offset = offset,
limit = limit, reverse = reverse)
class LdbSortedSet:
def __init__(self, table_name, user_name = None, key_name = "_key"):
# key-value的映射
self.member_dict = LdbHashTable... |
dparks1134/STAMP | stamp/plugins/samples/plots/configGUI/barUI.py | Python | gpl-3.0 | 9,975 | 0.00381 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'bar.ui'
#
# Created: Thu Aug 11 10:41:59 2011
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeEr... | oLegendPosLowerLeft"))
self.gridLayout.addWidget(self.radioLegendPosLowerLeft, 0, 4, 1, 1)
self.radioLegendPosUpperRight = QtGui.QRadioButton(self. | groupBox)
self.radioLegendPosUpperRight.setObjectName(_fromUtf8("radioLegendPosUpperRight"))
self.gridLayout.addWidget(self.radioLegendPosUpperRight, 1, 2, 1, 1)
self.radioLegendPosCentreRight = QtGui.QRadioButton(self.groupBox)
self.radioLegendPosCentreRight.setObjectName(_fromUtf8("rad... |
breenmachine/clusterd | src/module/invoke_payload.py | Python | mit | 3,120 | 0.003526 | from src.module.deploy_utils import parse_war_path
from commands import getoutput
from log import LOG
import utility
def invoke(fingerengine, fingerprint, deployer):
"""
"""
if fingerengine.service in ["jboss", "tomcat"]:
return invoke_war(fingerengine, fingerprint)
elif fingerengine.service... | /{2}".format(fingerengine.options.ip,
fingerprint.port,
| dfile)
else:
url = "http://{0}:{1}/CFIDE/{2}".format(fingerengine.options.ip,
fingerprint.port,
dfile)
if _invoke(url):
utility.Msg("{0} invoked at {1}".format(dfile, fingerengi... |
billzorn/fpunreal | titanfp/web/old_webdemo.py | Python | mit | 14,240 | 0.00302 | #!/usr/bin/env python
import sys
import os
import threading
import traceback
import json
import multiprocessing
import subprocess
import http
import html
import urllib
import argparse
from .aserver import AsyncCache, AsyncTCPServer, AsyncHTTPRequestHandler
from ..fpbench import fpcparser
from ..arithmetic import nat... | ve, np
from ..arithmetic import softfloat, soft | posit
from ..arithmetic import ieee754, posit
from ..arithmetic import sinking
from ..arithmetic import canonicalize
from ..arithmetic import evalctx
here = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(here, 'index.html'), 'rb') as f:
index = f.read()
with open(os.path.join(here, 'evaluate.h... |
SpectoLabs/myna | contrib/python-myna/myna/__init__.py | Python | apache-2.0 | 180 | 0.011111 | from . import shim
tmpdir = Non | e
def setUp():
global tmpdir
tmpdir = shim.setup_shim_for('kubectl')
def tearDown():
global tmpdir
| shim.teardown_shim_dir(tmpdir)
|
lowRISC/opentitan | util/tlgen/__init__.py | Python | apache-2.0 | 465 | 0 | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
from . | doc import selfdoc # noqa: F401
from .elaborate import elaborate # noqa: F401
from .generate import generate # noqa: F401
from .generate_tb import generate_tb # noqa: F401
from .item import Edge, Node, NodeType # noqa: F401
from .validate import validate # noqa: F401
from .xbar | import Xbar # noqa: F401
|
tcstewar/boardgame | boardgame/card.py | Python | gpl-2.0 | 59 | 0.016949 | i | mport boardgame as bg
class Card(bg.GamePiece):
pass
| |
imankulov/linguee-api | tests/test_linguee_client.py | Python | mit | 863 | 0 | import pytest
from linguee_api.const import LANGUAGE_CODE, LANGUAGES
from linguee_api.linguee_client import LingueeClient
from linguee_api.models import SearchResult
@pytest.mark.asyncio
async def test_linguee_client_should_redirect_on_not_found(
linguee_client: LingueeClient,
):
search_result = await lingue... |
async def test_linguee_client_should_process_test_requests(
linguee_client: LingueeClient,
lang: LANGUAGE_CODE,
):
search_result = await linguee_client.process_search_result(
query="test", src="en", dst=lang, guess_direction=False
)
ass | ert isinstance(search_result, SearchResult)
|
Eylesis/Botfriend | Cogs/GameTime.py | Python | mit | 1,883 | 0.012746 | import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bo... | e, bDate.second) + timedelta(days=delta.days*3) + (timedelta(days=(bDate.hour//8-2)))
if gametime.hour == 0:
gametime_hour = 12
time_decor = "AM"
else:
gametime_hour = gametime.hour-12 if gametime.hour > 12 else gametime.hour
time_decor = "PM" if gametime.hour > 12 else "AM"
... | t(gametime_hour, gametime_minute, time_decor, gametime.day, suffix(gametime.day), months[gametime.month-1])
def setup(bot):
bot.add_cog(GameTime(bot))
|
casbeebc/abenity-python | setup.py | Python | mit | 1,394 | 0 | #!/usr/bin/env python
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
clas | s PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['--strict', '--verbose', '--tb=long', '-s', 'tests']
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(err... | ion='Abenity API client',
long_description='A Python library for using the Abenity API.',
url='https://github.com/casbeebc/abenity-python',
author='Brett Casbeer',
author_email='brett.casbeer@gmail.com',
license='MIT',
cmdclass={'test': PyTest},
classifiers=[
'Development Status :: 3... |
4shadoww/usploit | lib/scapy/contrib/automotive/uds.py | Python | mit | 44,266 | 0 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Nils Weiss <nils@we155.de>
# This program is published under a GPLv2 license
# scapy.contrib.description = Unified Diagnostic Service (UDS)
# scapy.contrib.status = loads
import struct
import time
from iterto... | 0x62: 'ReadDataByIdentifierPositiveResponse',
0x63: 'ReadMemoryByAddressPositiveResponse',
0x64: 'ReadScalingDataByIdentifierPositiveResponse',
0x67: 'SecurityAccessPositiveResponse',
| 0x68: 'CommunicationControlPositiveResponse',
0x6A: 'ReadDataPeriodicIdentifierPositiveResponse',
0x6C: 'DynamicallyDefineDataIdentifierPositiveResponse',
0x6E: 'WriteDataByIdentifierPositiveResponse',
0x6F: 'InputOutputControlByIdentifierPositiveResponse',
0x71: 'R... |
CountZer0/PipelineConstructionSet | python/maya/site-packages/pymel-1.0.3/pymel/util/utilitytypes.py | Python | bsd-3-clause | 43,474 | 0.006073 | """
Defines common types and type related utilities: Singleton, etc.
These types can be shared by other utils modules and imported into util main namespace for use by other pymel modules
"""
import inspect, types, operator, sys, warnings
class Singleton(type):
""" Metaclass for Singleton classes.
| >>> class DictSingleton(dict) :
... __metaclass__ = Singleton
| ...
>>> DictSingleton({'A':1})
{'A': 1}
>>> a = DictSingleton()
>>> a
{'A': 1}
>>> b = DictSingleton({'B':2})
>>> a, b, DictSingleton()
({'B': 2}, {'B': 2}, {'B': 2})
>>> a is b and a is DictSingleton()
True
>>> class StringSinglet... |
alexei-matveev/ase-local | ase/tasks/calcfactory.py | Python | gpl-2.0 | 6,674 | 0.00015 | import optparse
from math import sqrt, pi
import numpy as np
from ase.dft.kpoints import monkhorst_pack
def str2dict(s, namespace={}, sep='='):
"""Convert comma-separated key=value string to dictionary.
Examples:
>>> str2dict('xc=PBE,nbands=200,parallel={band:4}')
{'xc': 'PBE', 'nbands': 200, 'par... | help='Density of k-points in Angstrom.')
calc.add_option('-p', '--parameters', metavar='key=value,...',
help='Comma-separated key=value pairs of ' +
'calculator specific parameters.')
parser.add_option_group(calc)
def parse(self, opts, args)... | shift = 0.5 * ((kpts + 1) % 2) / kpts
self.kpts = monkhorst_pack(kpts) + shift
else:
self.kpts = [int(k) for k in mp.split(',')]
self.kptdensity = opts.k_point_density
if opts.parameters:
self.kwargs.update(str2dict(opts.parameters))
# Rec... |
thorgate/django-project-template | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/settings/__init__.py | Python | isc | 392 | 0.002551 | import os
import sys
if os.environ.get("DJANGO_PRODUCTION_MODE"):
from settings.cloud import *
else:
# When not using production mode try to load local.py
| try:
from settings.local import *
except ImportError:
sys.stderr.write(
"Couldn't import settings.local, have you created it from setti | ngs/local.py.example ?\n"
)
sys.exit(1)
|
dspichkin/djangodashpanel | djangodashpanel/security/views.py | Python | gpl-3.0 | 9,113 | 0.002743 | import time
import json
import pytz
from datetime import datetime, timedelta
from django.utils import timezone
from django.conf import settings
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissi... | st_date")
date_tz = None
if raw_date:
date = datetime.fromtimestamp(int(raw_date))
date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None)
if host in temp_hosts:
temp_hosts[host]["count"] = temp_hosts[host]["count"] + ... | = date_tz.strftime("%b %d %H:%M")
else:
temp_hosts[host] = {
"host": host,
"count": v.get("count", 0),
"last_date": date_tz.strftime("%b %d %H:%M")
}
for user, v in value.get("users", {}).items():
... |
karel-brinda/smbl | smbl/utils/rule.py | Python | mit | 572 | 0.050699 | import smbl
__RULES=set()
def | register_rule(rule):
registered_rules=[r.encode() for r in get_registered_rules()]
if rule.encode() not in registered_rules:
__RULES.add(rule)
def get_registered_rules():
return list(__RULES)
class Rule:
def __init__(self,input,output,run):
self.__input=input
self.__output=output
self.__run=run
regist... | :
return self.__input
def get_output(self):
return self.__output
def run(self):
self.__run()
def encode(self):
return "{} {}".format(str(self.__input),str(self.__output))
|
kevin-intel/scikit-learn | sklearn/ensemble/_hist_gradient_boosting/tests/test_predictor.py | Python | bsd-3-clause | 6,256 | 0 | import numpy as np
from numpy.testing import assert_allclose
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
import pytest
from sklearn.ensemble._hist_gradient_boosting.binning import _BinMapper
from sklearn.ensemble._hist_gradient_... | binned_cat_bitsets[0], categories)
predictor = TreePredictor(nodes, binned_cat_bitsets,
| raw_categorical_bitsets)
# Check binned data gives correct predictions
prediction_binned = predictor.predict_binned(X_binned,
missing_values_bin_idx=6)
assert_allclose(prediction_binned, expected_predictions)
# manually construct b... |
hehongliang/tensorflow | tensorflow/python/kernel_tests/conv_ops_test.py | Python | apache-2.0 | 73,074 | 0.005351 | # 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... | ], [3, 3, 64, 192], [1, 1, 64, 64],
[1, 1, 24, 64]]
out_sizes = [[4, 5, 5, 128], [4, 8, 8, 384], [4, 8, 8, 384],
[4, 8, 8, 192], [4, 8, 8, 384], [4, 8, 8, 320],
[4, 8, 8, 448], [4, 8, 8, 384], [4, 8, 8 | , 384],
[4, 8, 8, 192], [4, 8, 8, 448], [4, 8, 8, 320],
[4, 8, 8, 192], [4, 17, 17, 192], [4, 17, 17, 192],
[4, 8, 8, 320], [4, 17, 17, 128], [4, 17, 17, 224],
[4, 17, 17, 256], [4, 17, 17, 256], [4, 17, 17, 192],
[4, 17, 17, 96], [4, 17, 17, 22... |
Virako/authapi | authapi/api/migrations/0004_auto_20141128_0914.py | Python | agpl-3.0 | 419 | 0 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20141128_0831'),
]
op | erations = [
migrations.AlterField(
model_name='acl',
name='user',
field=models.ForeignKey(to='api.UserData', related_name='acls'),
),
]
|
ME-ICA/me-ica | meica.libs/nibabel/benchmarks/__init__.py | Python | lgpl-2.1 | 25 | 0 | # Benchmarks | for nibabel
| |
WaterSums/EPANETFileUtility | EPANETFileUtility.py | Python | mit | 16,145 | 0.006813 | # ex:set ts=4 sw=4: <- for vim
#
# EPANET File Utility
# Uses EPAENTOutputFile.py to read the EPANET output file into memory and
# then displays the content in different ways.
#
# Dependencies:
# - Python 2.6 or 2.7 (32- or 64-bit)
# - wxPython 3.0.0 (32- or 64-bit to match installed version of Python)
# - EPANETOutput... | #style = wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL
)
self.control = MyListbook(self, -1, None)
self.basetitle = title
self.Sizer | = wx.BoxSizer(wx.VERTICAL)
self.Sizer.Add(self.control, 1, wx.GROW)
self.dataPage = None
self.tablePage = None
self.exportPage = None
self.dirname = ''
self.filename = None
self.epanetoutputfile = None
il = wx.ImageList(80, 80)
bmp = wx.Bitmap('i... |
frastlin/PyAudioGame | examples/basic_tutorial/ex1.py | Python | mit | 712 | 0.030899 | #Working with variables
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Here are some variables
#Let | s first write one line of text
my_name = "Frastlin"
#now lets write a number
m | y_age = 42
#now lets write several lines of text
my_song = """
My application tis to be,
the coolest you've ever seen!
"""
#Magic time!
def logic(actions):
key = actions['key']
if key == "a":
#Here is our one line of text, it will speak when we press a
spk(my_name)
elif key == "s":
#Here is our number, it wi... |
rackerlabs/horizon | openstack_dashboard/dashboards/project/access_and_security/keypairs/views.py | Python | apache-2.0 | 3,100 | 0.000645 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | d 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.
"""
Views for managing keypairs.
"""
import logging
from django.core.urlres... | te.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView
from django.views.generic import View
from horizon import exceptions
from horizon import forms
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.access_... |
wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/IPython/html/services/contents/filecheckpoints.py | Python | mit | 6,954 | 0 | """
File-based Checkpoints implementations.
"""
import os
import shutil
from tornado.web import HTTPError
from .checkpoints import (
Checkpoints,
GenericCheckpointsMixin,
)
from .fileio import FileManagerMixin
from IPython.utils import tz
from IPython.utils.path import ensure_dir_exists
from IPython.utils.py... | one checkpoint ID:
checkpoint_id = u"checkpoint"
os_checkpoint_path = self.checkpoint_path( | checkpoint_id, path)
self.log.debug("creating checkpoint for %s", path)
with self.perm_to_403():
self._save_notebook(os_checkpoint_path, nb)
# return the checkpoint info
return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
def get_notebook_checkpoint(self, ch... |
UFCGProjects/sig | src/tests/DropTablesTest.py | Python | mit | 1,528 | 0.003927 | import psycopg2
import unittest
import sys
class LDropTablesTest(unittest.TestCase):
def setUp(self):
conn = psycopg2.connect("dbname=teste user=postgres")
conn.set_isolation_level(0) # set autocommit
self.cur = conn.cursor()
def tearDown(self):
self.c... | tatusmessage, "DROP TABLE")
def testEDropTableHorario(self):
self.cur.execute("DROP TABLE Horario;")
self.assertEqual(self.cur.statusmessage, "DROP TABLE")
def testDDropTableLocalization(self):
self.cur.execute("DROP TABLE Localization CASCADE;")
self.as... |
def testFDropTableOnibus(self):
self.cur.execute("DROP TABLE Onibus;")
self.assertEqual(self.cur.statusmessage, "DROP TABLE")
def testBDropTablePontoOnibusRota(self):
self.cur.execute("DROP TABLE PontoOnibus_Rota;")
self.assertEqual(self.cur.statusmessag... |
Sprytile/Sprytile | rx/subjects/anonymoussubject.py | Python | mit | 548 | 0 | from rx.core import ObservableBase
class AnonymousSubject(ObservableBase):
def __init__(self, observer, observable):
super(AnonymousSubject, self).__init__()
self.observer = observer
self.observable = observable
def _subscribe_core(self, obs | erver):
return self.observable.subscribe(observer)
def on_completed(self):
self.observer.on_completed | ()
def on_error(self, exception):
self.observer.on_error(exception)
def on_next(self, value):
self.observer.on_next(value)
|
alirizakeles/tendenci | tendenci/apps/payments/forms.py | Python | gpl-3.0 | 2,831 | 0.000706 | from datetime import datetime
from django import forms
from django.utils.translation import ugettext_lazy as _
from tendenci.apps.base.fields import SplitDateTimeField
from tendenci.apps.payments.models import Payment, PaymentMethod
PAYMENT_METHODS = PaymentMethod.objects.filter().values_list(
'machine_name', 'hum... | )
class Meta:
model = Payment
fields = (
'amount',
'payment_method',
'submit_dt',
)
def save(self, user, invoice, *args, **kwargs):
"""
Save payment, bind invoice inst | ance.
Set payment fields (e.g. name, description)
"""
instance = super(MarkAsPaidForm, self).save(*args, **kwargs)
instance.method = self.cleaned_data['payment_method']
instance.invoice = invoice
instance.first_name = invoice.bill_to_first_name
instance.last_nam... |
djabber/Dashboard | bottle/dash/local/lib/pif-0.7/src/pif/utils.py | Python | mit | 1,686 | 0.002372 | from __future__ import print_function
__title__ = 'pif.utils'
__author__ = 'Artur Barseghyan'
__copyright__ = 'Copyright (c) 2013 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('ensure_autodiscover', 'list_checkers', 'get_public_ip')
from pif.base import registry
from pif.discover import autodiscover
... | ip_checker = ip_checker_cls(verbose=verbose)
ip = ip_checker.get_public_ip()
if verbose:
print('provider: ', | ip_checker_cls)
return ip
# Using all checkers.
for ip_checker_name, ip_checker_cls in registry._registry.items():
ip_checker = ip_checker_cls(verbose=verbose)
try:
ip = ip_checker.get_public_ip()
if ip:
if verbose:
print('pro... |
ceb8/astroquery | astroquery/jplhorizons/core.py | Python | bsd-3-clause | 67,058 | 0.000224 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# 1. standard library imports
from numpy import nan
from numpy import isnan
from numpy import ndarray
from collections import OrderedDict
import warnings
# 2. third party imports
from astropy.table import Table, Column
from astropy.io import ascii
from ... | ative imports
# commonly required local imports shown below as example
# all Query classes should inherit from BaseQuery.
from ..query import BaseQuery
# async_to_sync generates the relevant query tools from _async methods
from ..utils import async_to_sync
# import configurable items declared in __init__.py
from . impo... | class for querying the
`JPL Horizons <https://ssd.jpl.nasa.gov/horizons/>`_ service.
"""
TIMEOUT = conf.timeout
def __init__(self, id=None, location=None, epochs=None,
id_type=None):
"""Instantiate JPL query.
Parameters
----------
id : str, required
... |
Venturi/cms | env/lib/python2.7/site-packages/aldryn_newsblog/migrations/0005_auto_20150807_0207.py | Python | gpl-2.0 | 558 | 0.001792 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('aldryn_newsblog', '0004_auto_20150622_1606'),
]
operations = [
migrations.AlterField(
model_name='newsblogconfig... | ngth=20, null=True, verbose_name='Prefix for template dirs', choices=[(b'dummy', b'dummy')]),
preserve_default=True | ,
),
]
|
elianearaujo/tst-qcheck | bin/qchecklib.py | Python | agpl-3.0 | 3,348 | 0.011947 | #!/usr/bin/env python
# Aid tools to quality checker.
# Qchecklib
# Eliane Araujo, 2016
import os
import sys
import commands
import json
try:
from cc import measure_complexity
except ImportError:
print("tst quality checker needs cc.py to work.")
sys.exit(1)
try:
sys.path.append('/usr/local/bin/radon... | port urllib.request as urlrequest
except ImportError:
import urllib as urlrequest
url = 'http://qchecklog.appspot.com/api/action/'
def four_metrics(program_name):
return "%s %s %s %s" % ( lloc(program_name), cc(program | _name), vhalstead(program_name), pep8(program_name)["count"])
def pep8count(program):
return int(pep8(program)[0])
def pep8(program):
result = []
cmd = 'pycodestyle.py --select=E --count ' + program
try:
pep_errors = commands.getoutput(cmd)
except ImportError:
print("tst quality ch... |
wavemoth/wavemoth | wavemoth/test/test_blas.py | Python | gpl-2.0 | 812 | 0.004926 | import numpy as np
from numpy import all
from numpy.testing import assert_almost_equal
from nose.tools import ok_
from ..blas import *
def ndrange(shape, dtype=np.double, order='C'):
return np.arange(np.prod(shape), dtype=dtype).reshape(shape).copy(order)
def assert_dgemm(dgemm_func, A_order, B_order, C_order):
... | r)
B = ndrange((k, n), order=B_order)
C = np.zeros((m, n), order=C_order)
dgemm_func | (A, B, C)
assert_almost_equal(C, np.dot(A, B))
test(2, 3, 4)
test(0, 3, 4)
test(2, 0, 4)
test(2, 3, 0)
test(0, 0, 2)
test(0, 2, 0)
test(0, 0, 2)
test(0, 0, 0)
def test_dgemm():
yield assert_dgemm, dgemm_crc, 'F', 'C', 'F'
yield assert_dgemm, dgemm_ccc, 'F', 'F', 'F'
... |
vyscond/my-college-api | cfg/wsgi.py | Python | mit | 546 | 0 | """
WSGI config for cfg project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_appl | ication
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cfg.settings")
try:
if os.environ['ENV'] == 'production':
from dj_static import Cling
application = Cling(get_wsgi_application())
except Exception as e:
applica | tion = get_wsgi_application()
|
amagdas/superdesk | server/apps/aap/import_text_archive/commands.py | Python | agpl-3.0 | 9,503 | 0.001789 |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import supe... | st='query', required=True),
superdesk.Option('--count', '-c', dest='limit', required=False)
)
def run(self, start_id, user, password, url, query, limit):
print('Starting text archive import at {}'.format(start_id))
self._user = user
self._password = password
self._id = i... | ne:
self._limit = int(limit)
else:
self._limit = None
self._api_login()
x = self._get_bunch(self._id)
while x:
self._process_bunch(x)
x = self._get_bunch(self._id)
if self._limit is not None and self._limit <= 0:
... |
pgaref/HTTP_Request_Randomizer | http_request_randomizer/requests/parsers/js/UnPacker.py | Python | mit | 1,507 | 0.004645 | import re
import requests
import logging
logger = logging.getLogger(__name__)
class JsUnPacker(object):
"""
It takes the javascript file's url which contains the port numbers for
the encrypted strings. The file has to be unpacked to a readable form just like
http://matthewfl.com/unPacker.html does. T... | \b" + self.bas | eN(c, a) + "\\b", k[c], p)
return p
def get_port(self, key):
return self.ports[key]
def get_ports(self):
return self.ports
|
liberza/bacon | simulator/payload.py | Python | mit | 4,318 | 0.003475 | #!/usr/bin/python3
import json
import numpy as np
import random
class Payload():
'''
Instance contains altitude data for a balloon flight. Use alt() method
to get interpolated data.
'''
addr = None
name = "Payload"
time_index = 0.0 # index into the flight profile data, in seconds.
tim... |
self.timestep = 1.0/(-0.0815243*x*x*x + 0.1355*x*x - 0.391461*x + 1.33748611)
self.time_index += time_delta*self.timestep
def drop_mass(self, ballast_time_ms):
# experimental results show 4.925ml/s drain rate. with current setup.
# we give it random +-10% error, because th... | 1.1)
new_mass = self.mass - (noise*ballast_time_ms*0.004925/1000)*0.8
if (new_mass > self.initial_mass - self.initial_ballast):
self.mass = new_mass
else:
self.mass = self.initial_mass - self.initial_ballast
if __name__ == '__main__':
# initialize Flights. 'PAYLOAD_X... |
amueller/strata_singapore_2015 | solutions/cross_validation_iris.py | Python | cc0-1.0 | 280 | 0 | from sklearn.datasets import load_iris
from sklea | rn.cross_validation import StratifiedKFold, KFold
iris = load_iris()
X, y = iris.data, iris.target
print(cross_val_sco | re(LinearSVC(), X, y, cv=KFold(len(X), 3)))
print(cross_val_score(LinearSVC(), X, y, cv=StratifiedKFold(y, 3)))
|
Treode/store | client/python/tx_clock.py | Python | apache-2.0 | 2,394 | 0.003759 | # Copyright 2014 Treode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ime_micro_seconds)
# Input time in micro-seconds!
def __init__(self, micro_seconds=None):
if (micro_seconds == None):
raise ValueError("Please input time in micro-seconds!")
elif (micro_seconds > TxClock.__max_micro_seconds):
print "micro_seconds: ", micro_seconds
... | raise ValueError("micro_seconds arg > max micro_seconds value")
# Assume user input time in micro-seconds
else:
self.time = long(micro_seconds)
def to_seconds(self):
# Times are ints, not floats
return self.time / (10**6)
def __repr__(self):
return "Tx... |
caseyrollins/osf.io | admin/base/settings/defaults.py | Python | apache-2.0 | 7,533 | 0.00146 | """
Django settings for the admin project.
"""
import os
from urlparse import urlparse
from website import settings as osf_settings
from django.contrib import messages
from api.base.settings import * # noqa
# TODO ALL SETTINGS FROM API WILL BE IMPORTED AND WILL NEED TO BE OVERRRIDEN
# TODO THIS IS A STEP TOWARD INTEG... | = {'osf4m': 'osf4m', 'prereg_challenge_campaign': 'prereg',
'institution_campaign': 'institution'}
# Set in local.py
DESK_K | EY = ''
DESK_KEY_SECRET = ''
TINYMCE_APIKEY = ''
SHARE_URL = osf_settings.SHARE_URL
API_DOMAIN = osf_settings.API_DOMAIN
if DEBUG:
INSTALLED_APPS += ('debug_toolbar', 'nplusone.ext.django',)
MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware', 'nplusone.ext.django.NPlusOneMiddleware',)
DEBUG... |
drxaero/calibre | src/calibre/gui2/convert/azw3_output.py | Python | gpl-3.0 | 978 | 0.00818 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.convert.azw | 3_output_ui import Ui_Form
from calibre.gui2.convert import Widget
font_family_model = None
class PluginWidget(Widget, Ui_Form):
TITLE = _('AZW3 Output')
HELP = _('Options specific to')+' AZW3 '+_('output')
COMMIT_NAME = 'azw3_output'
ICON = I('mimetypes/azw3.png')
def __init__(self, parent, get... | ['prefer_author_sort', 'toc_title',
'mobi_toc_at_start',
'dont_compress', 'no_inline_toc', 'share_not_sync',
]
)
self.db, self.book_id = db, book_id
self.initialize_options(get_option, get_help, db, book_id)
|
qubs/climate-data-api | core/views.py | Python | apache-2.0 | 102 | 0 | fro | m django.shortcuts import render
def hom | e(request):
return render(request, "core/home.html")
|
rimsleur/QSLime | debugger/ObjectViewer.py | Python | gpl-2.0 | 412 | 0.026239 | #!/usr/bin/python
# coding: utf | 8
"""
Окно просмотра информации по объектам кода (константы, поля, записи, таблицы, списки)
"""
import sys
from PyQt4 import QtGui
class ObjectViewer (QtGui.QTableView):
def __init__ (self | , main_window):
QtGui.QTableView.__init__ (self)
main_window.object_viewer = self
self.main_window = main_window |
jmimu/pyNekketsu | retrogamelib/dialog.py | Python | gpl-3.0 | 4,110 | 0.007056 | import pygame
def arrow_image(color):
img = pygame.Surface((7, 6))
img.fill((226, 59, 252))
img.set_colorkey((226, 59, 252), pygame.RLEACCEL)
pygame.draw.polygon(img, color, ((0, 0), (3, 3), (6, 0)))
return img
class Menu(object):
def __init__(self, font, options):
self.font = fon... |
ypos = pos[1]
i = 0
if background:
pygame.draw.rect(surface, background, (pos[0]-4, pos[1]-4,
self.width+8, self.height+6))
if border:
pygame.draw.rect(surface, border, (pos[0]-4, pos[1]-4,
self.width+8, self.height+8), 1)
... | icon = " "
ren = self.font.render(icon + opt)
surface.blit(ren, (pos[0], ypos))
ypos += ren.get_height()+3
i += 1
def move_cursor(self, dir):
if dir > 0:
if self.option < len(self.options)-1:
self.option += 1
... |
terrorobe/barman | setup.py | Python | gpl-3.0 | 3,778 | 0.001853 | #!/usr/bin/env python
#
# barman - Backup and Recovery Manager for PostgreSQL
#
# Copyright (C) 2011-2015 2ndQuadrant Italia (Devise.IT S.r.l.) <info@2ndquadrant.it>
#
# 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... | st
errno = pytest.main(self.test_args)
sys.exit(errno)
cmdclass={'test': PyTest}
except ImportError:
from distutils.core import setup
cmdclass={}
if sys.version_info < (2, 6):
raise SystemExit('ERROR: Barman needs at least python 2.6 to work')
install_requires = ['psycopg2',... | ']
if sys.version_info < (2, 7):
install_requires.append('argparse')
barman = {}
with open('barman/version.py', 'r') as fversion:
exec (fversion.read(), barman)
setup(
name='barman',
version=barman['__version__'],
author='2ndQuadrant Italia (Devise.IT S.r.l.)',
author_email='info@2ndquadrant.... |
michael-ball/sublime-text | sublime-text-3/Packages/SublimeLinter/commands.py | Python | unlicense | 39,327 | 0.001653 | # coding: utf-8
#
# commands.py
# Part of SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ryan Hileman and Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter3
# License: MIT
#
"""This module implements the Sublime Text commands provided by SublimeLinter."""
impor... | ne
# If going forward, find the first region beginning after the point.
# If going backward, find the first region ending before the point.
# If nothing is found in the given direction, wrap to the first/last region.
if direction == 'next':
for region in regions:
... | in())
):
region_to_select = region
break
else:
for region in reversed(regions):
if (
(point == region.end() and empty_selection and not region.empty()) or
(point > region.end())
... |
couchbasedeps/git-repo | git_config.py | Python | apache-2.0 | 21,644 | 0.014692 | # -*- coding:utf-8 -*-
#
# Copyright (C) 2008 The Android Open Source Project
#
# 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 re... | None : The value was not defined, or is not a boolean.
True : The value was set to true or yes.
False: The value was set to false or no.
"""
v = self.GetString(name)
if v is None:
return None
v = v.lower()
if v in ('true', 'yes'):
return True
if v in ('false', 'no'):
... | is not defined.
This configuration file is used first, if the key is not
defined or all_keys = True then the defaults are also searched.
"""
try:
v = self._cache[_key(name)]
except KeyError:
if self.defaults:
return self.defaults.GetString(name, all_keys = all_keys)
... |
arizvisa/syringe | lib/mpdebug/default/host.py | Python | bsd-2-clause | 491 | 0 | class base(object):
| proc = dict
pagesize = pow(2, 12)
arch = None
# and other host-specific attributes
def __init__(self, **kwds):
pass
def __getitem__(self, processid):
return self.proc[processid]
def list(self):
pass
def create(self, executable, args, env=[], directory='.', **kw... | pass
def detach(self, id):
pass
def terminate(self, id):
pass
#######
|
eddiejessup/nex | tests/test_reader.py | Python | mit | 3,129 | 0.00032 | import pytest
from nex.reader import Reader, ReaderBuffer
from common import (test_not_here_file_name, test_file_name, test_chars,
test_2_chars)
def test_buffer_init():
"""Check buffer works sensibly."""
r = ReaderBuffer(test_chars)
assert r.i == -1
assert r.chars == test_chars
... | serting a new file after reading a first, reads the first then the second."""
r = Reader()
r.insert_chars(test_chars)
cs = list(r.advance_to_end())
r.insert_chars(test_2_chars)
cs.extend(list(r.advance_to_end()))
assert cs == test_chars + test_2_chars
def test_peek():
"""Test various error... | rt_chars(test_chars)
# Can't peek at start of buffer
with pytest.raises(ValueError):
r.peek_ahead(n=0)
r.advance_loc()
assert r.current_char == 'a'
# Can't peek backwards, (especially because this would be end of buffer).
with pytest.raises(ValueError):
r.peek_ahead(n=-1)
# V... |
bosmanoglu/adore-doris | lib/python/insar/__init__.py | Python | gpl-2.0 | 25,698 | 0.033349 | # -insar.py- coding: utf-8 -*-
"""
Created on Fri Sep 3 10:46:50 2010
@author: bosmanoglu
InSAR module. Includes functions for analyzing SAR interferometry with python.
"""
from numpy import *
from pylab import *
from basic import *
import scipy
from scipy import ndimage #scipy.pkgload('ndimage')
from scipy import ... | luty, 'linear')
stdpha=lutf(coh)
return stdpha
def stdpha2coh(stdpha, L=1, n=100, lut=100):
'''stdpha2cohML(stdpha, L=1, n=100, lut=100):
Creates a lookup table for coherence to stdpha and uses it to reverse the relation
'''
if isinstance(stdpha,list):
stdpha=array(stdpha)
elif ... | p table y
for k in xrange(len(lutx)):
luty[k]=sqrt(trapz(domain**2*coh2pdfML(lutx[k],L,n),domain));
lutf=scipy.interpolate.interp1d(flipud(luty),flipud(lutx), 'linear', bounds_error=False)
coh=lutf(stdpha);
coh[stdpha > luty.max() ]=0.01;
coh[stdpha < luty.min() ]=0.99;
return coh
def g... |
drammock/mne-python | mne/externals/tqdm/_tqdm/auto.py | Python | bsd-3-clause | 231 | 0 | import warnings
from .std import TqdmExperimentalWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore", | category=TqdmExperimentalWarning)
from .autono | tebook import tqdm, trange
__all__ = ["tqdm", "trange"]
|
FlowFX/unkenmathe.de | src/system_tests/test_adding_and_editing_exercises.py | Python | agpl-3.0 | 4,459 | 0.000673 | """Selenium tests."""
from .conftest import assert_regex, wait_for, wait_for_true
from selenium.common.exceptions import NoSuchElementException
from um.exercises.factories import ExerciseFactory
import pytest
import time
def test_florian_adds_a_new_exercise(browser, live_server):
# Florian wants to add a new ... | lick()
# Then, he gets back to the ho | me page,
assert_regex(browser.current_url, '.+/')
def test_florian_deletes_an_exercise(browser, live_server, user):
# GIVEN an existing exercise
ex = ExerciseFactory.create(author=user)
# Florian goes to the home page and wants to delete this exercise
browser.get(live_server.url)
# and sees ... |
abalakh/robottelo | tests/foreman/ui/test_role.py | Python | gpl-3.0 | 3,848 | 0 | # -*- encoding: utf-8 -*-
"""Test class for Roles UI"""
from ddt import ddt
from fauxfactory import gen_string
from nailgun import entities
from robottelo.decorators import data
from robottelo.helpers import generate_strings_list, invalid_names_list
from robottelo.test import UITestCase
from robottelo.ui.factory impor... | ame):
"""@Test: Create new role
@Feature: Role - Positive Create
@Assert: Role is created
"""
with Session(self.browser) as session:
make_role(session, name=name)
self.assertIsNotNone(self.role.search(name))
@data('', ' ')
def test_negative | _create_role_with_blank_name(self, name):
"""@Test: Create new role with blank and whitespace in name
@Feature: Role - Negative Create
@Assert: Role is not created
"""
with Session(self.browser) as session:
make_role(session, name=name)
self.assertIsNot... |
transcranial/keras-js | python/model_pb2.py | Python | mit | 6,998 | 0.003144 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: model.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflect... | r.FieldDescriptor(
name='id', full_name='Model.id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_de... | ype=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='keras_version', full_name='Model.keras_version... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.