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 |
|---|---|---|---|---|---|---|---|---|
gregorynicholas/raven-python | raven/contrib/django/models.py | Python | bsd-3-clause | 7,782 | 0.007325 | """
raven.contrib.django.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Acts as an implicit hook for Django installs.
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from h... | VERS'))
options.setdefault('include_paths', ga('INCLUDE_PATHS', []))
options['include_paths'] = set(options['include_paths']) | get_installed_apps()
options.setdefault('exclude_paths', ga('EXCLUDE_PATHS'))
options.setdefault('timeout', ga('TIMEOUT'))
options.setdefault('name', ga... | code('utf8')).hexdigest()))
options.setdefault('string_max_length', ga('MAX_LENGTH_STRING'))
options.setdefault('list_max_length', ga('MAX_LENGTH_LIST'))
options.setdefault('site', ga('SITE'))
options.setdefault('public_key', ga('PUBLIC_KEY'))
options.setdefault('secret_key', ga(... |
Sensorino/SensorinoServer-legacy | server/database.py | Python | gpl-2.0 | 1,707 | 0.008787 | #!/usr/bin/env python
import sqlite3
import common
class DbCreator:
@staticmethod
def createEmpty(filename=None):
if None == filename:
filename=common.Config.getDbFilename()
print "create db in file :"+filename
conn = sqlite3.connect(filename)
pri... | c = conn.cursor()
c.execute('''DROP TABLE IF EXISTS sensorinos''')
c.execute('''CREATE TABLE sensorinos
| (address TEXT PRIMARY KEY, name TEXT, description TEXT, owner TEXT, location TEXT)''')
c.execute('''DROP TABLE IF EXISTS services''')
c.execute('''CREATE TABLE services
(serviceId INTEGER PRIMARY KEY, name TEXT, saddress TEXT, instanceId INTEGER, state TEXT)''')
... |
vipmike007/tp-qemu | qemu/tests/sr_iov_irqbalance.py | Python | gpl-2.0 | 12,966 | 0.000308 | import re
import time
import logging
from autotest.client.shared import error
from autotest.client.shared import utils
from virttest import utils_test
from virttest import utils_net
# The backports module will take care of using the builtin if available
from virttest.staging.backports import bin
@error.context_awa... | :type service: String
:return: service's status in guest. 'active' or 'inactive'
| :rtype: String
"""
cmd = "service %s status" % service
output = session.cmd_output(cmd)
if re.search("running|active", output, re.I):
status = "active"
elif re.search("stopped|inactive", output, re.I):
status = "inactive"
else:
msg = "Fail to get '%s' service status. "... |
jansel/opentuner | opentuner/search/simulatedannealing.py | Python | mit | 5,936 | 0.001516 | from __future__ import division
import math
import random
from builtins import range
from past.utils import old_div
from opentuner.search import technique
# Default interval steps for cooling schedules
DEFAULT_INTERVAL = 100
# Pseudo-annealing - no relative energy input into acceptance function
class PseudoAnneal... | ue of param, scaled to be in range [0.0, 1.0]
unit_value = param.get_unit_value(state.data)
if unit_value > 0.0:
| # produce new config with param set step_size lower
down_cfg = manipulator.copy(state.data)
param.set_unit_value(down_cfg, max(0.0, unit_value - step_size * random.random()))
down_cfg = driver.get_configuration(down_cfg)
... |
pombredanne/parakeet | parakeet/c_backend/__init__.py | Python | bsd-3-clause | 112 | 0.008929 | from fn_compiler import FnCompiler
from pymodule_compiler import P | yModuleCompiler
from run_function impor | t run
|
shashankg7/pynet | tests/test_net.py | Python | mit | 225 | 0.022222 | import unittest
"" | "
Test for the local and the web html page for table table generation
"""
class TestNET(unittest.TestCase):
def test_net(self):
pass
if __name__ == "__main__":
unittest. | main()
|
hemmerling/codingdojo | src/game_of_life/python_coderetreat_socramob/cr_socramob09/gol01.py | Python | apache-2.0 | 1,168 | 0.008562 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Administrator
#
# Created: 08/10/2011
# Copyright: (c) Administrator 2011
# Licence: <your licence>
#--------------------------------------------------------------------... | ate]):
anzahlNachbarn -= 1
| print "Anzahl Nachbarn", anzahlNachbarn
return anzahlNachbarn
def isNextAlive(self, numberOfNeigbours):
return True
if __name__ == '__main__':
pass |
pnw/env-tracker | main.py | Python | mit | 6,662 | 0.003903 | from pathlib import Path
import click
from git import Repo
from git.exc import InvalidGitRepositoryError
from logger import logger
from config import config
from utils import PairedObject, PairedProject, get_current_project, PathType
@click.group()
@click.option('-v', '--verbose', is_flag=True, help='Enables verbos... | ory')
@click.argument('file', type=PathType(exists=True, file_okay=True, dir_okay=True, allow_dash=False, writable=True,
readable=True, resolve_path=False))
def cmd_unlink(file: Pat | h):
"""
Unlinks a tracked file by reverting the changes made by the `link` command
TODO: add an `--all` option to unlink all objects
"""
## Validate parameters and set defaults
obj_pair = PairedObject.from_path(file)
if not obj_pair.is_linked:
raise click.BadParameter('File is not ... |
wazeerzulfikar/scikit-learn | sklearn/neighbors/lof.py | Python | bsd-3-clause | 12,181 | 0 | # Authors: Nicolas Goix <nicolas.goix@telecom-paristech.fr>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD 3 clause
import numpy as np
from warnings import warn
from scipy.stats import scoreatpercentile
from .base import NeighborsBase
from .base import KNeighborsMixin
from .bas... | orce.
leaf_size : int, optional (default=30)
Leaf size passe | d to :class:`BallTree` or :class:`KDTree`. This can
affect the speed of the construction and query, as well as the memory
required to store the tree. The optimal value depends on the
nature of the problem.
metric : string or callable, default 'minkowski'
metric used for the distance... |
zeinsteinz/tacker | tools/install_venv.py | Python | apache-2.0 | 2,300 | 0 | #!/usr/bin/env python
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 OpenStack Foundation.
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); y... | """
Tacker development environment setup is complete.
Tacker development uses virtualenv to track and manage Python dependencies
while in development and testing.
To activate the Tacker virtualenv for the extent of your current shell
session you can run:
$ source .venv/bin/activate
Or, if you prefer, you ca... | our command>
Also, make test will automatically use the virtualenv.
"""
print(help)
def main(argv):
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
venv = os.path.join(root, '.venv')
pip_requires = os.path.join(root, 'requirements.txt')
test_requires = os.path.join(root, ... |
slivingston/flymovieformat | motmot/FlyMovieFormat/fmf_info.py | Python | bsd-3-clause | 724 | 0.006906 | import sys
import FlyMovieFormat
def main():
try:
filename1 = sys.argv[1]
except | :
| print """Usage: fmf_info fmf_filename
This program takes a set of .fmf files and saves the mean of all
frames from all files as a .bmp image file.
The files used are in the range fmf_filename1 <= FILE <= fmf_filename2.
"""
sys.exit()
fly_movie = FlyMovieFormat.FlyMovie(filename1)
x = fly_movie.g... |
teoreteetik/api-snippets | rest/taskrouter/workflows/list/post/example-1/example-1.6.x.py | Python | mit | 1,581 | 0 | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
import json
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
workspace_sid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
clie... | }]
}
],
'default_filter': {
'queue': everyone_queue_sid
}
}
}
workflow = cli | ent.taskrouter.workspaces(workspace_sid).workflows.create(
friendly_name='Sales, Marketing, Support Workflow',
assignment_callback_url='http://example.com',
fallback_assignment_callback_url='http://example2.com',
task_reservation_timeout='30',
configuration=json.dumps(config)
)
print(workflow.frien... |
swistakm/python-gmaps | tests/test_geocoding.py | Python | bsd-2-clause | 3,380 | 0 | # -*- coding: utf-8 -*-
import pytest
from gmaps import errors
from gmaps import Geocoding
from .testutils import retry
geocoding = Geocoding(sensor=False)
@retry
def test_geocode():
results = geocoding.geocode(u"Wrocław, Hubska")
assert results
assert len(results) > 0
@retry
def test_geocode_override... | assert results1[0]['geometry']['location'] != results2[0]['geometry'][
'location']
@retry
def test_geocode_components_without_address():
"""Test if querying explicitely set components returns same location like
with string address"""
components = {"route": "Łubinowa", "locality": "Wrocław"}
... | in(components.values())
results_with_address = geocoding.geocode(components=components)
results_without_address = geocoding.geocode(address)
assert results_with_address[0]['geometry']['location'] == \
results_without_address[0]['geometry']['location']
@retry
def test_geocode_no_results_exception(... |
VerosK/python-fakturoid | tests/mock.py | Python | mit | 329 | 0.030395 | import os
import json
class FakeResponse(object):
status_code = 200
text = None
headers = []
def __init__(self, text):
self.text = text
def json(s | elf):
return json.loads(self.text)
def response(name):
content = open(os.path.join(os.path.dirname(__file__), 'responses', name)).read()
return FakeResponse(conten | t)
|
mozilla-services/kinto-dist | kinto-remote-settings/tests/signer/test_utils.py | Python | apache-2.0 | 8,911 | 0.001234 | import unittest
import pytest
from kinto_remote_settings.signer import utils
from pyramid.exceptions import ConfigurationError
class ParseResourcesTest(unittest.TestCase):
def test_missing_arrow_raises_an_exception(self):
raw_resources = """
foo bar
"""
with pytest.raises(Configur... | es == {
| "/buckets/stage": {
"source": {"bucket": "stage", "collection": None},
"preview": {"bucket": "preview", "collection": None},
"destination": {"bucket": "prod", "collection": None},
}
}
def test_cannot_mix_per_bucket_and_per_collection(self):
... |
jmdana/memprof | memprof/__init__.py | Python | gpl-3.0 | 835 | 0 | # Copyright (c) 2013 Jose M. Dana
#
# This file is part of memprof.
#
# memprof is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation (version 3 of the License only).
#
# memprof is distributed in the hope that it wi... | r more details.
#
# You should have received a copy of the GNU General Public License
# along with memprof. If not, see <http://www.gnu.org/licenses/>.
from .memprof import *
import pkg_resources
try:
__version__ = pkg_resources | .get_distribution("memprof").version
except pkg_resources.DistributionNotFound:
__version__ = "local"
|
LevinJ/ud730-Deep-Learning | A1_notmnistdataset/logisticsregresstionsmaple.py | Python | gpl-2.0 | 1,313 | 0.00457 | print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
logistic = linear_model.LogisticRegression()
pca = decomposition.PCA()
pipe = Pipeline(steps=[('pca', pca), (... | xplained_variance_')
###############################################################################
# Prediction
n_components = [20, 40, 64]
Cs = np.logspace(-4, 4, 3)
#Parameters of pipelines can be set using '__' separated parameter names:
estimator = GridSearchCV(pipe,
| dict(pca__n_components=n_components,
logistic__C=Cs))
estimator.fit(X_digits, y_digits)
plt.axvline(estimator.best_estimator_.named_steps['pca'].n_components,
linestyle=':', label='n_components chosen')
plt.legend(prop=dict(size=12))
plt.show()
|
jacquelinekay/gsoc-ros-neural | mindwave_driver/src/mindwave_driver/wireless_headset.py | Python | apache-2.0 | 2,166 | 0.006925 | import time
from headset import Headset
from stream import Stream
from common import Version, BytesStatus
class WirelessHeadset(Headset):
"""This class represents the wireless version of the mindwave
Args:
dev: device link
headset: the id of mindwave wireless version
It has the basic f... | bytesize=stream.EIGHTBITS, writeTimeout=0, timeout=3, rtscts=True, xonxoff=False)
# self.stream = serial.Serial(self.device, self.baudrate, timeout=0.001, rtscts=True)
def autoconnect(self):
"""This method autoconnects to the mindwave every."""
self.stream.getStream().write(BytesStat... | lf):
"""This method connects to the mindwave with the id."""
if self.id is not None:
# we send a byte to CONNECTED and other byte in hex of headset id
self.stream.getStream().write(''.join([BytesStatus.CONNECT, self.id.decode('hex')]))
else:
self.autoconnect(... |
XTAv2/Enigma2 | lib/python/Components/Converter/YWeather.py | Python | gpl-2.0 | 22,223 | 0.01242 | # YWeather by 2boom 2013 v.0.6
# xml from http://weather.yahooapis.com/forecastrss
from Components.Converter.Converter import Converter
from Components.Element import cached
from Tools.Directories import fileExists
from Poll import Poll
import time
import os
class YWeather(Poll, Converter, object):
weather_ci... | elif type == "day2":
self.type = self.day2
elif type == "date2":
self.type = self.date2
elif type == "picon2":
self.type = self.picon2
elif type == "text3":
| self.type = self.wtext3
elif type == "templow3":
self.type = self.templow3
elif type == "temphigh3":
self.type = self.temphigh3
elif type == "day3":
self.type = self.day3
eli... |
wittrup/crap | sCRAPing/finn.no/jobb.py | Python | mit | 2,735 | 0.002194 | from urllib.parse import urlparse
import os.path
import requests
from time import sleep
from random import randrange
import glob
import parsers
import time
import csv
import cleaner
AD_URL = 'http://m.finn.no/job/fulltime/ad.html?finnkode='
update = ['sqamlr1dlesu0qiarus6pvzjgh']
listdict = {}
for line in open('list... | key, fname in adsdict.items():
key = int(os.path.basename(fname).split('.')[0])
adparser = parsers.AdParser()
for chunk in open(fname):
adparser.feed(chunk | )
adparser.clean()
jobdict[key] = adparser
print(jobdict)
header = ['id', 'title', 'arbeidsgiver', 'frist', 'tiltredelse', 'varighet', 'sektor', 'sted']
if header is None:
for key, val in jobdict.items():
for sk in val:
if sk not in header:
header.append(sk)
print... |
iluoyi/data-science-coursera | src/assignment3/MapReduce.py | Python | apache-2.0 | 693 | 0.004329 | import json
class MapReduce:
d | ef __init__(self):
self.intermediate = {}
self.result = []
def emit_intermediate(self, key, value):
self.intermediate.setdefault(key, [])
self.intermediate[key].append(value)
def emit(self, value):
self.result.append(value)
def execute(self, data, mapper, reducer)... | termediate[key])
#jenc = json.JSONEncoder(encoding='latin-1')
jenc = json.JSONEncoder()
for item in self.result:
print jenc.encode(item)
|
NateWardawg/godot | modules/enet/config.py | Python | mit | 201 | 0.014925 | def can_build(env, platform):
return True
def configure | (env):
pass
def get_doc_classes():
return [
"NetworkedMultiplayerENet",
| ]
def get_doc_path():
return "doc_classes"
|
IshavanBaar/railaid | app.py | Python | mit | 4,184 | 0.008365 | #!/usr/bin/python
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJ... | ,
'js/bootstrap-datetimepicker.min.js',
'js/slider.js',
'js/amounts.js',
'js/landing.js',
output='js_all.js'
)
)
env.register(
'css_all',
assets.Bundle(
'css/bootstrap.min.css',
'css/bootstrap-datetimepicker.mi | n.css',
'css/slider.css',
'css/landing-page.css',
output='css_all.css'
)
)
# Paypal lib
paypalrestsdk.configure(
mode="sandbox", # sandbox or live
client_id=paypal_client_id,
client_secret= paypal_client_secret
)
@app.route('/')
def index():
return render_template('index.html')
@a... |
weaselkeeper/misc_monitoring_scripts | src/webapp_monitor.py | Python | gpl-2.0 | 5,060 | 0.000791 | #!/usr/bin/env python
###
# Copyright (c) 2013, Jim Richardson <weaselkeeper@gmail.com>
# 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... | ll scala app.
To add more monitors, edit the "monitors" section, it should be pretty self
explanatory. But you may need to grab the metrics page to figure out what the
item you want to monitor is called. With a bit more time, could easily make a
config file to parse for this.
Run this via cron every (n) minutes. E... | you be inundated with a swarm of "all's well" messages.
"""
import smtplib
import sys
import json
import urllib
import logging
logging.basicConfig(level=logging.WARN,
format='%(asctime)s %(levelname)s - %(message)s',
datefmt='%y.%m.%d %H:%M:%S')
console = logging.StreamHandle... |
decebel/dataAtom_alpha | bin/plug/py/external/pattern/web/__init__.py | Python | apache-2.0 | 115,157 | 0.00785 | #### PATTERN | WEB #################################################################################
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
####################################... | urn query
url_decode = urldecode
def proxy(host, protocol="https"):
""" Returns the value for the URL.open() p | roxy parameter.
- host: host address of the proxy server.
"""
return (host, protocol)
class URLError(Exception):
pass # URL contains errors (e.g. a missing t in htp://).
class URLTimeout(URLError):
pass # URL takes to long to load.
class HTTPError(URLError):
pass # URL causes an error on th... |
tejasnikumbh/Algorithms | genericCode/matrixAndGraphUtility/matrixDFS.py | Python | bsd-2-clause | 5,021 | 0.013543 | # Importing standard libraries
import sys
'''
Returns the index of the element in the grid. Element passed in
must have a unique position. If not present returns [-1, -1]. If
multiple occurences present, returns the first one
'''
def findIndex(grid,charElem):
for i in range(len(grid)):
... |
if(grid[i][j] == charElem):
| return [i,j]
return [-1,-1]
'''
Function that generates the valid surrounding indices for a parti
- cular index in a grid The surroundings are just 4 as of now. But
this function can easily be modified by modifying the surrIndices
array.
Returns a list of tuples that are indicative ... |
jalilm/ryu | ryu/ofproto/oxs_fields.py | Python | apache-2.0 | 8,706 | 0.000345 | import struct
from ryu.lib.pack_utils import msg_pack_into
from ryu.lib import type_desc
# enum ofp_oxs_class
OFPXSC_OPENFLOW_BASIC = 0x8002 # Basic stats class for OpenFlow
OFPXSC_EXPERIMENTER = 0xFFFF # Experimenter class
# enum oxs_ofb_stat_fields
OFPXST_OFB_DURATION = 0 # Time flow entry has been alive.
OFPX... | m & 0x3f
td = i.type
add_attr('OFPXST_OFB_' + uk, ofpxst)
add_attr('OXS_OF_' + uk, mod.oxs_tlv_header(ofpxst, td.size))
name_to_field = dict((f.name, f) for f in mod.oxs_types)
num_to_field = | dict((f.num, f) for f in mod.oxs_types)
add_attr('oxs_from_user', functools.partial(_from_user, name_to_field))
add_attr('oxs_from_user_header',
functools.partial(_from_user_header, name_to_field))
add_attr('oxs_to_user', functools.partial(_to_user, num_to_field))
add_attr('oxs_to_user_hea... |
antoinecarme/sklearn2sql_heroku | tests/classification/FourClass_100/ws_FourClass_100_RidgeClassifier_oracle_code_gen.py | Python | bsd-3-clause | 144 | 0.013889 | f | rom s | klearn2sql_heroku.tests.classification import generic as class_gen
class_gen.test_model("RidgeClassifier" , "FourClass_100" , "oracle")
|
hsorby/libcellml | tests/resources/generator/cell_geometry_model/model.py | Python | apache-2.0 | 1,098 | 0.004554 | # The content of this file was generated using the Python profile of libCellML 0.2.0.
from enum import Enum
from math import *
__version__ = "0.3.0"
LIBCELLML_VERSION = "0.2.0"
VARIABLE_COUNT = 4
class VariableType(Enum):
CONSTANT = 1
COMPUTED_CONSTANT = 2
ALGEBRAIC = 3
VARIABLE_INFO = [
{"name"... | me": "vcell", "units": "microlitre", "component": "cell_geometry", "type": VariableType.COMPUTED_CONSTANT},
{"name": "vss", "units": "microlitre", "component": "cell_geometry", "type": VariableType.COMPUTED_CONSTANT}
]
def create_variables_array():
return [nan]*VARIABLE_COUNT
def initialise_variables(variab... | iables[2] = 1000.0*3.14*variables[1]*variables[1]*variables[0]
variables[3] = 0.02*variables[2]
def compute_variables(variables):
pass
|
hmoco/osf.io | api_tests/identifiers/views/test_identifier_detail.py | Python | apache-2.0 | 2,841 | 0.004224 | # -*- coding: utf-8 -*-
from nose.tools import * # flake8: noqa
import urlparse
from api.base.settings.defaults import API_BASE
from website.identifiers.model import Identifier
from tests.base import ApiTestCase
from osf_tests.factories import (
RegistrationFactory,
AuthUserFactory,
IdentifierFactory,
... | rFactory(referent=self.node)
self.node_url = '/{}identifiers/{}/'.format(API_BASE, self.node_identifier._id)
self.registration_res = self.app.get(self.registration_url)
self.registration_data = self.registration_res.json['data']
self.node_res = self.app.get(self.node_url)
self.... | registration_res.status_code, 200)
assert_equal(self.registration_res.content_type, 'application/vnd.api+json')
def test_identifier_detail_success_node(self):
assert_equal(self.node_res.status_code, 200)
assert_equal(self.node_res.content_type, 'application/vnd.api+json')
def test_iden... |
jloloew/AirBridge | parse.py | Python | gpl-3.0 | 3,509 | 0.047307 | import sys, math
from test import goertzel
import wave
import pyaudio
import Queue
import numpy as np
if len(sys.argv) < 2:
print "Usage: %s <filename> " % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
w = wave.open(filename)
fs = w.getframerate()
width = w.getsampwidth()
chunkDuration = .2 #.2 second chunks... | , (1036,1058), (1567,1569), (2082,2104))
chunk_data.append((freqs,results))
data = w.readframes(chunk)
num+=.2
stream.close()
p.terminate()
#finished getting data from chunks, now to parse the data
hi = []
lo = []
mid = []
#average first second of audio to get frequency baselines
for i in range (5):
a = chunk... | range(len(a)):
if a[j] > 1700:
hi.append(b[j])
elif a[j] < 1300:
lo.append(b[j])
else:
mid.append(b[j])
hi_average = sum(hi)/float(len(hi))
lo_average = sum(lo)/float(len(lo))
mid_average = sum(mid)/float(len(mid))
"""
Determine the frequency in each .2 second chunk that has the highest amplitude inc... |
powdahound/ec2instances.info | scripts/package.py | Python | mit | 1,037 | 0 | #!/usr/bin/env python
import pprint
import json
import subprocess
root_dir = subprocess.check_output([
'git', 'rev-parse', '--show-top | level'
]).decode().strip()
def path(s):
return "{}/{}".format(root_dir, s)
# Create the output directory
subprocess.call(['mkdir', '-p', path('ec2instances/info')])
# Make the project a module
subprocess.call(['touch', | path('ec2instances/__init__.py')])
with open(path('ec2instances/info/__init__.py'), 'w') as output:
# Final output will look like the following, though pretty-printed:
#
# ec2 = [{'instance_type': 't2.micro', ...}, ...]
# rds = [{'instance_type': 'db.t2.small', ...}, ...]
#
with open(path('w... |
cooperthompson/ct-com | soccercal/models.py | Python | mit | 3,010 | 0.000997 | from datetime import date
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from urlparse import urlparse
class Organization(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Season(models.Model):
name = models.... | main = domain
http_url = urlparse(domain)
webcal_url = http_url.geturl().replace(http_url.scheme, 'webcal', 1)
return '%s%s.ics' % (webcal_url, self.slug)
class Game( | models.Model):
league = models.ForeignKey(League)
home_team = ChainedForeignKey(Team,
chained_field='league',
chained_model_field='league',
related_name='home_team')
away_team = ChainedForeignKey(Team,
... |
datakortet/dk | tasks.py | Python | lgpl-3.0 | 4,792 | 0.000417 | # -*- coding: utf-8 -*-
"""
Base version of package/tasks.py, created by version 0.3.0 of
package/root/dir> dk-tasklib install
(it should reside in the root directory of your package)
This file defines tasks for the Invoke tool: http://www.pyinvoke.org
Basic usage::
inv -l # list all availabl... | kg.source_less}', ext='.less',
action=lambda e: build(ctx, less=True)
)
watcher.watch_directory(
path='{pkg.source_js}', ext='.jsx',
action=lambda e: build(ctx, js=True)
)
watcher.watch_directory(
path='{pkg.docs}', ext='.rst',
act | ion=lambda e: build(ctx, docs=True)
)
watcher.start()
# individual tasks that can be run from this project
ns = Collection(
build,
watch,
build_js,
lessc,
doctools,
version, upversion,
package,
collectstatic,
publish,
)
ns.configure({
'pkg': Package(),
'run': {
... |
wiso/dask | dask/context.py | Python | bsd-3-clause | 1,121 | 0 | """
Control gl | obal computation context
"""
from coll | ections import defaultdict
_globals = defaultdict(lambda: None)
_globals['callbacks'] = set()
class set_options(object):
""" Set global state within controled context
This lets you specify various global settings in a tightly controlled with
block
Valid keyword arguments currently include:
... |
jayceyxc/hue | apps/oozie/src/oozie/management/commands/oozie_setup.py | Python | apache-2.0 | 7,491 | 0.008944 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | LOG.info(_('Copying examples %(local_dir)s to %(remote_data_dir)s\n') % {
'local_dir': local_dir, 'remote_data_dir': remote_data_dir})
self.fs.do_as_user(self.fs.DEFAULT_USER, self.fs.copyFromLocal, local_dir, remote_data_dir)
# Copy sample data
local_dir = LOCAL_SAMPLE_DATA_DIR.g... | ir)s to %(remote_data_dir)s\n') % {
'local_dir': local_dir, 'remote_data_dir': remote_data_dir})
self.fs.do_as_user(self.fs.DEFAULT_USER, self.fs.copyFromLocal, local_dir, remote_data_dir)
# Load jobs
LOG.info(_("Installing examples..."))
if ENABLE_V2.get():
management.call_comma... |
greendavegreen/vmsareus | vmsareus/vmleases/migrations/0002_vm_branch_name.py | Python | mit | 453 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-19 18:17
from __fu | ture__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmleases', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='vm',
name='branch_name',
field=models.CharF... | ]
|
arrabito/DIRAC | Resources/Catalog/FileCatalogClient.py | Python | gpl-3.0 | 24,012 | 0.009995 | """ The FileCatalogClient is a class representing the client of the DIRAC File Catalog
"""
import os
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.DISET.TransferClient import TransferClient
from DIRAC.Core.Security.ProxyInfo import getVOfromProxyGroup
from DIRAC.ConfigurationSystem.Client.Helpers.Registry import g... | 'OK']:
for lfn in batch:
failed.setdefault(lfn, {})[batch[lfn]['SE']] = res['Message']
continue
for lfn in res['Value']['Failed']:
failed.setdefault(lfn, {})[batch[lfn]['SE']] | = res['Value']['Failed'][lfn]
for lfn in res['Value']['Successful']:
successful.setdefault(lfn, []).append(batch[lfn]['SE'])
return S_OK({'Successful': successful, 'Failed': failed})
@checkCatalogArguments
def listDirectory(self, lfn, verbose=False, timeout=120):
""" List the given director... |
imcleod/oz | oz/RHEL_7.py | Python | lgpl-2.1 | 2,885 | 0.001733 | # Copyright (C) 2013-2017 Chris Lalancette <clalancette@gmail.com>
# Copyright (C) 2013 Ian McLeod <imcleod@redhat.com>
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 2... | "\n"
else:
# RHEL6 dropped this command line directive due to an Anaconda bug
# that has since been fixed. Note that this used to be "method="
# but that has been deprecated for some time.
initrdline += " repo=cdrom:/dev/cdrom"
self._modify_isolinux | (initrdline)
def get_auto_path(self):
"""
Method to create the correct path to the RHEL 7 kickstart file.
"""
return oz.ozutil.generate_full_auto_path("RHEL7.auto")
def get_class(tdl, config, auto, output_disk=None, netdev=None, diskbus=None,
macaddress=None):
"""... |
reinbach/django-machina | machina/apps/forum_conversation/forum_attachments/__init__.py | Python | bsd-3-clause | 148 | 0 | # -*- coding: utf-8 - | *-
default_app_config = 'machina.apps.forum_conversation.forum_attachments.registry_conf | ig.AttachmentsRegistryConfig' # noqa
|
Intuity/Tktr | ticketing/profile/discount.py | Python | gpl-3.0 | 2,266 | 0.005296 | from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from ticketing.macros.baselayout import BaseLayout
from ticketing.models import Ticketing
class Discount(BaseLayout):
@view_config(
route_name="discount",
renderer="templates/discount.pt",
context=Ticket... | _view(self):
discount_code = None
if "submit | " in self.request.POST:
discount_code = (self.request.POST["discount_code"] if "discount_code" in self.request.POST and len(self.request.POST["discount_code"]) > 0 else None)
if discount_code == None:
self.request.session.flash("You must enter a valid discount code before clickin... |
vitalyvolkov/fontbakery | scripts/fix-ttf-ascii-name.py | Python | apache-2.0 | 1,671 | 0 | #!/usr/bin/python
# coding: utf-8
# Copyright 2013 The Font Bakery 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... | fix_name_table(fontfile):
font = ttLib.TTFont(fontfile)
for name_record in font['name'].names:
name_record.string = fix_ascii(name_record.string)
font.save(fontfile)
def show_name_table | (fontfile):
pass
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--autofix', action="store_true",
help="Autofix font ascii name")
parser.add_argument('filename', help="Font file in TTF format")
args = parser.parse_args... |
eedf/jeito | accounting/admin.py | Python | mit | 3,724 | 0.002685 | from django.contrib import admin
from django.db.models import Q
from .models import (Account, Analytic, Entry, BankStatement, Transaction,
ThirdParty, Purchase, Sale, Journal, Year,
Income, Expenditure, Cashing)
class HasScanListFilter(admin.SimpleListFilter):
title = "Ju... | 'opened', )
@admin.register(Journal)
class JournalAdmin(admin.ModelAdmin):
list_display = ('number', 'title')
search_fields = ('=number', 'title')
@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):
list_display = ('number', 'title')
search_fields = ('=number', 'title')
@admin.register(... | , 'title', 'type', 'account', 'client_number', 'iban', 'bic')
search_fields = ('=number', 'title', '=client_number', '=iban', '=bic')
list_filter = ('type', )
ordering = ('number', )
@admin.register(Analytic)
class AnalyticAdmin(admin.ModelAdmin):
list_display = ('number', 'title')
search_fields =... |
FabriceSalvaire/PyValentina | QtShim/__init__.py | Python | gpl-3.0 | 13,118 | 0.002592 | """Minimal Python 3 shim around PyQt5 and Pyside2 Qt bindings for QML applications.
Forked from https://github.com/mottosso/Qt.py under MIT License.
Copyright (c) 2016 Marcus Ottosson
Changes
* Dropped Python2 and Qt4 support
* Focus on last Python 3 release
* Focus on last Qt API : QML
Requirements
* make use of ... |
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except Im... | QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type('QtCompat', (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
... |
balazssimon/ml-playground | udemy/lazyprogrammer/numpy-stack/scipy_test.py | Python | apache-2.0 | 1,730 | 0.009249 | import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.stats import multivariate_normal as mvn
norm.pdf(0)
# mean: loc, stddev: scale
norm.pdf(0, loc=5, scale=10)
r = np.random.randn(10)
# probability distribution function:
norm.pdf(r)
# log probability:
norm.log... | ')
plt.show()
# non-axis-aligned Gaussian:
cov = np.array([[1,0.8],[0.8,3]]) # covariant matrix, covariance: 0.8 in both dimensions
mu = np.array([0,2])
r = mvn.rvs(mean=mu, cov=cov, size=1000)
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()
r = np.random.multivariate_normal(mean=mu, cov=cov, size... | loading WAV files: scipy.io.wavfile.read (default sampling: 44100 Hz)
# saving WAV files: scipy.io.wavfile.write
# signal processing, filtering: scipy.signal
# convolution: scipy.signal.convolve, scipy.signal.convolve2d
# FFT is in numpy:
x = np.linspace(0, 100, 10000)
y = np.sin(x) + np.sin(3*x) + np.sin(5*x... |
raycarnes/erppeek | erppeek.py | Python | bsd-3-clause | 64,722 | 0.000201 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" erppeek.py -- Odoo / OpenERP client library and command line tool
Author: Florent Xicluna
(derived from a script by Alan Bell)
"""
import _ast
import atexit
import collections
import csv
import functools
import optparse
import os
from pprint import pprint
import re
imp... | e of this field
rec.read(fields=None) # Return values for the fields
client.login(user) # Login with another user
client.connect(env) | # Connect to another env.
client.modules(name) # List modules matching pattern
client.upgrade(module1, module2, ...)
# Upgrade the modules
"""
STABLE_STATES = ('uninstallable', 'uninstalled', 'installed')
DOMAIN_OPERATORS = frozenset('!|&')
# Supported operator... |
fosslabs/django-qna | src/qna/urls.py | Python | bsd-3-clause | 536 | 0.001866 | from django.conf.urls.defaults import patterns
from qna import views
from qna.models import Question
from voting.views import xmlhttprequest_vote_on_object
urlpatterns = patterns('',
(r'^question/ask/$', views.ask),
(r'^question/(\d+)/$', views.question),
(r'^question/(\d+)/answer/ | $', views. | answer),
(r'^question/comment/(\d+)/$', views.comment),
(r'^question/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/$',
xmlhttprequest_vote_on_object, dict(model=Question)),
(r'^$', views.question_list),
)
|
timrchavez/capomastro | jenkins/migrations/0001_initial.py | Python | mit | 7,143 | 0.00756 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'JenkinsServer'
db.create_table(u'jenkins_jenkinsserver', ... | 'url': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'jenkins.build': {
'Meta': {'ordering': "['-number']", 'object_name': 'Build'},
'build_ | id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'console_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'duration': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField',... |
ElenorFrisbee/MSC | regmod/pcaPython/np2geotiff.py | Python | mit | 1,652 | 0.020581 | ### write numpy array as geoitiff to disk
import sys
import numpy as np
# append path for osgeo gdal to resolve "No module named _gdal_array" conflict
sys.path.insert(0, '/home/manuel/regmod/postgis-cb-env/lib/python2.7/site-packages/')
from osgeo.gdalconst import *
def numpy2geotiff(numpyArr, lat, lon):
# modifie... | = np.shape(array)
xres = (xmax-xmin)/float(ncols)
yres = (ymax-ymin)/float(nrows)
geotransform=( | xmin,xres,0,ymax,0, -yres)
# That's (top left x, w-e pixel resolution, rotation (0 if North is up),
# top left y, rotation (0 if North is up), n-s pixel resolution)
output_raster = gdal.GetDriverByName('GTiff').Create('/var/shiny-server/www/datacollectorv2/www/genmaps/temp.tif',ncols, nrows... |
utkbansal/tardis | tardis/plasma/exceptions.py | Python | bsd-3-clause | 632 | 0.011076 | class PlasmaException(Exception):
pass
class Incomplete | AtomicData(PlasmaException):
def __init__(self, atomic_data_name):
message = ('The current plasma calculation requires {0}, '
'which is not provided by the given atomic data'.format(
atomic_data_name))
super(PlasmaException, self).__init__(message)
class PlasmaMissin... | Module(PlasmaException):
pass
class NotInitializedModule(PlasmaException):
pass
class PlasmaIonizationError(PlasmaException):
pass
class PlasmaConfigError(PlasmaException):
pass |
boogiekodi/script.module.livelib | lib/scrapers/jw.py | Python | gpl-2.0 | 894 | 0.059284 | import boogietools as bt
import re
import urllib
import urlparse
encoding="utf-8"
def run(id,ref):
type="rtmp"
#provides: http://www.hdmyt.info, http://www.playerhd(n).pw
r_pageurl="http://content.jwplatform.com/players/%s.html"%id
jsurl="http://content.jwplatform.com/players/%s.js"%id
#loop through endless doma... | YNEWS//"
values["playpath"]=r_playpath
values["pageUrl"]=r_pageurl
values["swfUrl"]=r_swfurl
values["flashver"]="WIN 19,0,0,185"
values["live"]="true"
return type | ,values |
John-Hart/autorest | src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/operations/explicit.py | Python | mit | 39,961 | 0.001051 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | s the direct response alongside the
deserialized response
| :param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/reqopt/optional/integer/parameter'
... |
CELMA-project/CELMA | celma/pickleTweaks/neutralScan/neutralField1D.py | Python | lgpl-3.0 | 6,252 | 0.019994 | #!/usr/bin/env python
"""
Tweak of profile plots as a function of nn.
"""
import pickle
import matplotlib.pylab as plt
import matplotlib.lines as mlines
import numpy as np
from subprocess import Popen
import os, sys
# If we add to sys.path, then it must be an absolute path
commonDir = os.path.abspath("./../../../com... | fontsize by 1 to get some spacing
sD[scans[0] | ][key]["ax"].set_ylabel(labels[0], fontsize=11)
# Manually ajust the wspace as fig.subplots_adjust messes with the
# spacing
for key in ("phi", "om", "sA"):
pos = sD[scans[0]][key]["ax"].get_position()
pos = (pos.x0 + 0.05, pos.y0, pos.width, pos.height)
sD[scans[0]][key]["ax"].set_... |
PanDAWMS/panda-server | pandaserver/workflow/pcwl_test.py | Python | apache-2.0 | 5,846 | 0.005474 | from ruamel import yaml
import logging
import sys
from pandaserver.workflow.workflow_utils import get_node_id_map, dump_nodes, set_workflow_outputs, \
convert_nodes_to_workflow
from pandaserver.workflow.pcwl_utils import parse_workflow_file, resolve_nodes
logging.basicConfig(format='%(asctime)s - %(levelname)s - ... | "--useCMake --cmtConfig x86_64-slc6-gcc49-opt "}],
"prodSourceLabel": "user",
"processingType": "panda-client-1.4.81-je | di-run",
"architecture": "x86_64-slc6-gcc49-opt@centos7"}
c_template = {"sourceURL": "https://aipanda048.cern.ch:25443",
"cliParams": "prun --cwl test.cwl --yaml a.yaml "
"--relayHost aipanda059.cern.ch --outDS "
"user.tmaeno.1f2860f0-30d... |
i3visio/osrframework | osrframework/domains/other_subdomains.py | Python | agpl-3.0 | 17,273 | 0.002084 | # !/usr/bin/python
# -*- coding: utf-8 -*-
#
##################################################################################
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ... | he hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. ... | ee <http://www.gnu.org/licenses/>.
#
##################################################################################
tld = {
".h4ck.me",
# A sample from: https://freedns.afraid.org/domain/registry/
".0x.no",
".100mountain.com",
".10x.es",
".120v.ac",
".1337.cx",
".150watt.ru",
".... |
daspecster/google-cloud-python | scripts/verify_included_modules.py | Python | apache-2.0 | 6,329 | 0 | # Copyright 2016 Google 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions ... | mport argparse
import os
import sys
import warnings
from sphinx.ext.intersphinx import fetch_inventory
from script_utils import PROJECT_ROOT
DOCS_DIR = os.path.join(PROJECT_ROOT, 'docs')
IGNORED_PREFIXES = ('test_', '_')
IGNORED_MODULES = frozenset([
'google.cloud',
'google.cloud.bigquery',
'google.clou... |
repalov/megad-mqtt-gw | setup.py | Python | apache-2.0 | 1,025 | 0.002927 | from distutils.core import setup
setup(
name='megad-mqtt-gw',
version='0.3',
description='Gateway between MQTT queue and MegaD devices (http://ab-log.ru)',
author='rs',
author_email='repalov@gmail.com',
url='https://github.com/repalov/megad-mqtt-gw',
license='Apache License',
classifier... | ming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: System :: Networking',
'License :: OSI Approved :: Apache Software License',
],
packages=['megad'],
install_requires=['aiohttp>=3.4.4', 'paho-mqtt>=1.4',... | ['megad-mqtt-gw.homeassistant.conf', 'megad-mqtt-gw.wirenboard.conf']),
('/lib/systemd/system', ['megad-mqtt-gw.service'])
],
entry_points={'console_scripts': ['megad-mqtt-gw=megad.megad_mqtt_gw:main']}
)
|
FinalHashLLC/Barnacoin | contrib/devtools/update-translations.py | Python | mit | 6,783 | 0.006487 | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... | invalid
translation_node.clear()
translation_node.set('type', 'unfinished')
have_errors = True
# Remove location tags
for location in message.findall('location'):
message.remove(location)
... | ntire message if it is an unfinished translation
if translation_node.get('type') == 'unfinished':
context.remove(message)
# write fixed-up tree
# if diff reduction requested, replace some XML to 'sanitize' to qt formatting
if reduce_diff_hacks:
ou... |
ancho85/pylint-playero-plugin | corepy/embedded/Field.py | Python | gpl-2.0 | 1,010 | 0.006931 | from Embedded_OpenOrange import Embedded_Field
#from core.database.Database import Database
from decimal import Decimal
class Field(Embedded_Field):
def __init__(self, record, fieldname_or_fielddef):
Embedded_Field.__init__(self, record, fieldname_or_fielddef)
def setValue(self, v):
if isinst... | d.setValue(self, v)
def getSQLValue(self):
return None
#return Database.getCurrentDB().parseFieldValue(self, False)
def getPythonSQLValue(self):
return None
#return Database.getCurrentDB().parsePythonFieldValue(self)
def getAsString(self): pass
def getDecimals(self): ... | def getType(self): pass
def getValue(self): pass
def isNone(self): pass
def isPersistent(self): pass
def setDecimals(self): pass
def setFromString(self): pass
|
detiber/lib_openshift | test/test_v1_user.py | Python | apache-2.0 | 1,212 | 0.0033 | # coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
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
... | ted 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.
"""
from __future__ import absolute_import
import os
import sys
import unittest
import lib_openshift
from lib_openshift.rest import ApiException
from lib_openshift.models.v1_user import V1User
class TestV1User(unittest.TestCase):
""" V1User unit test stubs """
def setUp(self):
... |
calispac/digicampipe | digicampipe/scripts/rate_scan.py | Python | gpl-3.0 | 4,980 | 0.000201 | """
Make a "Bias Curve" or perform a "Rate-scan",
i.e. measure the trigger rate as a function of threshold.
Usage:
digicam-rate-scan [options] [--] <INPUT>...
Options:
--display Display the plots
--compute Computes the trigger rate vs threshold
-o OUTPUT --output=OUTPUT. F... | containers import CameraEventType
def compute(files, output_filename, thresholds, n_samples=1024):
|
thresholds = thresholds.astype(float)
data_stream = event_stream(files)
# data_stream = trigger.fill_event_type(data_stream, flag=8)
data_stream = filters.filter_event_types(data_stream,
flags=CameraEventType.INTERNAL)
data_stream = baseline.fill_baseli... |
btrent/knave | pychess/ic/block_codes.py | Python | gpl-3.0 | 4,351 | 0.000689 | # -*- coding: utf-8 -*-
"""
Internal command codes used in FICS block mode
(see "help block_codes" and "help iv_block").
Used mostly by internal library functions.
BLOCK_ variables are message boundary markers.
BLKCMD_ variables are command codes.
"""
BLOCK_START = chr(21) # \U
BLOCK_SEPARATOR = chr(22) #... | 119
BLKCMD_SIMOPEN = 120
BLKCMD_SIMPASS = 121
BLKCMD_SIMPREV = 122
BLKCMD_SMOVES = 123
BLKCMD_SMPOSITION = 124
BLKCMD_SPOSITION = 125
BLKCMD_STATISTICS = 126
BLKCMD_STORED = 127
BLKCMD_STYLE = 128
BLKCMD_SWITCH = 130
BLKCMD_TAKEBACK = 131
BLKCMD_TELL = 132
BLKCMD_TIME = 133
BLKCMD_TOMOVE = 134
BLKCMD_TOURNSET = 135
BLK... | = 136
BLKCMD_UNEXAMINE = 137
BLKCMD_UNOBSERVE = 138
BLKCMD_UNPAUSE = 139
BLKCMD_UPTIME = 140
BLKCMD_USCF = 141
BLKCMD_USTAT = 142
BLKCMD_VARIABLES = 143
BLKCMD_WHENSHUT = 144
BLKCMD_WHISPER = 145
BLKCMD_WHO = 146
BLKCMD_WITHDRAW = 147
BLKCMD_WNAME = 148
BLKCMD_XKIBITZ = 149
BLKCMD_XTELL = 150
BLKCMD_XWHISPER = 151
BLKC... |
mekolat/manachat | actor.py | Python | gpl-2.0 | 745 | 0 | import net.mapserv as mapserv
from net.common import distance
def find_nearest_being(nam | e='', type='', ignored_ids=[], allowed_jobs=[]):
if mapserv.beings_cache is None:
return None
min_disance = 1000000
px = mapserv.player_pos['x']
py = mapserv.player_pos['y']
nearest = None
for b in mapserv.beings_cache.values():
if b.id in ignored_ids:
continue
... | if allowed_jobs and b.job not in allowed_jobs:
continue
dist = distance(px, py, b.x, b.y)
if dist < min_disance:
min_disance = dist
nearest = b
return nearest
|
YuxuanLing/trunk | trunk/code/study/python/Fluent-Python-example-code/attic/strings-bytes/charfinder.py | Python | gpl-3.0 | 555 | 0 | #!/usr/bin/env python
from unicodedata import name
import sys
if len(sys.argv) > 1:
query = sys.argv[1:]
else:
query = input('search words: ').split()
query = [s.upper() for s in query]
count = 0
for i in range(20, sys.maxunicode):
car = chr(i)
descr = name(car, None)
if descr i | s None:
continue
words = descr.split()
if | all(word in words for word in query):
print('{i:5d} {i:04x} {car:^5} {descr}'.format(**locals()))
count += 1
print('{0} character(s) found'.format(count))
|
koyadovic/Dia | predictive/systems/statistical/analysis/bundles/parameters.py | Python | gpl-2.0 | 592 | 0.01692 | # -*- coding: utf-8 -*-
from ...analysis.parameters.glucose_dose import GlucoseGramsDose
from ...analysis.parameters.carb_dose import CarbsDoses
class Param | etersGathering(object):
"""
Recopila objetos que extraen parámetros
"""
def __init__(self, context, basic_gathering):
pass
#self._c = context
#self.
#self.carbs_and_doses = CarbsDoses(context, start_dt, end_dt, cf, meal)
#self.glucose_and_doses = GlucoseG... | (carbs_doses, body_traits)
@property
def context(self):
return self._c |
catmaid/CATMAID | django/applications/catmaid/management/commands/catmaid_update_project_configuration.py | Python | gpl-3.0 | 1,566 | 0.006386 | # -*- coding: utf-8 -*-
import logging
logger = logging.getLogger(__name__)
from django.core.management.base import BaseCommand, CommandError
from catmaid.models import Project, User
from catmaid.control.project import validate_project_setup
from catmaid.apps import get_system_user
from .common import set_log_level
... | 'user_id'])
if options['project_id'] is None:
projects = Project.objects.all()
else:
projects = Project.objects.filter(pk=options['projects_id'])
for p in projects:
try:
validate_project_setup(p.id, user.id, True)
logger.i | nfo(f"Validated project {p} (ID: {p.id})")
except Exception as e:
logger.error("Could not validate project setup of project " + \
f"{p} (ID: {p.id}): {e}")
|
mesosphere/dcos-commons | frameworks/helloworld/tests/test_seccomp.py | Python | apache-2.0 | 2,135 | 0.001405 | import logging
import pytest
import json
import sdk_install
import sdk_agents
import sdk_cmd
import sdk_plan
import sdk_marathon
from tests import config
log = logging.getLogger(__name__)
SECCOMP_DIR = "/opt/mesosphere/etc/dcos/mesos/seccomp/test_profile.json"
custom_profile = {
"defaultAction": "SCMP_ACT_ALLOW... | uninstall(config.PACKAGE_NAME, config.SERVICE_NAME)
options = {
"service": {
"yaml": "seccomp"
},
"hello": {
| "seccomp-profile-name": "default.json"
}
}
sdk_install.install(config.PACKAGE_NAME, config.SERVICE_NAME, expected_running_tasks=1 , additional_options=options)
yield # let the test session execute
finally:
sdk_install.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME)... |
kubeflow/pipelines | sdk/python/kfp/deprecated/dsl/metrics_utils.py | Python | apache-2.0 | 6,121 | 0.002777 | # Copyright 2021 The Kubeflow 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 applicable law or agreed to in... | ase):
"""Metrics class representing a Confidence Metrics."""
# Initialization flag to support setattr / getattr behavior.
_initialized = False
def __getattr__(self, name: str) -> Any:
"""Custom __getattr__ to allow access to metrics schema fields."""
if name not in self._metric_fields... | ield: {} in metrics.'.format(name))
return self._values[name]
def __setattr__(self, name: str, value: Any):
"""Custom __setattr__ to allow access to metrics schema fields."""
if not self._initialized:
object.__setattr__(self, name, value)
return
if name no... |
sentient-energy/emsw-bitbake-mirror | lib/bb/persist_data.py | Python | gpl-2.0 | 6,609 | 0.000454 | """BitBake Persistent Data Store
Used to store data in a central location such that other threads/tasks can
access them at some future date. Acts as a convenience wrapper around sqlite,
currently, providing a key/value store accessed by 'domain'.
"""
# Copyright (C) 2007 Richard Purdie
# Copyright (C) 2010 ... | rom pysqlite2 import dbapi2 as sqlite3
sqlversion = sqlite3.sqlite_version_info
if sqlversion[0] < 3 or (sqlversion[0] == 3 and sqlversion[1] < 3):
raise Exception("sqlite3 version 3.3.0 or later is required.")
logger = logging.getLogger("BitBake.PersistData")
if hasattr(sqlite3, 'enable_shared_cache'):
try:... | _cache(True)
except sqlite3.OperationalError:
pass
@total_ordering
class SQLTable(collections.MutableMapping):
"""Object representing a table/domain in the database"""
def __init__(self, cachefile, table):
self.cachefile = cachefile
self.table = table
self.cursor = connect(... |
qedsoftware/commcare-hq | corehq/ex-submodules/pillowtop/processors/sample.py | Python | bsd-3-clause | 1,108 | 0 | from pillowtop.logger import pillow_logging
from pillowtop.processors.interface import PillowProcessor
class NoopProcessor(PillowProcessor):
"""
Processor that does absolutely nothing.
"""
def process_change(self, pillow_instance, change):
pass
class LoggingProcessor(PillowProcessor):
"... | ssor that just logs things - useful in tests or debugging.
"""
def __init__(self, logger=None):
self.logger = logger or pillow_logging
def process_change(self, pillow_instance, change):
self.logger.info(change)
class CountingProcessor(PillowProcessor):
"""
Processor that jus | t counts how many things it has processed
"""
def __init__(self):
self.count = 0
def process_change(self, pillow_instance, change):
self.count += 1
class TestProcessor(PillowProcessor):
"""
Processor that just keeps the change in an in-memory list for testing
"""
def __i... |
hep-cce/hpc-edge-service | argo/urls.py | Python | bsd-3-clause | 349 | 0.022923 | from django.conf.urls import url
impo | rt logg | ing
logger = logging.getLogger(__name__)
from argo import views
local_urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^filter/$',views.filter,name='filter'),
url(r'^job_display/(?P<job_num>\w+)/$',views.job_display,name='job_display'),
]
urlpatterns = local_urlpatterns
|
plepe/pgmapcss | pgmapcss/eval/eval_range.py | Python | agpl-3.0 | 907 | 0.002205 | class config_eval_range(config_base):
mutable = 3
def eval_range(param):
if len(param) < 2:
return ''
step = 1.0
if len(param) > 2:
try:
step = float(param[2])
except ValueError:
return ''
try:
start = float(param[0])
except ValueError:
... | urn ''
try:
stop = float(param[1])
except ValueError:
return ''
l = []
if step > 0:
while start <= stop: |
l.append(float_to_str(start))
start += step
elif step < 0:
while start >= stop:
l.append(float_to_str(start))
start += step
else:
return ''
return ';'.join(l)
# TESTS
# IN ['1', '3']
# OUT '1;2;3'
# IN ['1', '5', '2']
# OUT '1;3;5'
# IN ['... |
eric-stanley/robotframework | src/robot/result/merger.py | Python | apache-2.0 | 2,998 | 0 | # Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 l... | % (self.root.name, name))
def _find(self, items, name):
for item in items:
| if item.name == name:
return item
raise IndexError
def end_suite(self, suite):
self.current = self.current.parent
def visit_test(self, test):
try:
old = self._find(self.current.tests, test.name)
except IndexError:
test.message = se... |
Traecp/pyFit28 | pyFit28/extract_spec_dialog.py | Python | gpl-3.0 | 6,370 | 0.013344 | #!/usr/bin/python
# -*- coding: utf-8 -*-
######################################################################################################
# GUI for inelastic spectra fitting
# Thanh-Tra NGUYEN for the European Synchrotron Radiation Facility - ID28
# thanhtra0104@gmail.com
#######################################... | artial_done(self, frac):
self.progressBar.setValue(frac)
@QtCore.pyqtSlot()
def warning(self, txt):
self.label_Done.setText("<html><head/><body><p><span style=' font-size:12pt; color:#ff0000;'>%s</span></p></body></html>"%txt)
@QtCore.pyqtSlot()
def done(self):
... | setText("<html><head/><body><p><span style=' font-size:12pt; color:#ff0000;'>HDF5 file written. Normal end.</span></p></body></html>")
|
tnalpgge/electionfraud | python/electionfraud/countmethod/mrx.py | Python | artistic-2.0 | 2,363 | 0.000423 | # -*- python -*-
import electionfraud.countmethod.abc as efcmabc
import electionfraud.countmethod.exception as efcmx
import electionfraud.countmethod.fptp as fptp
class MultiRoundExhaustible(efcmabc.AbstractCountMethod):
"""
A base class for implementing counting methods that could possibly
span multiple ... | nt(len(non_exhausted_votes) / 2)
first_choices = [[x[0]] for x in responses if len(x)]
counter = fptp.FirstPastThePost()
counter.count(first_choices)
return (counter, half)
def are_we_there_yet(self):
if self.results is None:
raise efcmx.IncompleteCount()
de... | ader(self):
self.are_we_there_yet()
return self.results.leader()
def trailer(self):
self.are_we_there_yet()
return self.results.trailer()
|
Joy-El/metagene_analysis | test_Read.py | Python | mit | 9,434 | 0.004134 | #!/usr/bin/python
"""test_Read.py to test the Read class.
Requires:
python 2 (https://www.python.org/downloads/)
nose 1.3 (https://nose.readthedocs.org/en/latest/)
Joy-El R.B. Talbot Copyright (c) 2014
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this... | se_input, test, bad_bitwise_flag[test])
@raises(MetageneError)
def check_catch_bad_bitwise_input(test, (values, expected)):
print Read.parse_sam_bitwise_flag(*values)
def build_samline(bitcode, chromosome, start, cigar, length, abundance, mappings):
"""Return a SAM format line"""
string = "a" * length
... | cigar,
string,
string,
mappings,
abundance)
def test_create_read():
for test in good_input:
yield (check_create_read, test, good_input[test])
def check_create_read(test, values):
# create expected result
if int(values[0]) == 4:
expected = "Non-alignin... |
HermasT/flask-admin | flask_admin/tests/test_model.py | Python | bsd-3-clause | 19,143 | 0.000679 | import wtforms
from nose.tools import eq_, ok_
from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.test import Client
from wtforms import fields
from flask_admin import Admin, form
from flask_admin._compat import iteritems, itervalues
from flask_admin.model import base, filters
fro... | rs(self, name):
return [SimpleFilter(name)]
def scaffold_sortable_columns(self):
return ['col1', 'col2', 'col3']
def scaffold_form(self):
return Form
# Data
def get_list(self, page, sort_field, sort_desc, search, filters,
page_size | =None):
self.search_arguments.append((page, sort_field, sort_desc, search, filters))
return len(self.all_models), itervalues(self.all_models)
def get_one(self, id):
return self.all_models.get(int(id))
def create_model(self, form):
model = Model(self.last_id)
self.last_i... |
sehe/Lilypond | python/lilylib.py | Python | gpl-3.0 | 9,740 | 0.016119 | # This file is part of LilyPond, the GNU music typesetter.
#
# Copyright (C) 1998--2012 Han-Wen Nienhuys <hanwen@xs4all.nl>
# Jan Nieuwenhuizen <janneke@gnu.org>
#
# LilyPond is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# t... | TNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
impor | t __main__
import glob
import os
import re
import shutil
import sys
import optparse
import time
################################################################
# Users of python modules should include this snippet
# and customize variables below.
# Python 2.5 only accepts strings with proper Python internal encodin... |
jonathansick/pySPS | demo/snapshot_test.py | Python | bsd-3-clause | 10,519 | 0.010077 | #!/usr/bin/env python
# encoding: utf-8
"""
Tests the iso-age library
History
-------
2011-10-02 - Created by Jonathan Sick
"""
__all__ = ['']
import os
import tables
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import snapshotlib
from fspsq import Param... | ge=age)
def define_samples(self, n=50000):
"""Define the set of models."""
for i in xrange(n):
pset = ParameterSet(None, # automatically create a name
sfh=1,
imf_type=1, # Chabrier 2003
| dust_type=2, # Calzetti 2000 attenuation curve
zmet=int(self._sample_zmet()),
tau=float(self._sample_tau()),
const=float(self._sample_const()),
sf_start=float(self._sample_sf_start()),
fburst=float(self._sample_fburst()),
... |
LedaLima/incubator-spot | spot-oa/api/resources/proxy.py | Python | apache-2.0 | 17,096 | 0.022637 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | row[0],row[18],score)
| fb_data.append([row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7] \
,row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15] \
,row[16],row[17],row[18],row[19],score,row[20],row[21],row[22], \
row[23],hash_field])
insert_command += "{0}{1}".format("," if not first else "", threat_data)
... |
Cadovvl/test_push | test.py | Python | gpl-3.0 | 488 | 0.018443 | class Base:
def get_postfix(self):
return " base postfix"
def get_fu | ll_str(self):
return "Base prefix " + self.get_postfix()
class Derived(Base):
def print_string(self):
print self.get_full_str()
class PlymorphicDerived(Base):
# polimorphism is here
def get_postfix(self):
return " polymorphically changed postfix"
def print_string(self):
print self.get... | int_string()
|
qedsoftware/commcare-hq | corehq/apps/userreports/util.py | Python | bsd-3-clause | 5,418 | 0.00203 | import collections
import hashlib
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from corehq.util.soft_assert import soft_assert
from corehq import privileges, toggles
from corehq.apps.hqwebapp.templatetags.hq_shared_tags import toggle_enabled
from corehq.apps.userreports.con... | value
def default_language():
return "en"
def has_report_builder_add_on_privilege(request):
return any(
has_privilege(request, p) for p in privileges.REPORT_BUILDER_ADD_ON_PRIVS
)
def has_report_builder_access(request):
builder_enabled = toggle_enabled(request, toggles.REPORT_BUILDER)
... | y_builder_priv = has_privilege(request, privileges.REPORT_BUILDER)
beta_group_enabled = toggle_enabled(request, toggles.REPORT_BUILDER_BETA_GROUP)
has_add_on_priv = has_report_builder_add_on_privilege(request)
return (builder_enabled and legacy_builder_priv) or beta_group_enabled or has_add_on_priv
def a... |
ollyc/kajiki | speedtest.py | Python | mit | 1,552 | 0.000644 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from collections import defaultdict
import time
from contextlib import contextmanager
from kajiki import XMLTemplate
from genshi.template import MarkupTemplate
FN =... | ['compile.genshi'] / timings['compile.kajiki']))
print('Render 100 kajiki speedup: %s' % (
timings['render.100.genshi'] / timings['render.100.kajiki']))
print('Rend | er 500 kajiki speedup: %s' % (
timings['render.500.genshi'] / timings['render.500.kajiki']))
|
rezoo/chainer | chainer/reporter.py | Python | mit | 13,600 | 0 | import collections
import contextlib
import copy
import json
import warnings
import numpy
import six
from chainer.backends import cuda
from chainer import configuration
from chainer import serializer as serializer_module
from chainer import variable
def _copy_variable(value):
if isinstance(value, variable.Varia... |
def add_observers(self, prefix, observers):
"""Registers multiple observers at once.
This is a convenient method to register multiple objects at once.
Args:
prefix (str): Prefix of each name of observers.
observers: Iterator of name and observer pairs.
"""... | for name, observer in observers:
self._observer_names[id(observer)] = prefix + name
def report(self, values, observer=None):
"""Reports observed values.
The values are written with the key, prefixed by the name of the
observer object if given.
.. note::
As o... |
puttarajubr/commcare-hq | corehq/apps/groups/tests/__init__.py | Python | bsd-3-clause | 27 | 0 | f | rom .test_ | groups import *
|
jakespringer/lostexhaust-v2 | api/lostexhaust/util.py | Python | lgpl-3.0 | 1,265 | 0.006324 | import math, M2Crypto, base64
from lostexhaust.models.carpool import Carpool
from lostexhaust.models.household import Household
def geo_distance(latitude, longitude, other_latitude, other_longitude):
| lat = math.radians(latitude)
lon = math.radians(longitude)
lat2 = math.radians(other_latitude)
lon2 = math.radians(other_longitude)
deltaLat = lat2 - lat
deltaLon = lon2 - lon
sinPart = (math.sin(deltaLat / 2.0))
cosPart = (math.cos(lat) * math.cos(lat2) * math.sin(deltaLon / 2.0))
angl... | _households):
return sorted([Carpool(origin.household_id, o.household_id, geo_distance(origin.latitude, origin.longitude, o.latitude, o.longitude)).__dict__ for o in other_households], key=lambda e: e["distance"])
def m2crypto_load_der(filename):
TEMPLATE = """
-----BEGIN RSA PUBLIC KEY-----
%s
-----END RSA PU... |
redhat-cip/dci-control-server | dci/alembic/versions/19dd8a44afdf_add_fingerprint_table.py | Python | apache-2.0 | 2,476 | 0.003231 | #
# Copyright (C) 2017 Red Hat, 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 writin... | me.datetime.utcnow,
nullable=False,
),
sa.Column(
" | etag",
sa.String(40),
nullable=False,
default=utils.gen_etag,
onupdate=utils.gen_etag,
),
sa.Column(
"topic_id",
pg.UUID(as_uuid=True),
sa.ForeignKey("topics.id", ondelete="CASCADE"),
nullable=False,
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/mpmath/functions/zeta.py | Python | agpl-3.0 | 35,983 | 0.007309 | from ..libmp.backend import xrange
from .functions import defun, defun_wrapped, defun_static
@defun
def stieltjes(ctx, n, a=1):
n = ctx.convert(n)
a = ctx.convert(a)
if n < 0:
return ctx.bad_domain("Stieltjes constants defined for n >= 0")
if hasattr(ctx, "stieltjes_cache"):
stieltjes_c... | == ctx.inf or t == ctx.ninf):
if d < 2:
if t == ctx.ninf and d == 0:
return ctx.ninf
return ctx.inf
else:
return ctx.zero
if d == 0:
if ctx._im(t):
# XXX: cancellation occurs
a = ctx.loggamma(0.25+0.5j*t)
... | else:
if ctx.isinf(t):
return t
return ctx._im(ctx.loggamma(0.25+0.5j*t)) - ctx.ln(ctx.pi)/2*t
if d > 0:
a = (-0.5j)**(d-1)*ctx.polygamma(d-1, 0.25-0.5j*t)
b = (0.5j)**(d-1)*ctx.polygamma(d-1, 0.25+0.5j*t)
if ctx._im(t):
if d == 1:
... |
wpjesus/codematch | ietf/nomcom/migrations/0005_remove_position_incumbent.py | Python | bsd-3-clause | 348 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nomcom', '0004_auto_20151027_0829'),
]
operations = [
migrat | ions.RemoveFiel | d(
model_name='position',
name='incumbent',
),
]
|
Azure/azure-sdk-for-python | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/aio/operations/_api_tag_description_operations.py | Python | mit | 19,783 | 0.005156 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | cItemPaged(
get_next, extract_data
)
list_by_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/tagDescriptions'} # type: ignore
@distributed_trace_async
async def get_entit... | y
) -> bool:
"""Gets the entity state version of the tag specified by its identifier.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:para... |
meteoswiss-mdr/precipattractor | pyscripts/growth_errors_nans.py | Python | gpl-3.0 | 39,057 | 0.012443 | #!/usr/bin/env python
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import pandas as pd
import sys
import os
import matplotlib as mpl
#mpl.use('Agg')
from matplotlib import ticker
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matpl... | nce import pdist,cdist
import datetime
import time
import glob
import numpy.ma as ma
import importlib
import time_tools_attractor as ti
import io_tools_attractor as io
import data_tools_attractor as dt
import stat_tools_attractor as st
fmt1 = "%.1f"
fmt2 = "%.2f"
fmt3 = "%.3f"
np.set_printoptions(prec | ision=4)
################# DEFAULT ARGS #########################
inBaseDir = '/scratch/lforesti/data/' # '/store/msrad/radar/precip_attractor/data/' #'/scratch/lforesti/data/'
outBaseDir = '/users/lforesti/results/'
tmpBaseDir = '/scratch/lforesti/tmp/'
pltType = 'spread' #'evolution' 'spread'
timeSampMin = 5
spr... |
Donkyhotay/MoonPy | zope/tal/tests/utils.py | Python | gpl-3.0 | 1,998 | 0.005005 | ################################################### | ###########################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EX... | IES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Helper functions for the test suite.
$Id: utils.py 30139 2005-04-24 07... |
eroh92/asset-manager | asset_manager/datauris.py | Python | bsd-3-clause | 2,268 | 0.007055 | import base64
import re
import os
URL_FINDER = re.compile('url\(.*?\)')
STRIP_URL = re.compile('url\(|\)|\'|"')
file_extensions_to_types = {
"png": "image/png",
"jpg": "image/jpg",
"gif": "image/gif",
}
def _extract_image_urls_from_css(css):
return URL_FINDER.findall(css)
def _extract_image_urls_fro... | image_url = _get_image_path_from_css_url(css_image_url)
data_uri = _parse_image_url_into_data_uris(css_path, image_url)
css_file_content = css_file_content.replace(image_url | , data_uri)
except KeyError:
pass
except IOError:
pass
with open(css_path, 'w') as css_file:
css_file.write(css_file_content)
def _get_file_type(path):
return file_extensions_to_types[_get_file_extension_from_path(path)]
def _get_file_exten... |
juliantaylor/scipy | scipy/sparse/linalg/isolve/setup.py | Python | bsd-3-clause | 1,510 | 0.005298 | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import os
import sys
import re
from distutils.dep_util import newer_group, newer
from glob import glob
from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.system_info import get_inf... | package,top_path)
lapack_opt = get_info('lapack_opt')
if not lapack_opt:
raise NotFoundError('no lapack/blas resources found')
# iterative methods
methods = ['BiCGREVCOM.f.src',
'BiCGSTABREVCOM.f.src',
'CGREVCOM.f.src',
'CGSREVCOM.f.src',
# ... | Util = ['STOPTEST2.f.src','getbreak.f.src']
sources = Util + methods + ['_iterative.pyf.src']
sources = [join('iterative', x) for x in sources]
sources += get_g77_abi_wrappers(lapack_opt)
config.add_extension('_iterative',
sources=sources,
extra_info=l... |
azlanismail/prismgames | examples/games/car/networkx/algorithms/assortativity/tests/base_test.py | Python | gpl-2.0 | 1,539 | 0.046134 | import networkx as nx
class BaseTestAttributeMixing(object):
def setUp(self):
G=nx.Graph()
G.add_nodes_from([0,1],fish='one')
G.add_nodes_from([2,3],fish='two')
G.add_nodes_from([4],fish='red')
G.add_nodes_from([5],fish='blue')
G.add_edges_from([(0,1)... | h='red')
D.add_nodes_from([5],fish='blue')
D.add_edges_from([(0,1),(2,3),(0,4),(2,5)])
self.D=D
M=nx.MultiGraph()
M.add_nodes_from([0,1],fish='one')
M.add_node | s_from([2,3],fish='two')
M.add_nodes_from([4],fish='red')
M.add_nodes_from([5],fish='blue')
M.add_edges_from([(0,1),(0,1),(2,3)])
self.M=M
S=nx.Graph()
S.add_nodes_from([0,1],fish='one')
S.add_nodes_from([2,3],fish='two')
S.add_nodes_from([4],fis... |
fajoy/nova | nova/network/dns_driver.py | Python | apache-2.0 | 1,432 | 0 | # Copyright 2011 Andrew Bogott for the Wikimedia Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file e | xcept in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class DNSDriver(object):
"""Defines the DNS manager interfa... |
facebookresearch/ParlAI | docs/source/generate_opt_presets.py | Python | mit | 995 | 0.001005 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
import pkg_resources
from parlai.opt_presets.docs import PRESET_DESCRIPTIONS
fout = open('opt_presets_list... | CRIPTIONS[alias]
with pkg_resources.resource_stream("pa | rlai", f"opt_presets/{alias}.opt") as f:
expansion = json.load(f)
assert isinstance(expansion, dict)
expansion_str = []
for key, value in expansion.items():
key = '--' + key.replace('_', '-')
expansion_str.append(f'`{key} {value}`')
expansion_str = " ".joi... |
akretion/connector-magento | magentoerpconnect/doc/conf.py | Python | agpl-3.0 | 10,704 | 0.000093 | # -*- coding: utf-8 -*-
#
# Connectors documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 4 11:35:44 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... | o'))
# Load OpenERP | with correct addons-path so the doc can be built even if
# the addon import modules from other branches
import openerp
BASE_PATH = os.path.abspath(os.path.join(os.getcwd(), '../../..'))
# You may need to change with your own paths
ADDONS_PATHS = ('odoo/openerp/addons',
'odoo/addons',
'co... |
Etxea/gestioneide | turismo/models.py | Python | gpl-3.0 | 3,329 | 0.019826 | # -*- coding: utf-8 -*-
from django.db import models
from gestioneide.models import DIAS_SEMANA
import calendar
class Curso(models.Model):
year = models.ForeignKey('gestioneide.Year',on_delete=models.CASCADE)
nombre = models.CharField(max_length=50,default="")
def __unicode__(self):
return "%s - %s... | mes(self,mes):
dias_semana_clase = []
dias_clase = []
for dia in self.clases_turismo.all():
dias_semana_clase.append(dia.dia_semana)
year = Year().get_activo()
ano = yea | r.start_year
if mes < 8 :
ano = ano + 1
cal = calendar.Calendar()
for semana in cal.monthdays2calendar(ano,mes):
for dia in semana:
#Comprobamos que ese dia de la semana haya clase y no sea 0 (es de otro mes)
#Sumanos 1 al dia ya que empiez... |
numairmansur/RoBO | test/test_fmin/test_mtbo.py | Python | bsd-3-clause | 826 | 0.002421 | import unittest
import numpy as np
from robo.fmin import mtbo
def objective(x, t):
if t == 1:
c = 1000
y = (x - 0.5) ** 2
else:
| c = 1
y = (x - 0.5) ** 2 + 1
return y[0], c
class TestFminInterface(unittest.TestCase):
def setUp(self):
self.lower = np.zeros([2])
self.upper = np.ones([2]) * 3
def test_bayesian_o | ptimization(self):
res = mtbo(objective_function=objective,
lower=self.lower,
upper=self.upper,
n_tasks=2,
n_init=2,
num_iterations=3)
assert len(res["x_opt"]) == self.lower.shape[0]
assert np.all(res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.