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 |
|---|---|---|---|---|---|---|---|---|
Miaou/PyPlagia | libplagia/testLib.py | Python | gpl-3.0 | 1,092 | 0.019337 | #!/usr/bin/python3
# Test de la lib
# Il fa | udrait des tests plus sérieux, en particulier pour vérifier que je me suis pas planté dans les indices dans les algos...
# (ce qui est arrivé au moins une fois)
# Et tester la symétrie
import ctypes
from sys import platform
#import random
import time
if platform.startswith('linux'): # win32
LIB_PATH='./libpla | gia.so' # Le './' est important
else:
LIB_PATH='libplagia.dll'
if __name__=='__main__':
# strAlignScore("dudu dodo toto", "toto")
libplagia = ctypes.cdll.LoadLibrary(LIB_PATH)
lToto = (ctypes.c_uint*4)(*list(map(ord,"toto")))
lBuf = (ctypes.c_uint*5)() # 4+1 pour les méthodes ilar, 4 pour sim.
... |
ezequielpereira/Time-Line | timelinelib/drawing/interface.py | Python | gpl-3.0 | 3,967 | 0.000252 | # Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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 th... | Draw a representation of a timeline.
The dc is used to do the actual drawing. The timeline is used to get
the events to visualize. The view properties contains information like
which events are selected in the view we are drawing for and what
period is currently displayed.
... | ariable must be deleted before the draw method ends.
"""
def use_fast_draw(self, value):
self.fast_draw = value
def event_is_period(self, time_period):
"""
Return True if the event time_period will make the event appear
below the center line, as a period event.
... |
elsevierlabs-os/soda | src/main/python/sodaclient_test.py | Python | apache-2.0 | 2,973 | 0.006054 | # -*- coding: utf-8 -* | -
import unittest
import sodaclient
SODA_URL = "http://localhost:8080"
LEXICON_NAME = "test_countries-3"
MATCHINGS = | ["exact", "lower", "stop", "stem1", "stem2", "stem3"]
LOOKUP_ID = "http://test-countries-3.com/ABW"
TEXT = "Institute of Clean Coal Technology, East China University of Science and Technology, Shanghai 200237, China"
PHRASE = "Emirates"
PHRASE_MATCHINGS = ["lsort", "s3sort"]
PHRASE_MATCHINGS.extend(MATCHINGS)
class S... |
jainaman224/zenodo | tests/unit/records/test_schemas_csl.py | Python | gpl-2.0 | 5,246 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later v... | cord.update({
'resource_type': {'type': 'publication'}
})
obj = csl_v1.transform_record(recid_pid, Record(minimal_record))
assert obj['type'] == 'article'
minimal_record.update({
'resource_typ | e': {'type': 'image'}
})
obj = csl_v1.transform_record(recid_pid, Record(minimal_record))
assert obj['type'] == 'graphic'
def test_author(db, minimal_record, recid_pid):
""""Test author."""
minimal_record['creators'] = []
obj = csl_v1.transform_record(recid_pid, Record(minimal_record))
ass... |
lerker/cupydle | cupydle/dnn/gridSearch.py | Python | apache-2.0 | 4,741 | 0.003586 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Ponzoni, Nelson"
__copyright__ = "Copyright 2015"
__credits__ = ["Ponzoni Nelson"]
__maintainer__ = "Ponzoni Nelson"
__contact__ = "npcuadra@gmail.com"
__email__ = "npcuadra@gmail.com"
__license__ = "GPL"
__version__ = "1.0.0"
_... | e}, {'a': 2, 'b': False}])
True
>>> grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}]
>>> list(ParameterGrid(grid)) == [{'kernel': 'linear'},
... | {'kernel': 'rbf', 'gamma': 1},
... {'kernel': 'rbf', 'gamma': 10}]
True
>>> ParameterGrid(grid)[1] == {'kernel': 'rbf', 'gamma': 1}
True
See also
--------
:class:`GridSearchCV`:
uses ``ParameterGrid`` to perform a full parallelized parameter search.... |
oliverdrake/brewtoad-scraper | tests.py | Python | mit | 2,584 | 0 | import mock
from nose.tools import assert_equals, raises
from scrapebrewtoad import Brewtoad
user = "me"
password = "password"
session = mock.Mock()
session.post.return_value.url = "http://dummyurl.com/blah/12345/"
@mock.patch("pyquery.PyQuery")
def test_init_stores_params_and_calls_login(PyQuery):
toad = Brewt... | )
@raises(ValueError)
@mock.patch("pyquery.PyQuery")
def test_init_raises_Val | ueError_if_login_post_returns_bad_response(PyQuery):
# If server doesn't return a url with a user id embedded:
with mock.patch.object(
session.post.return_value, 'url', "http://dummyurl.com/"):
Brewtoad(username_email=user, password=password, session=session)
@mock.patch("pyquery.PyQuery")... |
nevil-brownlee/pypy-libtrace | lib/natkit/try-dict.py | Python | gpl-3.0 | 2,776 | 0.009006 |
import plt, ipp
import os, string
print "Starting try-trace.py: dir() = %s" % dir()
# try-trace.py: test program for pypy plt
print "- - - - -"
print "NO_COMRESSION = %d" % plt.NO_COMPRESSION
#base = "/Users/jbro111" # OSX
base = "/home/nevil" # Ubuntu
#fn = "pypy/small-sample.erf"
#fn = "tcp-analyse/fdt-p5... | :
# print "File opened OK"
# file.close()
#except IOError as e:
# print "Unable to open file" #Does not exist OR no read permissions
trace_format = "pcapfile"
#trace_format = "erf"
uri = trace_format + ':' + full_fn
print ">> uri = %s" % uri
t = plt.trace(uri)
t.start()
test_dict = {}
def print_fir... | (t):
ip = pkt.ip
print "--- n=%d ---" % n
print "pkt linktype %d, ethertype %04x, vlan_id %d" % (
pkt.linktype, pkt.ethertype, pkt.vlan_id)
print "ip.seconds = %.6f, ip.ts_sec = %d, ip.time = %s" % (
ip.seconds, ip.ts_sec, ip.time)
print "ip.erf_time = %s" % ip.erf_time
print... |
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/twisted/test/test_application.py | Python | bsd-3-clause | 24,190 | 0.002728 | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
import sys, copy, os, pickle, warnings
from twisted.trial import unittest, util
from twisted.application import service, internet, app
from twisted.persisted import sob
from twisted.python import log, usage
from twisted.python.util impo... | uid = os.getuid()
curgid = os.getgid()
else:
curuid = curgid = 0
class TestProcess(unittest.TestCase):
def testID(self):
p = service.Process(5, 6)
self.assertEqual(p.uid, 5)
| self.assertEqual(p.gid, 6)
def testDefaults(self):
p = service.Process(5)
self.assertEqual(p.uid, 5)
self.assertEqual(p.gid, None)
p = service.Process(gid=5)
self.assertEqual(p.uid, None)
self.assertEqual(p.gid, 5)
p = service.Process()
self.assertEqu... |
benjamin9999/python-stix | stix/bindings/extensions/vulnerability/cvrf_1_1.py | Python | bsd-3-clause | 25,422 | 0.005035 | # Copyright (c) 2014, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated Thu Apr 11 15:07:59 2013 by generateDS.py version 2.9a.
#
import sys
import getopt
import re as re_
import stix.bindings.exploit_target as exploit_targe... | T%H:%M:%S')
else:
_svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S.%f')
if input_data.tzinfo is not None:
tzoff = input_data.tzinfo.utcoffset(input_data)
if tzoff is not None:
total_secon | ds = tzoff.seconds + (86400 * tzoff.days)
if total_seconds == 0:
_svalue += 'Z'
else:
if total_seconds < 0:
_svalue += '-'
total_seconds *= -1
else:
... |
open-pli/enigma2 | lib/python/Screens/InfoBar.py | Python | gpl-2.0 | 22,960 | 0.029268 | from Tools.Profile import profile
from Tools.BoundFunction import boundFunction
from enigma import eServiceReference
# workaround for required config entry dependencies.
import Screens.MovieSelection
from Screen import Screen
from Screens.MessageBox import MessageBox
profile("LOAD:enigma")
import enigma
profile("LO... | er)
no_plugin = False
except Exception, e:
self.session.open(MessageBox, _("The OperaBrowser plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def openSleepTimer(self):
from Screens.SleepTimerEdit import SleepTimerEdit
self.session.open(SleepTimerEdit)
def openTi... | m Screens.TimerEdit import TimerEditList
self.session.open(TimerEditList)
def showMediaPlayer(self):
try:
from Plugins.Extensions.MediaPlayer.plugin import MediaPlayer
self.session.open(MediaPlayer)
no_plugin = False
except Exception, e:
self.session.open(MessageBox, _("The MediaPlayer plugin is not... |
shianchin/mini_projects | stock_commision_fee_cal/stock.py | Python | apache-2.0 | 6,253 | 0.016152 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------
# Project : Stock commision fee calculator
#
# File name : stock.py
#
# Author : Cheang Shian Chin
#
# Date created : 20 Nov 2015
#
# Purpose : Calculate stoc... | re_lot = int(input('How many lots ( 1 lot = 100 shares): '))
gross_amount = price_per_share * share_lot * 100
print ("")
print (" Buy/Se | ll/Breakeven ", '{:>9}'.format(action.upper()))
print (" Quantity = ", '{:>9}'.format('{:,}'.format(share_lot * 100)))
print (" Price = RM ", '{:>9}'.format('{:,.6f}'.format(price_per_share)))
print (" Gross amount = RM ", '{:>9}'.format('{:,.2f}'.format(gross_amoun... |
alunduil/muniments | test_muniments/test_unit/test_scheduler/test_models/__init__.py | Python | mit | 208 | 0 | # Copyright (C) 2015 by Alex Brandt <alunduil@alunduil.com>
#
# muniments is freely distributable under the terms of an MIT-style license.
# See COPYING or ht | tp://www.opensource.org/licenses/mit-licen | se.php.
|
dennisobrien/bokeh | examples/plotting/file/bar_nested_colormapped.py | Python | bsd-3-clause | 1,229 | 0.00895 | from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure
from bokeh.transform import factor_cmap
output_file("bar_nested_colormapped.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ['2015', '2016', '201... | ("Apples", "2015"), ("Apples", "2016"), ("Apples", "2017"), ("Pears", "2015), | ... ]
x = [ (fruit, year) for fruit in fruits for year in years ]
counts = sum(zip(data['2015'], data['2016'], data['2017']), ()) # like an hstack
source = ColumnDataSource(data=dict(x=x, counts=counts))
p = figure(x_range=FactorRange(*x), plot_height=350, title="Fruit Counts by Year",
toolbar_location=Non... |
ClaudiaSaxer/PlasoScaffolder | src/plasoscaffolder/dependencies.py | Python | apache-2.0 | 1,470 | 0 | # -*- coding: utf-8 -*-
# fyi: those methods are copied from plaso
"""Functionality to check for the availability and version of dependencies."""
from __future__ import print_function
# Dictionary that contains version tuples per module name.
#
# A version tuple consists of:
# (version_attribute_name, minimum_version... | hon-click',
u'setuptools': u'python-setuptools',
u'Jinja2': u'python-jinja2',
u'colorama': u'python-colorama',
u'yapf': u'yapf3'}
# Maps Python module names to PyPI projects.
_PYPI_PROJECT_NAMES = {
u'click': u'click',
u'setuptools': u'setuptools ',
u'Jinja2': u'Jinja2',
u'colorama': u'... | pf'}
# Maps Python module names to RPM packages.
_RPM_PACKAGE_NAMES = {
u'click': u'python-click',
u'setuptools': u'python-setuptools',
u'Jinja2': u'python-Jinja2',
u'colorama': u'python-colorama',
u'yapf': u'yapf'}
|
soodoku/get-cricket-data | scripts/scraper.py | Python | mit | 1,947 | 0.010272 | '''
Download Cricket Data
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import csv
import sys
import time
import os
import unicodedata
from urlparse import urlparse
from BeautifulSoup import BeautifulSoup, SoupStrainer
BASE_URL = 'http://www.espncricinfo.com'
if not os.path.exists('./espncricinf... | str(i)).read())
#fc:
soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=first%20class;all=1;page=' + str(i)).read())
time.sleep(1)
for new_host in soupy.findAll('a', {'class' : 'srchPlyrNmTxt'}):
try:
new_host = new_host['href'... | 'ascii','ignore')
print new_host
#print(type(str.split(new_host)[3]))
print str.split(new_host, "/")[4]
html = urllib2.urlopen(odiurl).read()
if html:
with open('espncricinfo-fc/{0!s}'.format(str.split(new_host, "/")[4]), "wb") as f:
f.write(html)
... |
testmana2/test | PyUnit/__init__.py | Python | gpl-3.0 | 429 | 0 | # -*- coding | : utf-8 -*-
# Copyright (c) 2002 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Package implementing an interface to the pyunit unittest package.
The package consist of a single dialog, which may be called as a
standalone version using the eric6_unittest script or from within the eric6
IDE. If it is called... | t.
"""
|
gooofy/voxforge | zamiaai/skills/sports/__init__.py | Python | lgpl-3.0 | 735 | 0.009524 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016, 2017, 2018 Guenter Bartsch
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta | in a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permi... |
novalis/BusTracker | mta_data/management/commands/mta_to_gtfs.py | Python | gpl-3.0 | 23,554 | 0.013204 | from django.contrib.gis.geos import LineString, Point
from django.core.management.base import BaseCommand
from mta_data_parser import parse_schedule_dir
from mta_data.models import *
from mta_data.utils import st_line_locate_point
from subway_stop_to_gid import stop_id_to_gid, end_of_line
from zipfile import ZipFile
i... | kml xmlns="http://earth.google.com/kml/2.2">
<Document>
"""
for i, (x, y) in enumerate(coords):
print>>f, """
<Placemark>
<name>
%d
</name>
<Point>
<coordinates>%f, %f</coordinates>
</Point>
</Placemark>
""" % (i, x,... | (primary_key=True)
id = models.FloatField()
line = models.CharField(max_length=20)
routes = models.CharField(max_length=9)
the_geom = models.GeometryField()
class MTASubwayStop(models.Model):
gid = models.IntegerField(primary_key=True)
routes = models.CharField(max_length=13)
line = models.... |
saurabh6790/omnisys-lib | webnotes/install_lib/install.py | Python | mit | 8,275 | 0.039517 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# called from wnf.py
# lib/wnf.py --install [rootpassword] [dbname] [source]
from __future__ import unicode_literals
import os, sys, json
import webnotes
import webnotes.db
import getpass
from webnotes.model.db_s... | word: ")
self.root_password = root_password
self.conn = webnotes.db.Database(user=root_login, password=root_password)
def install(self, db_name, source_sql=None, admin_password = 'admin', verbose=0,
force=0):
if force or (db_name not in self.dbman.get_database_list()):
# delete user (if exists)
... | db_password)
if verbose: print "Created user %s" % db_name
# create a database
self.dbman.create_database(db_name)
if verbose: print "Created database %s" % db_name
# grant privileges to user
self.dbman.grant_all_privileges(db_name, db_name)
if verbose: print "Granted privileges to user %s and da... |
tlseabra/dailyprogrammer | Python/intermediate/i375.py | Python | mit | 352 | 0 | # 15/02/2019
# influenced heavily by Gprime5's solution
def flip(cards):
| order = []
direction = True
for i, card in enumerate(cards):
if direction:
ord | er.insert(0, str(i))
else:
order.append(str(i))
direction ^= (card == '1')
return ' '.join(order) if not direction else 'no solution'
|
TEDICpy/write-it | nuntium/migrations/0007_auto__add_messagerecord.py | Python | gpl-3.0 | 5,320 | 0.007895 | # -*- 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 model 'MessageRecord'
db.create_table(u'nuntium_messagerecord', (
(u'id', self.gf('djan... | AutoField', [], {'primary_key': 'True'}),
'label_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'uniq... | pe'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.Ch... |
alsrgv/tensorflow | tensorflow/python/distribute/saved_model_save_load_test.py | Python | apache-2.0 | 3,531 | 0.004248 | # Copyright 2019 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... | distribution)
@combinations.generate(
combinations.times(test_base.simple_models_with_strategies(),
combinations.combin | e(save_in_scope=[True, False])))
def test_save_strategy_restore_no_strategy(self, model_and_input,
distribution, save_in_scope):
if save_in_scope:
self.skipTest(('Saving model within tf.distribute.Strategy scope is not ',
'supported.'))
s... |
tonyseek/simple-rbac | examples/proxy.py | Python | mit | 3,965 | 0 | #!/usr/bin/env python
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from rbac.acl import Registry
from rbac.proxy import RegistryProxy
from rbac.context import IdentityContext, Perm... | urn self.roles.split(",")
def set_roles(self, roles):
self.roles = ",".join(roles)
class Message(ResourceMixin, ModelBase):
"""Message Model"""
__tablename__ = "post"
id = Column(Integer, primary_key=True)
content = Column(String, nullable=False)
owner_id = Column(ForeignKey(User.id)... | control list
acl = RegistryProxy(Registry())
identity = IdentityContext(acl, lambda: current_user.get_roles())
# registry roles and resources
acl.add_role("staff")
acl.add_role("admin")
acl.add_resource(Message)
def check(acl, role, operation, resource):
return db.query(Message).g... |
aevri/mel | mel/cmd/rotomapedit.py | Python | apache-2.0 | 21,197 | 0 | """Edit a 'rotomap' series of images.
In all modes:
Press 'q' to quit.
Press 'Q' to quit with exit code 1.
Press left for previous image, right for next image.
Press up for previous map, down for next map.
Ctrl-click on a point to zoom in on it.
Press 'z' or 'x' to adjust the zoom level.
P... |
import mel.lib.common
import mel.lib.fullscreenui
import mel.lib.image
import mel.lib.math
import mel.lib.u | i
import mel.rotomap.display
import mel.rotomap.mask
import mel.rotomap.moles
import mel.rotomap.relate
# Radius within which we should look for moles, in later work perhaps we'll
# make this configurable by the user.
_MAGIC_MOLE_FINDER_RADIUS = 50
def setup_parser(parser):
parser.add_argument(
"ROTOMAP"... |
sandeep048/python-saml | src/onelogin/saml2/auth.py | Python | bsd-3-clause | 16,929 | 0.002599 | # -*- coding: utf-8 -*-
""" OneLogin_Saml2_Auth class
Copyright (c) 2014, OneLogin, Inc.
All rights reserved.
Main class of OneLogin's Python Toolkit.
Initializes the SP SAML instance
"""
from base64 import b64encode
from urllib import quote_plus
import dm.xmlsec.binding as xmlsec
from onelogin.saml2.settings i... | out_response.get_error()
elif logout_response.get_status() != OneLogin_Saml2_Constants.STATUS_SUCCESS:
self.__errors.append('logout_not_success')
elif not keep_local_session:
OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
elif 'g | et_data' in self.__request_data and 'SAMLRequest' in self.__request_data['get_data']:
logout_request = OneLogin_Saml2_Logout_Request(self.__settings, self.__request_data['get_data']['SAMLRequest'])
if not logout_request.is_valid(self.__request_data):
self.__errors.append('invalid... |
fierval/KaggleMalware | Learning/SupervisedLearning.py | Python | mit | 5,930 | 0.005059 | import numpy as np
from sklearn.grid_search import GridSearchCV
import sklearn.metrics as metrics
from sklearn import preprocessing as prep
from tr_utils import merge_two_dicts, isEmpty
class SKSupervisedLearning (object):
"""
Thin wrapper around some learning methods
"""
def __init__(self, classifi... | validation sets based upon it
"""
self._scaler = self._fit_scaler(prep.StandardScaler, self.X_train)
self.X_train_scaled = self._scaler.transform(self.X_train)
self.X_test_scaled = self._scaler.transform(self.X_test)
def fit_and_validate(self):
'''
Returns tr... | Y_test = self.Y_test
self.clf.fit(X_train, Y_train)
# get probabilities
self._proba_train = self.clf.predict_proba(X_train)
self._proba_test = self.clf.predict_proba(X_test)
return metrics.log_loss(Y_train, self.proba_train), np.array([]) if isEmpty(Y_test) else metrics.log_l... |
mrGeen/cython | Cython/Compiler/ExprNodes.py | Python | apache-2.0 | 498,361 | 0.00197 | #
# Parse tree nodes for expressions
#
from __future__ import absolute_import
import cython
cython.declare(error=object, warning=object, warn_once=object, InternalError=object,
CompileError=object, UtilityCode=object, TempitaUtilityCode=object,
StringEncoding=object, operator=object,
... | __built | in__ import basestring
except ImportError:
# Python 3
basestring = str
any_string_type = (bytes, str)
else:
# Python 2
any_string_type = (bytes, unicode)
if sys.version_info[0] >= 3:
IS_PYTHON3 = True
_py_int_types = int
else:
IS_PYTHON3 = False
_py_int_types = (int, long)
class ... |
phievo/phievo | phievo/AnalysisTools/main_functions.py | Python | lgpl-3.0 | 7,449 | 0.015573 | import numpy as np
import shelve
import sys,os,glob,pickle,zipfile,re
from urllib.request import urlretrieve
from phievo.AnalysisTools import palette
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
def read_network(filename,verbose=False):
"""Retrieve a who... | ir_name+".zip")+("#"*int(state/2))+(" "*(50-int(state/2)))+"] {}%".format(state),end="\r")
urlretrieve(url,zip_path,reporthook=dlProgress)
print("{}: [".format(dir_name+" | .zip")+("#"*50)+"] 100%",end="\n")
## unziping file
print("Extracting zip file...",end="\r")
zip_ref = zipfile.ZipFile(zip_path, 'r')
zip_ref.extractall(dir_name)
zip_ref.close()
print("Extracting zip file... done.",end="\n")
print("Deleting zip file...",end="\r")
os.remove(zip_pa... |
rh-s/heat | heat/common/config.py | Python | apache-2.0 | 19,187 | 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
# ... | help=_('Keystone domain name which contains heat '
'template-defined users. If `stack_user_domain_id` '
'option is set, this option is ignored.')),
cfg.StrOpt('stack_domain_admin',
help=_('Keystone username, a user with roles sufficient to '
... |
help=_('Keystone password for stack_domain_admin user.')),
cfg.IntOpt('max_template_size',
default=524288,
help=_('Maximum raw byte size of any template.')),
cfg.IntOpt('max_nested_stack_depth',
default=5,
help=_('Maximum depth allowed ... |
puentesarrin/asyncflux | setup.py | Python | apache-2.0 | 2,548 | 0.000785 | # -*- coding: utf-8 *-*
import os
import subprocess
import sys
try:
from setuptools import setup
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
from distutils.cmd import Command
with open('README.rst') as f:
readme_content = f.read()... | ense :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
| 'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :... |
plotly/python-api | packages/python/plotly/plotly/validators/scatter3d/marker/_line.py | Python | mit | 5,005 | 0.0002 | import _plotly_utils.basevalidators
class LineValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="line", parent_name="scatter3d.marker", **kwargs):
super(LineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | rray containing
arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`... | l the bounds of the colorscale in
color space, use`marker.line.cmin` and
`marker.line.cmax`. Alternatively, `colorscale`
may be a palette name string of the following
list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,R
eds,Blues,Picnic,Rainbow,... |
tbeckham/DeploymentManager | resource_manager/server.py | Python | apache-2.0 | 658 | 0.00152 | #!/usr/bin/python
from eve import Eve
from eve.auth import BasicAuth
from flask_bootstrap import Bootstrap
from eve_docs import eve_docs
|
class ResourceManagerBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource, me | thod):
if method == 'GET':
# Allow read-only access without a password
return True
else:
# all the other resources are secured
return username == 'admin' and password == 'admin'
app = Eve(settings="./api_config.py", auth=ResourceManagerBasicAuth)
Bootstra... |
fbraem/mqweb | samples/python/channel_start.py | Python | mit | 1,189 | 0.023549 | '''
Starts a channel on a queuemanager
MQWeb runs on localhost and is listening on port 8081.
'''
import json
import httplib
import socket
import argparse
parser = argparse.ArgumentParser(
description='MQWeb - Python sample - Start Channel',
epilog="For more information: http://www.mqweb.org"
)
parser.add_argument... | annel', required=True)
args = parser.parse_args()
url = "/api/channel/start/" + args.queuemanager + '/' + args.channel;
try:
conn = httplib.HTTPConnection('localhost', 8081)
conn.request('GET', url)
res = conn.getresponse()
result = json.loads(res.read())
if 'error' in result:
print ('Received a WebSphere MQ ... | ean the channel is running! Use chstatus to get the status of the channel."
except httplib.HTTPException as e:
print ('An HTTP error occurred while starting a channel: ' +
e.errno + e.strerror
)
except socket.error as e:
print e.strerror
print 'Is the MQWeb daemon running?'
|
ratoaq2/Flexget | flexget/ui/plugins/schedule/__init__.py | Python | mit | 91 | 0 | fro | m __future__ import unicode_literals, division, absolute_import
f | rom .schedule import *
|
Frumple/mrt-file-server | instance_template/production/config.py | Python | mit | 510 | 0.005882 | # Add settings here that are specific for live production environments
# These settings will override those set in default_config.py
# SECRET_KEY must be set to a random and unique phrase before running the application.
# See http://flask.pocoo.org/docs/0.12/quickstart/ on how to gene | rate a secret key.
# SECRET_KEY = ""
# Enable basic authentication for production
BASIC_AUTH_FORCE = True
# Uncomment and set your basic authentication credentials
# BASIC_AUTH_USERNAME = "files"
# BASIC_AUTH_PAS | SWORD = "" |
alxgu/ansible | lib/ansible/modules/cloud/vmware/vmware_host_acceptance.py | Python | gpl-3.0 | 6,958 | 0.002731 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadat... | self.hosts_facts[host.name]['level'] = host_image_config_mgr.HostImageConfigGetAcceptance()
host_changed = True
except vim.fault.HostConfigFault as e:
self.hosts_facts[host.name]['error'] = to_native(e.msg)
change.append... | nged)
self.module.exit_json(changed=any(change), facts=self.hosts_facts)
def check_acceptance_state(self):
self.gather_acceptance_facts()
if self.desired_state == 'list':
self.module.exit_json(changed=False, facts=self.hosts_facts)
self.set_acceptance_level()
def main(... |
josepedro/acidentes_em_rodovias_refatoracao | acidentes_em_rodovias/app/models/ocorrencia_basica.py | Python | gpl-3.0 | 1,059 | 0.009506 | # -*- coding: utf-8 -*-
#
# Universidade de Brasilia - FGA
# Técnicas de Programação, 1/2014
#
# Acidentes em Rodovias, 2013-2014
# GitHub: https://github.com/josepedro/acidentes_em_rodovias_refatoracao
#
"""@package Municipios
Declaração das classes para ocorrencias.
Este modulo contem declação da classe de modelo
p... | table
self.ocodataocorrencia = ''
## Occurrences register's date table
self.ocodataregistro = ''
## Denomination table
| self.tcodescricao = ''
## Accident type table
self.ttadescricao = ''
## Accident cause table
self.tcadescricao = ''
## Local of hightway
self.lbrbr = ''
## Vehicle's brand table
self.tmvdescricao = ''
## Vehicle's table
self.tvvdescricao... |
raymondxyang/tensorflow | tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py | Python | apache-2.0 | 78,772 | 0.003504 | # Copyright 2016 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... | een set.
Raises:
ValueError: if `expected_shape` is not a `Tensor` and the shape of `value`
| is known and is not equal to `expected_shape`.
"""
assert isinstance(value, ops.Tensor)
if isinstance(expected_shape, tensor_shape.TensorShape):
expected_shape = expected_shape.as_list()
if isinstance(expected_shape, ops.Tensor):
expected_shape_value = tensor_util.constant_value(expected_shape)
... |
cedricbonhomme/k-means-clustering | recommend.py | Python | mit | 2,926 | 0.005126 | #! /usr/bin/python
#-*- coding:utf-8 -*
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.3 $"
__date__ = "$Date: 2015/08/31$"
__revision__ = "$Date: 2015/10/26 $"
__copyright__ = ""
__license__ = ""
import sys
import requests
import json
import pickle
import clusters
import lis | t_clusters
def recommend(user_id, recommender_nickname, recommender_password,
| service_url):
"""
Select talks/booths/poster to recommend from clusters.
"""
recommended_talks = []
request = requests.get(service_url + "/api/v1.0/profiles.json/" + user_id,
auth=(recommender_nickname, recommender_password))
if request.status_code == 200:
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_None/model_control_one_enabled_None_Lag1Trend_Seasonal_DayOfWeek_AR.py | Python | bsd-3-clause | 155 | 0.051613 | import tests.model_control.test_o | zone_custom_models_enabled as testmod
testmod.build_model( ['None'] , | ['Lag1Trend'] , ['Seasonal_DayOfWeek'] , ['AR'] ); |
py-in-the-sky/challenges | intermediate_words_search_python/shortest_path_search.py | Python | mit | 1,749 | 0.004574 | # imports from solution
from utils import underestimate_edit_distance_fn_factory
# 3rd-party imports
from Queue import Queue, PriorityQueue
def shortest_path_bfs(word1, word2, neighbors_fn, queue=None):
visited_words = set()
start_state = ( word1, )
q = Queue() if queue is None else queue
q.put(star... | rds = set()
start_state = (1 + underestimate_edit_distance(word1), ( word1, ))
q = PriorityQueue() if queue is None else queue
q.put(start_state)
while not q.empty():
_, path = q.get()
last_word = path[-1]
if last_word == word2:
return path
if last_word not... | bors_fn(last_word):
if neighbor_word not in visited_words:
new_path = path + ( neighbor_word, )
underestimated_distance_to_target = underestimate_edit_distance(neighbor_word)
underestimated_total_path_length = underestimated_distance_to_targe... |
manhhomienbienthuy/scikit-learn | sklearn/impute/__init__.py | Python | bsd-3-clause | 438 | 0 | """Transformers for missing value imputation"""
import typing
f | rom ._base import MissingIndicator, SimpleImputer
from ._knn import KNNImputer
if typing.TYPE_CHECKING:
# Avoid errors in type checkers (e.g. mypy) for experimental estimators.
# TODO: remove this check once the estimator is no longer experimental.
from ._iterative import IterativeImputer # noqa
__all__ ... | ", "KNNImputer"]
|
lissyx/build-mozharness | mozharness/mozilla/testing/testbase.py | Python | mpl-2.0 | 34,334 | 0.003291 | #!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import copy
import os
import pla... | tools import TryToolsMixin
from mozharness.mozilla.tooltool import TooltoolMixin
from mozharness.lib.python.authentication import get_credentials
INSTALLER_SUFFIXES = | ('.tar.bz2', '.zip', '.dmg', '.exe', '.apk', '.tar.gz')
testing_config_options = [
[["--installer-url"],
{"action": "store",
"dest": "installer_url",
"default": None,
"help": "URL to the installer to install",
}],
[["--installer-path"],
{"action": "store",
"dest": "installer... |
DirectXMan12/nova-hacking | nova/scheduler/chance.py | Python | apache-2.0 | 4,443 | 0.002476 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 OpenStack Foundation
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you m... | instance_uuid)
self.compute_rpcapi.run_instance(context,
instance=updated_instance, host=host,
requested_networks=requested_networks,
injected_files=injected_files | ,
admin_password=admin_password,
is_first_time=is_first_time,
request_spec=request_spec,
filter_properties=filter_properties)
except Exception as ex:
# NOTE(vish): we don't reraise the exception h... |
izrik/tudor | tests/logic_t/layer/LogicLayer/test_do_authorize_user_for_task_by_email.py | Python | gpl-2.0 | 7,024 | 0 | #!/usr/bin/env python
import unittest
from werkzeug.exceptions import Forbidden, NotFound
from tests.logic_t.layer.LogicLayer.util import generate_ll
class AuthorizeUserForTaskByEmailTest(unittest.TestCase):
def setUp(self):
self.ll = generate_ll()
self.pl = self.ll.pl
def test_authorizes_... | address
self.assertEqual(0, self.pl.count_users(email_in=['user@example.com']))
# and no users are authorized for the task
self.assertEqual(0, len(task.users))
# expect
self.assertRaises(
NotFound,
self.ll.do_authorize_user_for_task_by_email,
... | # and no users are authorized for the task
self.assertEqual(0, len(task.users))
def test_current_user_not_allowed_raises(self):
# given a task
task = self.pl.create_task('task')
self.pl.add(task)
# and a user to authorize
user = self.pl.create_user('user@example.c... |
SPARC-Auburn/Lab-Assistant | assistant/tests/gttstest.py | Python | apache-2.0 | 1,149 | 0.008703 | """
A testing program that utilizes Googles Text To Speech (GTTS) engine and pyglet to speak text.
Ensure that AVbin is installed for pyglet to run properly: https://avbin.github.io/AVbin/Downloa | d.html
"""
from gtts import gTTS
import time
import os
from sys import platform
if platform == "linux" or platform == "linux2":
import pygame
else:
import pyglet
def speak(whattosay):
print (whattosay)
audio_file = "response.mp3"
tts = gTTS(text=str(whattosay), lang="en")
tts.s | ave(audio_file)
playsound(audio_file)
os.remove(audio_file)
def playsound(audio_file):
if platform == "linux" or platform == "linux2":
pygame.mixer.pre_init(22050,-16,1,2048)
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(audio_file)
pygame.mixer.music.p... |
M2IS/vendendo | userapp/apps.py | Python | gpl-2.0 | 124 | 0 | from __future__ im | port unicode_literals
from django.apps import AppConfig
class UserConfig(AppConfig):
na | me = 'user'
|
RobWouters/omnikassa | tests/test_omnikassa.py | Python | mit | 1,432 | 0.000698 | import unittest
from omnikassa import Omnikassa
from omnikassa.exceptions import (
InvalidSeal,
InvalidResponseCode,
)
class OmnikassaTests(unittest.TestCase):
def setUp(self):
self.settings = {
'normalReturnUrl': 'https://example.com/omnikassa',
'automaticResponseUrl': 'h... | _seal(seal, data))
data = 'test string 1'
self.assertFalse(self.omnikassa._check_seal(seal, data))
def test_response_fail(self):
data = 'responseCode=99'
seal = self.omnikassa._generat | e_seal(data)
with self.assertRaises(InvalidResponseCode):
self.omnikassa.verify_callback({'Seal': seal, 'Data': data})
def test_response_success(self):
data = 'responseCode=00'
seal = self.omnikassa._generate_seal(data)
data = self.omnikassa.verify_callback({'Seal': seal... |
michel-slm/bodhi | bodhi/services/comments.py | Python | gpl-2.0 | 6,317 | 0.002691 | # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | data = request.validated
query = db.query(Comment)
anonymous = data.get('anonymous')
if anonymous is not None:
query = query.filter_by(anonymous=anonymous)
like = data.get('like')
if like is not None:
query = query.filter(or_(*[
Comment.text.like('%%%s%%' % like | )
]))
packages = data.get('packages')
if packages is not None:
query = query\
.join(Comment.update)\
.join(Update.builds)\
.join(Build.package)
query = query.filter(or_(*[Build.package==pkg for pkg in packages]))
since = data.get('since')
if ... |
hackoregon/urbandev-backend | wsgi.py | Python | mit | 1,231 | 0.019496 | import os, sys
# Web app imports
from flask import Flask, stream_with_context, request, Response
# Web app config
app = Flask(__name__)
app.config['DEBUG'] = True
def genMarkdownResult(filename):
hdr = '''<!DOCTYPE html>
<html>
<title>{}</title>
<xmp theme="united" style="dis... | return hdr.format(d[0]) + '\n'.join(d[1:]) + ftr
else:
return 'Error: Need more that one line in .md file'
@app.route('/')
def index():
return genMarkdownResult("doc/services.md")
@app.route('/permits/')
def permits():
return 'This is the permits service'
@app.rou | te('/neighborhoods/')
def neighborhoods():
return 'This is the neighborhoods service'
if __name__ == '__main__':
app.run()
#def application(environ, start_response):
# start_response('200 OK', [('Content-Type', 'text/html')])
# return [b'<html><body><h1 style="color:blue">Hello from wsgi</h1></body></h... |
szpotona/cloudify-openstack-plugin | system_tests/openstack_handler.py | Python | apache-2.0 | 17,759 | 0.000282 | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... | @property
def age | nt_keypair_name(self):
return self.config['agent_public_key_name']
@property
def management_keypair_name(self):
return self.config['manager_public_key_name']
@property
def use_existing_agent_keypair(self):
return self.config['use_existing_agent_keypair']
@property
def ... |
deathmetalland/IkaLog | tools/create_mask.py | Python | apache-2.0 | 1,712 | 0.001752 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA
#
# 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/l... | r implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This is a developtment tool to create a filtering mask from multiple images.
# Usage:
# ./tools/create_mask.p | y --input img1.png img2.png --output mask.png
#
# TODO:
# Support other filters in addition to MM_DARK.
#
import argparse
import cv2
import os.path
import sys
# Append the Ikalog root dir to sys.path to import IkaUtils.
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from ikalog.utils import *
def ... |
pycket/pycket | pycket/values_struct.py | Python | mit | 55,181 | 0.002773 | import itertools, sys
from pycket import config
from pycket import values
from pycket import vector as values_vector
from pycket.arity import Arity
from pycket.base import SingleResultMixin, UnhashableType
from pycket.cont import continuation, label
from pycket.error import SchemeException
from pycket.prims.expose imp... | w_name
self.constructor_name = w_constructor_name
self.w_super = w_super_type
self.init_field_count = init_f | ield_count
self.total_init_field_count = init_field_count
self.auto_field_count = auto_field_count
self.total_auto_field_count = auto_field_count
self.total_field_count = init_field_count + auto_field_count
if isinstance(w_super_type, W_StructType):
self.total_field_... |
odoousers2014/LibrERP | account_invoice_merge/invoice.py | Python | agpl-3.0 | 4,433 | 0.009023 | # -*- coding: utf-8 -*-
#################################################################################
# Autor: Mikel Martin (mikel@zhenit.com)
# Copyright (C) 2012 ZhenIT Software (<http://ZhenIT.com>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
... | id.name )
| if inv.state != 'draft' :
raise osv.except_osv(_("Invalid action !"),_("You can merge only invoices in draft state."))
# Merge invoices that are in draft state
inv_line_obj = self.pool.get('account.invoice.line')
name = parent.name or ''
comment = parent.comment... |
dbarbier/privot | python/test/t_TruncatedNormalFactory_std.py | Python | lgpl-3.0 | 1,645 | 0.004255 | #! /usr/bin/env python
from openturns import *
TESTPREAMBLE()
RandomGenerator().SetSeed(0)
try :
mu = NumericalPoint(4, 0.0)
sigma = NumericalPoint(4, 1.0)
a = NumericalPoint(4)
b = NumericalPoi | nt(4)
a[0] | = -4.0
b[0] = 4.0
a[1] = -1.0
b[1] = 4.0
a[2] = 1.0
b[2] = 2.0
a[3] = 3.0
b[3] = 6.0
PlatformInfo.SetNumericalPrecision(4)
for i in range(4) :
distribution = TruncatedNormal(mu[i], sigma[i], a[i], b[i])
size = 10000
sample = distribution.getSample(size)
... |
saffroncoin/csfrblockd | lib/blockchain/addrindex.py | Python | mit | 8,675 | 0.003919 | """
This module replaces blockexplorer functions with RPC calls to addrindex-enabled saffroncoind.
Module configuration:
blockchain-service-name=addrindex
blockchain-service-connect=http://RPC_USER:RPC_PASSWORD@RPC_HOST:RPC_PORT
"""
import decimal
import json
import re
import time
from lib import config, util, util_bi... | txlist.append(rpc('getrawtransaction', [rawtx]))
except Exception:
pass
rv = [rpc('decoderawtransaction', [tx]) for tx in txlist]
for tx in rv:
tx['confirmations'] = 0
return rv
def searchrawtx(address):
rv = []
idx = 0
while True:
chunk = rpc('se... | rv += [t for t in chunk if 'confirmations' in t and t['confirmations']]
idx += 100
return rv
def ismine(vout, address, allow_multisig=False):
return 'scriptPubKey' in vout and \
(allow_multisig or vout['scriptPubKey']['type'] != 'multisig') and \
'addresses' in vout['scriptP... |
stvstnfrd/edx-platform | common/djangoapps/student/management/tests/test_bulk_unenroll.py | Python | agpl-3.0 | 5,578 | 0.002331 | """Tests for Bulk Un-enroll Management command"""
from tempfile import NamedTemporaryFile
import six
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management import call_command
from testfixtures import LogCapture
from common.djangoapps.course_modes.tests.factories import CourseModeF... | , csv_file=csv_file)
course_id = self.enrollments[0].course.id
| with LogCapture(LOGGER_NAME) as log:
call_command("bulk_unenroll", "--commit")
log.check(
(
LOGGER_NAME,
'INFO',
'Processing [{}] with [1] enrollments.'.format(course_id),
),
(
... |
pmghalvorsen/gramps_branch | gramps/gen/plug/menu/_placelist.py | Python | gpl-2.0 | 1,794 | 0.003344 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007-2008 Brian G. Matherly
# Copyright (C) 2008 Gary Burton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either v... | .
"""
def __init__(self, label):
"""
:param label: A label to be applied to this option.
Example: "Places"
:type | label: string
:param value: A set of GIDs as initial values for this option.
Example: "111 222 333 444"
:type value: string
:return: nothing
"""
Option.__init__(self, label, "")
|
clede/Radiotrack | radiotracking/migrations/0003_program_day_string.py | Python | apache-2.0 | 472 | 0 | # -*- coding: utf-8 -*-
# | Generated by Django 1.10.1 on 2016-09-29 05:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('radiotracking', '0002_auto_20160918_0244'),
]
operations = [
migrations.AddField(
model_... | ,
name='day_string',
field=models.CharField(default='', max_length=30),
),
]
|
colour-science/colour-hdri | colour_hdri/generation/tests/test_radiance.py | Python | bsd-3-clause | 2,680 | 0.000373 | # !/usr/bin/env python
"""Defines the unit tests for the :mod:`colour_hdri.generation.radiance` module."""
from __future__ import annotations
import numpy as np
import os
import unittest
from colour import RGB_COLOURSPACES
from colour.hints import List
from colour_hdri import TESTS_RESOURCES_DIRECTORY
from colour_h... | "
__status__ = "Production"
__all__ = [
"FROBISHER_001_DIRECTORY",
"GENERATION_DIRECTORY",
"JPG_IMAGES",
"TestRadianceImage",
]
FROBISHER_001_DIRECTORY: str = os.path.join(
TESTS_RESOURCES_DIRECTORY, "frobisher_001"
)
GENERATION_DIRECTORY: str = os.path.join(
TESTS_RESOURCES_DIRECTORY, "colou... | lour_hdri.generation.radiance.\
image_stack_to_radiance_image` definition unit tests methods.
"""
def test_radiance_image(self):
"""
Test :func:`colour_hdri.generation.\
radiance.image_stack_to_radiance_image` definition.
"""
image_stack = ImageStack.from_files(JPG_IMAGES)
... |
melkamar/webstore-manager | tests/test_util.py | Python | mit | 2,782 | 0 | import requests
import pytest
import json
import os
import zipfile
from flexmock import flexmock
import webstore_manager.util as util
from webstore_manager.util import pushd, temp_dir
def test_check_requests_response_status_ok():
response = flexmock()
response.should_receive('raise_for_status').and_return(Tr... | .and_raise(requests.HTTPError)
response.should_receive('json').and_return(json.dumps({"foo": "bar"}))
with pytest.raises(requests.HTTPError):
util.handle_requests_response_status(response)
def test_read_json_key_ok():
assert util.read_json_key({"foo": "bar"}, "foo") == "bar"
def test_read_json_... | read_json_key({"foo": "bar"}, "invalid")
def test_makezip_nodest():
zip_path = os.path.join(os.getcwd(), 'tests/files/sample_folder')
temp_path = 'tests/files/temp_test_makezip'
zip_name = 'testzip.zip'
with temp_dir(temp_path):
with pushd(temp_path):
assert not os.path.exists(zip... |
google/deepvariant | deepvariant/multisample_make_examples.py | Python | bsd-3-clause | 9,287 | 0.004092 | # Copyright 2021 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... | _image_heights'
]:
if flags_obj[flag_name].value != 'DEFAULT':
flags_organized[flag_name] = | flags_obj[flag_name].value.split(';')
if len(flags_organized[flag_name]) != num_samples:
raise ValueError(f'--{flag_name} has {len(flags_organized[flag_name])} '
f'samples, but it should be matching the number of '
f'samples in --reads, which was {num_samp... |
0xbaadf00d/phial | phial/jinja_tools/ext/__init__.py | Python | mit | 194 | 0 | # -*- coding: utf-8 -*-
from .jinja2htmlcompress import SelectiveHTMLCompress
fro | m .jinja2datetime import DatetimeExtension
__all__ = [
'DatetimeExtension',
'SelectiveHTMLC | ompress',
]
|
mapzen/vector-datasource | integration-test/1622-hide-early-university.py | Python | mit | 3,553 | 0 | # -*- encoding: utf-8 -*-
from . import FixtureTest
class HideEarlyUniversityTest(FixtureTest):
def test_large_university(self):
import dsl
z, x, y = (10, 165, 399)
self.generate_fixtures(
# https://www.openstreetmap.org/relation/309918
dsl.way(309918, dsl.box_ar... | : 'openstr | eetmap.org',
'type': 'multipolygon',
'website': 'https://csumb.edu/',
'wikidata': 'Q624686',
'wikipedia': 'en:California State University, Monterey Bay',
}),
)
self.assert_has_feature(
z, x, y, 'pois', {
... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extract夢見る世界.py | Python | bsd-3-clause | 772 | 0.046543 | def extract夢見る世界(item):
"""
Parser for '夢見る世界'
"""
if 'Otome Games' in item['tags']:
return None
if 'Drama CDs' in item['tags']:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower() | :
return None
tagmap = [
('Miss Appraiser and Gallery Demon', 'Miss Appraiser and Gallery Demon', 'translated'),
('Light Bey | ond Road\'s End', 'Light Beyond (LN)', 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
byt3bl33d3r/CrackMapExec | cme/modules/zerologon.py | Python | bsd-2-clause | 3,386 | 0.006202 | # everything is comming from https://github.com/dirkjanm/CVE-2020-1472
# credit to @dirkjanm
# module by : @mpgn_x64
import sys
from impacket.dcerpc.v5 import nrpc, epm
from impacket.dcerpc.v5.dtypes import NULL
from impacket.dcerpc.v5 import transport
from impacket import crypto
import hmac, hashlib, struct, sys, soc... | ck is probably not working.
if ex.get_error_code() == 0xc0000022:
return None
else:
fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
except BaseException as ex:
fail | (f'Unexpected error: {ex}.')
def perform_attack(dc_handle, dc_ip, target_computer):
# Keep authenticating until succesfull. Expected average number of attempts needed: 256.
logging.debug('Performing authentication attempts...')
rpc_con = None
binding = epm.hept_map(dc_ip, nrpc.MSRPC_UUID_NRPC, protocol... |
sgiavasis/nipype | nipype/interfaces/camino/__init__.py | Python | bsd-3-clause | 848 | 0 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Camino top l | evel namespace
"""
from .conne | ctivity import Conmat
from .convert import (Image2Voxel, FSL2Scheme, VtkStreamlines, ProcStreamlines,
TractShredder, DT2NIfTI, NIfTIDT2Camino, AnalyzeHeader,
Shredder)
from .dti import (DTIFit, ModelFit, DTLUTGen, PicoPDFs, Track, TrackPICo,
TrackBayesDirac,... |
dirtycold/git-cola | cola/version.py | Python | gpl-2.0 | 2,260 | 0 | # Copyright (c) David Aguilar
"""Provide git-cola's version number"""
from __future__ import division, absolute_import, unicode_literals
import os
import sys
if __name__ == '__main__':
srcdir = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(1, srcdir)
from .git import git
from .git import STDOUT
... | ueError:
n = p
ver_list.append(n)
return ver_list
|
@memoize
def git_version_str():
"""Returns the current GIT version"""
return git.version()[STDOUT].strip()
@memoize
def git_version():
"""Returns the current GIT version"""
parts = git_version_str().split()
if parts and len(parts) >= 3:
return parts[2]
else:
# minimum support... |
nortxort/tinybot-rtc | apis/other.py | Python | mit | 3,454 | 0.002316 | """ Contains functions to fetch info from different simple online APIs."""
import util.web
def urbandictionary_search(search):
"""
Searches urbandictionary's API for a given search term.
:param search: The search term str to search for.
:return: defenition str or None on no match or error.
"""
... | onse['json'] is not None:
if response['json']['type'] == 'success':
joke | = response['json']['value']['joke']
return joke
return None
|
benqiu2016/nifi-minifi-cpp | thirdparty/librdkafka-0.11.1/packaging/nuget/release.py | Python | apache-2.0 | 2,393 | 0.002507 | #!/usr/bin/env python
#
| #
# NuGet release packaging tool.
# Creates a NuGet package from CI artifacts on S3.
#
import sys
import argparse
import packaging
dry_run = False
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--no-s3", help="Don't collect from S3", action="store_true")
parser.ad... | acts but don't actually download or do anything",
action="store_true")
parser.add_argument("--directory", help="Download directory (default: dl-<tag>)", default=None)
parser.add_argument("--no-cleanup", help="Don't clean up temporary folders", action="store_true")
parser.add_argument... |
fnp/wolnelektury | src/sponsors/__init__.py | Python | agpl-3.0 | 236 | 0 | # | This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
__author__ = 'Marek Stępniowski, <marek@stepniowski.com>'
__version__ = '0 | .1'
|
joedeller/pymine | forloop.py | Python | mit | 1,535 | 0.000651 | #! /usr/bin/pyt | hon
# Joe Deller 2014
# Using for loops
# Level : Beginner
# Uses : Libraries, variables, operators, loops
# Loops are a very important part of programming
# The for loop is a very common loop
# It counts from a starting number to a finishing number
# It normally counts up in ones, but you can count up
# in any numb... | his program uses a for loop to draw wool blocks
# of all 16 different colours
# It also uses the for loop to set where the block is drawn
# so we can see all 16 colours
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
# Setup the connection and clear a space
# set us down in the middle of th... |
sandz-in/twilio_trello | twilio_sms_handler/apps.py | Python | mit | 174 | 0 | # | -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
clas | s TwilioSmsHandlerConfig(AppConfig):
name = 'twilio_sms_handler'
|
github-borat/cinder | cinder/tests/test_netapp_nfs.py | Python | apache-2.0 | 47,799 | 0.000063 |
# Copyright (c) 2012 NetApp, 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 require... | /mnt')
drv._discover_file_till_timeout(IgnoreArg()).AndReturn(True)
| drv._set_rw_permissions_for_all(IgnoreArg())
mox.ReplayAll()
loc = drv.create_volume_from_snapshot(volume, snapshot)
self.assertEqual(loc, expected_result)
mox.VerifyAll()
def _prepare_delete_snapshot_mock(self, snapshot_exists):
drv = self._driver
mox = self.mox... |
mozillazg/lark | lark/music/models.py | Python | mit | 1,119 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.db import models
from django.utils.encoding import python_2 | _unicode_compatible
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
@python_2_unicode_compatible
class Music(TimeStampedModel):
title = models.CharField(_('title'), max_length=100)
author = models.CharField(_('author'), max_length=50)
cover = models... | d(_('ogg file url'))
douban = models.URLField(_('douban page'), blank=True)
sid = models.CharField(_('SID'), max_length=10, blank=True)
class Meta:
verbose_name = _('music')
verbose_name_plural = _('music')
def __str__(self):
return '"{0}" by {1}'.format(self.title, self.author... |
yhtang/MUI | wrappers/Python/mui4py/common.py | Python | apache-2.0 | 4,086 | 0.007097 | import collections
import mui4py.mui4py_mod as mui4py_mod
from mui4py.config import get_default_config
from mui4py.types import map_type, get_float_type_str, get_int_type_str, get_io_type_str
import re
import numpy as np
class CppClass(object):
def __init__(self, config=None, args=(), kwargs={}):
self._cpp... | w_point = None
self.raw = N | one
self.io_data_type = None
# Convertir args en Args()
self.args = tuple([Arg(a) if not issubclass(a.__class__, Arg) else a for a in args])
self.namespace = ""
# Filter None-valued entries to gake C++ default values.
self.kwargs = {k: v for k, v in kwargs.items() if v is... |
opotowsky/cyclus.github.com | source/numpydoc/docscrape_sphinx.py | Python | bsd-3-clause | 9,437 | 0.001166 | from __future__ import division, absolute_import, print_function
import sys, re, inspect, textwrap, pydoc
import sphinx
import collections
from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
if sys.version_info[0] >= 3:
sixu = lambda s: s
else:
sixu = lambda s: unicode(s, 'unicode_escape')
class Sp... | name)
out += ['']
for param, param_type, desc in self[name]:
if param_type:
out += self._str_indent(['**%s** : %s' % (param.strip(),
param_type)])
else:
out += se... | trip()])
if desc:
out += ['']
out += self._str_indent(desc, 8)
out += ['']
return out
@property
def _obj(self):
if hasattr(self, '_cls'):
return self._cls
elif hasattr(self, '_f'):
return sel... |
nuagenetworks/vspk-python | vspk/v6/nuconnectionendpoint.py | Python | bsd-3-clause | 14,146 | 0.00919 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyrigh... | s", remote_name="IPAddress", attribute_type=str, is | _required=False, is_unique=False)
self.expose_attribute(local_name="ip_type", remote_name="IPType", attribute_type=str, is_required=False, is_unique=False, choices=[u'IPV4', u'IPV6'])
self.expose_attribute(local_name="ipv6_address", remote_name="IPv6Address", attribute_type=str, is_required=False, is_un... |
karlward/igsql | igsql/database.py | Python | gpl-3.0 | 537 | 0.001862 | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('postgresql://igsql:igsql@127.0.0.1/igsql' | )
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session. | query_property()
def init_db():
import igsql.model
Base.metadata.create_all(bind=engine)
|
EmreAtes/spack | var/spack/repos/builtin/packages/r-iranges/package.py | Python | lgpl-2.1 | 2,504 | 0.001198 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | t list-like
| classes for storing, transforming
and aggregating large grouped data,
i.e., collections of atomic vectors and DataFrames."""
homepage = "https://www.bioconductor.org/packages/IRanges/"
url = "https://git.bioconductor.org/packages/IRanges"
list_url = homepage
version('2.12.0', git='http... |
angusgbishop/biast | makeDrink.py | Python | apache-2.0 | 13 | 0.076923 | def makeDr | ink | |
NicolasLM/crawler | crawler/crawler.py | Python | mit | 3,682 | 0.001086 | from urllib.parse import urlparse
from collections import namedtuple
import socket
import requests
from requests.packages import urllib3
from bs4 import BeautifulSoup
import rethinkdb as r
from celery import Celery
from celery.utils.log import get_task_logger
import pyasn
import geoip2.database, geoip2.errors
import ... | in_info):
| r.table('domains').insert({
'name': domain_name,
'success': True,
'headers': domain_info.headers,
'elapsed': domain_info.elapsed,
'asn': domain_info.asn,
'country': domain_info.country,
'date': r.now()
}).run(conn)
logger.info('Fetched domain {} in {}ms'.... |
nycholas/ask-undrgz | src/ask-undrgz/django/template/defaultfilters.py | Python | bsd-3-clause | 28,636 | 0.005133 | """Default variable filters."""
import re
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import random as random_module
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.template import Variable, Library
from django... | s(value)
fix_ampersands.is_safe=True
fix_ampersands = stringfilter(fix_ampersands)
# Values for testin | g floatformat input against infinity and NaN representations,
# which differ across platforms and Python versions. Some (i.e. old Windows
# ones) are not recognized by Decimal but we want to return them unchanged vs.
# returning an empty string as we do for completley invalid input. Note these
# need to be built up f... |
OrlyMar/gasistafelice | gasistafelice/lib/views_support.py | Python | agpl-3.0 | 10,577 | 0.011629 | # This code has been taken from http://www.assembla.com/spaces/datatables_demo/wiki
from django.db.models import Q
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.utils.cache import add_never_cache_headers
from django.utils import simplejson
import os
fro... | ecord:
querySet = querySet[startRecord:endRecord] #get the slice
return querySet, {
'iTotalRecords' : iTotalRecords,
'iTotalDisplayRecords' : iTotalDisplayRecords,
}
def prepare_datatables_list(request, queryList, columnIndexNameMap, *args):
"""
Retrieve list of objec... | umnIndexNameMap: field names in order to be displayed.
Return a tuple:
queryList: data to be displayed after this request
datatables parameters: a dict which includes
- iTotalRecords: total data before filtering
- iTotalDisplayRecords: total data after filtering
"... |
burunduk3/t.sh | unsorted.py | Python | gpl-2.0 | 1,016 | 0.024606 | import os
suffixes = {
'c': 'c',
'pas': 'pascal', 'dpr': 'delphi',
'java': 'java', 'pl': 'perl', 'py': detector_python, 'sh': 'bash'
}
def suffixes_all ():
return suffixes.keys ()
def tests_export ( problem ):
os.chdir (problem.path)
if not problem.tests:
problem.research_tests ()
... | sts'):
os.mkdir ('tests')
pattern = '%02d'
if len (tests) >= 100:
pattern = '%03d'
if len (tests) >= 1000:
raise Error ("[problem %s]: too many tests (%d)" % (problem.name, len (tests)))
n = 0
for i, x in enumerate (tests):
test = x.create ()
name = patt | ern % (i + 1)
shutil.copy (test, os.path.join ('tests', name))
shutil.copy (test + '.a', os.path.join ('tests', name) + '.a')
n += 1
log ('pattern: %s, tests copied: %d' % (pattern, n))
|
vasilcovsky/pytinypng | pytinypng/__init__.py | Python | bsd-2-clause | 54 | 0 | __ | version__ = '0.0.9'
__author__ = 'Igor Va | silcovsky'
|
kafluette/ffnnet | ffnnet.py | Python | apache-2.0 | 10,067 | 0.000397 | #!/usr/bin/env python
"""Example which shows with the MNIST dataset how Lasagne can be used."""
from __future__ import print_function
import gzip
import itertools
import pickle
import os
import sys
import numpy as np
import lasagne
import theano
import theano.tensor as T
from scipy.linalg import hadamard
from scipy.... | area = (1.0 / np.sqrt(num_units * np.pi)) *\
((2 * np.pi *np.exp(1)) / num_units) ** (num_units / 2)
s_i = ((2.0 * np.pi) ** (-num_units / 2.0)) * (1.0 / area)
for i in xrange(num_units):
S_values[i, i] = s_i * g_frob
self.S = theano.shared(value=S_values, name='S', bo... | np.random.shuffle(np.transpose(perm_matrix_values))
perm_matrix = theano.shared(value=perm_matrix_values, name='PI',
borrow=True)
self.PI = perm_matrix
# H - Hadamard matrix
H_values = hadamard(num_units, dtype=np.int)
H = theano.share... |
RedFantom/GSF-Parser | network/minimap/server.py | Python | gpl-3.0 | 4,942 | 0.000405 | """
Author: RedFantom
Contributors: Daethyra (Naiii) and Sprigellania (Zarainia)
License: GNU GPLv3 as in LICENSE
Copyright (C) 2016-2018 RedFantom
"""
import socket
import threading
from queue import Queue
from select import select
from ast import literal_eval
from network.connection import Connection
SUPPORTED_COMM... | """Logout a Client from the Server"""
self.client_sockets.remove(client)
name = self.client_names[client]
for client_alt in self.client_sockets:
client_alt.send("logout_{}".format(name))
del self.client_names[client]
try:
client.send("exi | t")
except (OSError, socket.error):
pass
print("[MiniMapServer] Client logout")
client.close()
def stop(self):
"""Stop the Server's activities"""
self.exit_queue.put(True)
|
HMProgrammingClub/NYCSL | problems/workers/worker.py | Python | mit | 6,938 | 0.027674 | import os
import os.path
import stat
import platform
import trueskill
import pymysql.cursors
import random
import shutil
import urllib.request
import urllib.parse
from sandbox import *
from config import *
import copy
TRON_PROBLEM_ID = 3
cnx = pymysql.connect(host="162.243.229.252", user="superuser", database="Defhack... | nnerRating, loserRating = trueskill.rate_1vs1(winnerRating, loserRating)
print("Score: " + str(winnerRating.mu - (3*winnerRating.sigma)))
cursor.execute("UPDATE Submission SET mu = %f, sigma = %f, score = %f WHERE userID = %d and problemID = %d" % (winnerRating.mu, winnerRating.sigma, float(winnerRating.mu - (3*winne... | = %f, score = %f WHERE userID = %d and problemID = %d" % (loserRating.mu, loserRating.sigma, float(loserRating.mu - (3*loserRating.sigma)), loserID, TRON_PROBLEM_ID))
cnx.commit()
# Get replay file by parsing shellOutput
replayFilename = lines[-1][len("Output file is stored at ") : len(lines[-1])]
shutil.move(os.p... |
henriquegemignani/randovania | randovania/game_description/world/dock.py | Python | gpl-3.0 | 1,738 | 0.000575 | from dataclasses import d | ataclass
from enum import unique, Enum
from typing import Iterator
from frozendict import frozendict
from randovania.game_description.requirements import Requirement
@unique
class DockLockType(Enum):
FRONT_ALWAYS_BACK_FREE = 0
FRONT_BLAST_BACK_FREE_UNLOCK = 1
FRONT_BLAST_BACK_BLAST = 2
FRONT_BLAST_B... | extra: frozendict
requirement: Requirement
def __hash__(self):
return hash((self.name, self.lock_type, self.extra))
def __repr__(self):
return self.name
@property
def long_name(self):
return self.name
@dataclass(frozen=True)
class DockType:
short_name: str
long... |
leotrubach/sourceforge-allura | ForgeGit/forgegit/tests/functional/test_controllers.py | Python | apache-2.0 | 8,569 | 0.003151 | import json
import re
import tg
import pkg_resources
import pylons
pylons.c = pylons.tmpl_context
pylons.g = pylons.app_globals
from pylons import c
from ming.orm import ThreadLocalORMSession
from datadiff.tools import assert_equal
from allura import model as M
from allura.lib import helpers as h
from allura.tests im... |
def test_merge_request_visible_to_admin(self):
assert 'Request Merge' in self._fork_page()
def test_merge_request_invisible_to_non_admin(self):
assert 'Request Merge' not in self._fork_page(
extra_environ=dict(username='test-user'))
def test_merge_action_available_to_admin(se... | elf.app.get(
'/p/test2/code/request_merge',
status=403, extra_environ=dict(username='test-user'))
def test_merge_request_detail_view(self):
r, mr_num = self._request_merge()
assert 'would like you to merge' in r, r.showbrowser()
def test_merge_request_list_view(self):
... |
ailabitmo/sempubchallenge2014-task1 | CeurWsParser/parsers/publication_parser.py | Python | mit | 13,497 | 0.003186 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urllib
import os
import tempfile
import traceback
from grab.error import DataNotFound
from grab.tools import rex
from grab.spider import Task
from rdflib import URIRef, Literal
from rdflib.namespace import RDF, RDFS, FOAF, DCTERMS, DC, XSD
from PyPDF2 im... | ile_name = link.rsplit('.pdf')[0].rsplit('/')[-1]
publication_object = {
'name': name,
'file_name': file_name,
'link': link,
'editors': editors
}
publication_object['is_invited'] = self.is_inv... | ication_object)
if len(self.data['workshops']) > 1:
try:
session = self.grab.tree.xpath(
'//a[@href="%s"]/preceding::*[@class="CEURSESSION"][1]' % href)[0]
publication_object['presentedAt'] = []
... |
mvaled/sentry | src/sentry/tasks/options.py | Python | bsd-3-clause | 1,214 | 0.002471 | from __future__ import absolute_import
import logging
import six
from datetime import timedelta
from django.utils import timezone
from sentry.models import Option
from sentry.options import default_manager
from sentry.options.manager import UnknownOption
from sentry.tasks.base import instrumented_task
ONE_HOUR = 60... | ezone.now() - timedelta(seconds=cutoff)
# TODO(dcramer): this doesnt handle deleted options (whic | h shouldn't be allowed)
for option in Option.objects.filter(last_updated__gte=cutoff_dt).iterator():
try:
opt = default_manager.lookup_key(option.key)
default_manager.store.set_cache(opt, option.value)
except UnknownOption as e:
logger.exception(six.text_type(e))
|
bonville/nyc-councilmatic-test | core/migrations/0001_initial.py | Python | mit | 9,776 | 0.00358 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Action',
fields=[
('id', models.AutoField(verbo... | ime', models.DateTimeField(null=True)),
('all_day', models.BooleanField(default=False)),
('status', models.CharField(max_length=100)),
('location_name', | models.CharField(max_length=255)),
('location_url', models.CharField(max_length=255, blank=True)),
('source_url', models.CharField(max_length=255)),
('source_note', models.CharField(max_length=255, blank=True)),
],
),
migrations.CreateModel(
... |
FunnyMan3595/mcp_rebuild | settings.py | Python | mit | 2,293 | 0.000436 | #!/usr/bin/env python
# All (current) configuration settings take the form of paths to specific files
# or directories. Aside from BASE itself, all paths are assumed to be relative
# to BASE unless specified as absolute.
# Windows examples:
# BASE = r"C:\MCP"
# USER = r"mcp_rebuild\My Projects"
# TARGET = r"Z:\My Mo... | cygdrive/c/you/get/the/idea). Send in a bug reportif you have
# any problems, the GitHub page is listed in the README.
# Linux examples:
# BASE = r".."
# USER = r"~/mcp_projects"
# TARGET = r" | /var/www/minecraft/bleeding_edge"
# SORUCE_BUNDLE = r".source.tbz2"
#
# This set of configs assumes that rebuild.sh is located in a subdirectory of
# MCP's root. The source bundle is stored as a hidden file in MCP's root,
# projects are read out of the mcp_projects directory in your $HOME, and
# packages are placed di... |
botswana-harvard/tshilo-dikotla | td_maternal/admin/maternal_interim_idcc_admin.py | Python | gpl-2.0 | 772 | 0.002591 | from collections import Order | edDict
from django.contrib import admin
from edc_export.actions import export_as_csv_action
from tshilo_dikotla.base_model_admin import BaseModelAdmin
from ..forms import MaternalInterimIdccForm
from ..models import MaternalInterimIdcc
from .base_maternal_model_admin import BaseMaternalModelAdmin
class MaternalIn... | alInterimIdccForm
radio_fields = {'info_since_lastvisit': admin.VERTICAL,
'value_vl_size': admin.VERTICAL}
list_display = ('report_datetime', 'recent_cd4', 'value_vl',)
list_filter = ('info_since_lastvisit', 'recent_cd4_date', 'value_vl_size', 'recent_vl_date')
admin.site.register(Ma... |
e-koch/VLA_Lband | 14B-088/HI/imaging/sd_regridding/gbt_feather_beamsize.py | Python | mit | 2,146 | 0.002796 |
'''
How much is the feathered image affected by assuming a wrong beam size?
'''
from spectral_cube import SpectralCube
import matplotlib.pyplot as plt
import os
from corner import hist2d
from radio_beam import Beam
import astropy.units as u
from astropy.visualization import hist
from uvcombine.uvcombine import feathe... | ue > 2
vla_beam_kernel = vla_plane.beam.as_tophat_kernel(vla_plane.header["CDELT2"]).array > 0
vla_mask = np.isfinite(vla_plane)
vla_mask = nd.binary_erosion(vla_mask, vla_beam_kernel, iterat | ions=10)
plt.plot([feather_80.real[vla_mask].sum() / gbt_fr_plane[vla_mask].sum().value,
feather_90.real[vla_mask].sum() / gbt_fr_plane[vla_mask].sum().value,
feather_100.real[vla_mask].sum() / gbt_fr_plane[vla_mask].sum().value])
|
plotly/plotly.py | packages/python/plotly/plotly/graph_objs/histogram2d/_legendgrouptitle.py | Python | mit | 4,724 | 0.002117 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Legendgrouptitle(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "histogram2d"
_path_str = "histogram2d.legendgrouptitle"
_valid_props = {"font", "t... | aph_objs.histogram2d.legendgrouptitle.Font`
- A dict | of string/value properties that will be passed
to the Font constructor
Supported dict properties:
color
family
HTML font family - the typeface that will be
applied by the web browser. The web brow... |
samvarankashyap/linch-pin | linchpin/provision/roles/azure/filter_plugins/filter_list_by_attr.py | Python | gpl-3.0 | 275 | 0 | #!/usr/bin/e | nv python
import linchpin.FilterUtils.FilterUti | ls as filter_utils
class FilterModule(object):
''' A filter to filter list by attribute '''
def filters(self):
return {
'filter_list_by_attr': filter_utils.filter_list_by_attr
}
|
braveghz/cobra | tests/test_directory.py | Python | mit | 905 | 0 | # -*- coding: utf-8 -*-
"""
tests.test_directory
~~~~~~~~~~~~~~~~~~~~
Tests pickup.directory
:author: Feei <feei@feei.cn>
:homepage: https://github.com/wufeifei/cobra
:license: MIT, see LICE | NSE for more details.
:copyright: Copyright (c) 2017 Feei. All rights reserved
"""
import os
from cobra.config import project_directory
from | cobra.pickup import Directory
def test_file():
absolute_path = os.path.join(project_directory, 'cobra.py')
files, file_sum, time_consume = Directory(absolute_path).collect_files()
ext, ext_info = files[0]
assert '.py' == ext
assert 1 == ext_info['count']
assert 'cobra.py' in ext_info['list']
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.