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 |
|---|---|---|---|---|---|---|---|---|
MobileCloudNetworking/dssaas | dss_sm_so/sm/sm-0.3/sm/so_manager.py | Python | apache-2.0 | 24,446 | 0.002332 | # Copyright 2014-2015 Zuercher Hochschule fuer Angewandte Wissenschaften
# Copyright (c) 2013-2015, Intel Performance Learning Solutions Ltd, Intel Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the Lice... | ty.kind.term[0:4] + 'srvinst' + ''.join(random.choice('0123456789ABCDEF') for i in range(16))
heads = {
'Content-Type': 'text/occi',
'Category': 'app; scheme="http://schemas.ogf.org/occi/platform#", '
'python-2.7; scheme="http://schemas.openshift.com/template/app#", '
... | + app_name
}
url = self.nburl + '/app/'
LOG.debug('Requesting container to execute SO Bundle: ' + url)
LOG.info('Sending headers: ' + heads.__repr__())
r = http_retriable_request('POST', url, headers=heads, authenticate=True)
loc = r.headers.get('Location', '')
... |
openjck/kuma | kuma/wiki/middleware.py | Python | mpl-2.0 | 2,332 | 0 | from django.http import HttpResponseRedirect
from django.shortcuts import render
from kuma.core.utils import urlparams
from .exceptions import ReadOnlyException
f | rom .jobs | import DocumentZoneURLRemapsJob
class ReadOnlyMiddleware(object):
"""
Renders a 403.html page with a flag for a specific message.
"""
def process_exception(self, request, exception):
if isinstance(exception, ReadOnlyException):
context = {'reason': exception.args[0]}
r... |
cjaymes/expatriate | src/expatriate/model/xs/DayTimeDurationType.py | Python | lgpl-3.0 | 1,473 | 0.002037 | # Copyright 2016 Casey Jaymes
# This file is part of Expatriate.
#
# Expatriate is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version | 3 of the License, or
# (at your option) any later version.
| #
# Expatriate is distributed in the 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public Li... |
im0rtel/OpenBazaar | node/constants.py | Python | mit | 1,678 | 0.001192 | # ######## KADEMLIA CONSTANTS ###########
BIT_NODE_ID_LEN = 160
HEX_NODE_ID_LEN = BIT_NODE_ID_LEN // 4
# Small number representing the degree of
# parallelism in network calls
ALPHA = 3
# Maximum number of contacts stored in a bucket
# NOTE: Should be an even number.
K = 8 # pylint: disable=invalid-name
# Maximum n... | IVE_LOOKUP_DELAY = RPC_TIMEOUT / 2
# If a KBucket has not been used for this amount of time, refresh it.
# [seconds]
REFRESH_TIMEOUT = 60 * 60 * 1000 # 1 hour
# The interval at which nodes replicate (republish/refresh)
# the data they hold
# [seconds]
REPLICATE_INTERVAL = REFRESH_TIMEOUT
# The time it takes for dat... | _TIMEOUT = 86400 # 24 hours
# ####### IMPLEMENTATION-SPECIFIC CONSTANTS ###########
# The interval in which the node should check whether any buckets
# need refreshing or whether any data needs to be republished
# [seconds]
CHECK_REFRESH_INTERVAL = REFRESH_TIMEOUT / 5
# Max size of a single UDP datagram.
# Any larg... |
edineicolli/daruma-exemplo-python | scripts/fiscal/ui_fiscal_retornosstatusecf.py | Python | gpl-2.0 | 31,540 | 0.006603 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_fiscal_retornosstatusecf.ui'
#
# Created: Mon Nov 24 22:26:20 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_ui_FISCAL_Retorno... | essora_ECF_Daruma.triggered.connect(self.on_rStatusImpressora_ECF_Daruma_triggered)
self.actionM_todo_rStatusImpressoraBinario_ECF_Daruma.triggered.connect(self.on_rStatusImpressoraBinario_ECF_Daruma_triggered)
self.actionM_todo_rConsultaStatusImpressoraStr_ECF_Daruma.triggered.connect(self.on_rConsulta... | f.on_rConsultaStatusImpressoraInt_ECF_Daruma_triggered)
self.actionM_todo_rStatusUltimoCmd_ECF_Daruma.triggered.connect(self.on_rStatusUltimoCmd_ECF_Daruma_triggered)
self.actionM_todo_rStatusUltimoCmdInt_ECF_Daruma.triggered.connect(self.on_rStatusUltimoCmdInt_ECF_Daruma_triggered)
self.actionM... |
googleapis/python-datacatalog | google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py | Python | apache-2.0 | 1,167 | 0.000857 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the | "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC | ENSE-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 Li... |
spcui/autotest | client/deps/libaio/libaio.py | Python | gpl-2.0 | 809 | 0.001236 | #!/usr/bin/python
import os
from autotest.client import utils
version = 1
def setup(tarball, topdir):
srcdir = os.path.join(topdir, 'src')
utils.extract_tarball_to_dir(tarball, srcdir)
os.chdir(srcdir)
utils.system('patch -p1 < ../00_arches.patch')
utils.make()
utils.make('prefix=%s install' ... | update_version(pwd+'/src | ', False, version, setup, tarball, pwd)
|
Star2Billing/cdr-stats | cdr_stats/user_profile/views.py | Python | mpl-2.0 | 3,380 | 0.002663 | #
# CDR-Stats License
# http://www.cdr-stats.org
#
# 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/.
#
# Copyright (C) 2011-2015 Star2Billing S.L.
#
# The Initial Developer of the Or | iginal Code is
# Arezqui Belaid <[email protected]>
#
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404
#from django.http import HttpResponseRedirect
from django.template.context import RequestCon... |
synw/django-chartflo | chartflo/templatetags/chartflo_tags.py | Python | mit | 374 | 0 | # -*- coding: utf-8 | -*-
import os
from django import template
register = template.Library()
@register.simple_tag
def get_altair_scripts(dashboard_slug):
path = "dashboards/" + dashboard_slug + "/altair_scripts"
scripts = os.listdir("templates/" + path)
includes = []
for script in scripts:
includes.append(path + ... | + script)
return includes
|
ericmjl/bokeh | examples/models/file/trail.py | Python | bsd-3-clause | 4,605 | 0.004778 | from math import atan2, cos, radians, sin, sqrt
import numpy as np
import scipy.ndimage as im
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.models import (Column, ColumnDataSource, GMapOptions, GMapPlot,
Grid, Label, Line, LinearAxis, PanTool, Patches,
... | lor='red'))
return plot
def altitude_profile(data):
plot = Plot(plot_width=800, plot_height=400)
plot.title.text = "%s - Altitude Profile" % name
plot.y_range.range_padding = 0
xaxis = LinearAxis(axis_label="Distance (km)")
plot.add_layout(xaxis, 'below')
yaxis = LinearAxis(axis_ | label="Altitude (m)")
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) # x grid
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # y grid
plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())
X, Y = data.dist, data.alt
y0 = min(Y)
patches_... |
RedHatInsights/insights-core | insights/parsers/tests/test_ls_edac_mc.py | Python | apache-2.0 | 875 | 0.001143 | from insights.parsers import ls_edac_mc
from insights.parsers.ls_edac_mc import LsEdacMC
from insights.tests import context_wrap
import doctest
LS_EDAC_MC = """
/sys/devices/system/eda | c/mc:
total 37592
drwxr-xr-x. 3 0 0 0 Jan | 10 10:33 .
drwxr-xr-x. 3 0 0 0 Jan 10 10:33 ..
drwxr-xr-x. 2 0 0 0 Jan 10 10:33 power
drwxr-xr-x. 2 0 0 0 Jan 10 10:33 mc0
drwxr-xr-x. 2 0 0 0 Jan 10 10:33 mc1
drwxr-xr-x. 2 0 0 0 Jan 10 10:33 mc2
"""
def test_ls_edac_mc():
ls_edac_mc = LsEdacMC(context_wrap(LS_EDAC_MC))
assert '/sys/devices/system/edac/mc' i... |
cherrygirl/micronaet7 | production_line_statistic/statistic.py | Python | agpl-3.0 | 4,479 | 0.005135 | # -*- coding: utf-8 -*-
###############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# d$
#
# This program is free software: you can redistribute it and/or modify
#... | , required=True),
'note': fields.text('Note'),
'uptime': fields.boolean('Uptime', help='Motivation that means up time'),
}
_defaults = {
'sequence': 100,
'uptime': False,
}
class mrp_workcenter_work(osv.osv):
''' WOrkcenter statistic (work and extra motives)
'''
... | -------------------------------------------------------------
# Utility function
# -------------------------------------------------------------------------
def load_days_statistic(self, cr, uid, from_date, to_date, line=False, forced=False, context=None):
''' Load all statist... |
saltstack/salt | salt/returners/memcache_return.py | Python | apache-2.0 | 5,855 | 0.001366 | """
Return data to a memcache server
To enable this returner the minion will need the python client for memcache
installed and the following values configured in the minion or master
config, these are the defaults.
.. code-block:: yaml
memcache.host: 'localhost'
memcache.port: '11211'
Alternative configurat... | v, "minions")
returns = serv.get_multi(minions, key_prefix="{}:".format(jid))
# returns = {minion: return, minion: return, ...}
ret = {}
for minion, data in returns.items():
ret[minion] = salt.utils.json.loads(data)
return ret
def get_fun(fun):
"""
Return a dict of the last functio... | serv = _get_serv(ret=None)
minions = _get_list(serv, "minions")
returns = serv.get_multi(minions, key_prefix="{}:".format(fun))
# returns = {minion: return, minion: return, ...}
ret = {}
for minion, data in returns.items():
ret[minion] = salt.utils.json.loads(data)
return ret
def ge... |
tedsunnyday/Tweet2DowJones | json/dev/gen.py | Python | mit | 683 | 0.01757 | #!/usr/bin/python
import json
from random import randint
INPUT = "Tweet.size1000page1cnt849.json"
OUTPUT = 'new.json'
objs = json.load(open(INPUT,'r'))
print len(objs)
# for k,v in objs[ | 0].items():
# print "%s=\n\t%s | " % (str(k),str(v))
def date_handler(obj):
import datetime
return obj.strft | ime("%Y-%m-%d %H:%M:%S") if isinstance(obj,datetime.datetime) else obj
se = []
for o in objs:
# se.append( {'x':o['created_at'],'y':randint(0,1000)} )
se.append([o['created_at'],randint(0,1000)])
di = {'name':'LA','series':se}
# print json.dumps(di)
# print type(di['series'][0][0])
f = open(OUTPUT,'w+')
f.wr... |
GoogleCloudPlatform/declarative-resource-client-library | python/services/cloudresourcemanager/project.py | Python | apache-2.0 | 5,106 | 0.001371 | # Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | .labels)
if Primitive.to_proto(self.displayName):
request.resource.displayName = Primitive.to_proto(self.displayName)
if Primitive.to_proto(self.parent):
request.resource.par | ent = Primitive.to_proto(self.parent)
if Primitive.to_proto(self.name):
request.resource.name = Primitive.to_proto(self.name)
request.service_account_file = self.service_account_file
response = stub.ApplyCloudresourcemanagerProject(request)
self.labels = Primitive.from_pro... |
kaplun/Invenio-OpenAIRE | modules/bibformat/lib/elements/bfe_cited_by.py | Python | gpl-2.0 | 2,193 | 0.013224 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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
## ... | ement(bfo, separator='; '):
"""
Prints a list of records citing this record
@param separator: a s | eparator between citations
"""
from urllib import quote
from invenio.config import CFG_SITE_URL
primary_report_numbers = bfo.fields('037__a')
additional_report_numbers = bfo.fields('088__a')
primary_citations = ['<a href="' + CFG_SITE_URL + \
'/search?f=reference&p... |
m0re4u/LeRoT-SCLP | lerot/evaluation/DcgEval.py | Python | gpl-3.0 | 2,915 | 0 | # This file is part of Lerot.
#
# Lerot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Lerot is distributed in the hope tha... | e metric
- ranking contains the list of documents to evaluate
- labels are the relevance labels for all the documents, even those
that are not in the ranking; labels[doc.get_id()] is the relevance of
doc
- orientations contains orientation values for the verticals;
... | the
doc (from 0 to 1).
"""
return self.get_dcg([labels[doc.get_id()] for doc in ranking], cutoff)
|
2015fallhw/cdw2 | users/s2b/g4/scrum5_task1.py | Python | agpl-3.0 | 3,680 | 0.005582 | 各組分別在各自的 .py 程式中建立應用程式 (第1步/總共3步)
from flask import Blueprint, render_template
# 利用 Blueprint建立 ag1, 並且 url 前綴為 /ag1, 並設定 template 存放目錄
scrum5_task1 = Blueprint('scrum5_task1', __name__, url_prefix='/bg4', template_folder='templates')
# scrum5_task1 為完整可以單獨執行的繪圖程式
@scrum5_task1.route('/scrum5_task1')
def task1():
... | # 放大 5 倍
cgo.render(cmbr, x, y, 5, rot)
O(0, 0, 0, 0, 0, "lightyellow", True, 4)
</script>
<!-- 以協同方式加上 ag100 的 scrum-2 組員所寫的 task1 程式碼 -->
<!-- <script type="text/python" src="/ag100/scrum2_task1"></script>
<!-- 以協同方式加上 ag100 的 sc | rum-3 組員所寫的 task1 程式碼 -->
<!-- <script type="text/python" src="/ag100/scrum3_task1"></script>
</body>
</html>
'''
return outstring |
spahan/unixdmoain | wwwlib/rest.py | Python | bsd-3-clause | 2,782 | 0.009346 | from mod_python import apache
from mod_python import util
import os.path
import urllib
import logging
debug = True
def handler(req):
"""
This is called by Apache and maps the request to the resource class.
Process of maping:
1. Try import a python script which handles this resource.
T... |
req is the request object,
id is the parsed id or None
args is the mp_table object (may be empty)
returns the return code from the function
if the method is not defined, we return HTTP_NOT_IMPLEMENTED
"""
#Set log level here. For Production, disable ... | ed for simple error search.
#logging.basicConfig(level=logging.INFO) #Used for error search with config.
# 1.
try:
(mtype, mid) = req.path_info.lstrip('/').split('/',1)
except ValueError, err:
mtype = req.path_info.lstrip('/')
mid = ''
try:
resourceModule = apache.imp... |
kzganesan/you-get | src/you_get/common.py | Python | mit | 30,127 | 0.006738 | #!/usr/bin/env python
import getopt
import json
import locale
import os
import re
import sys
from urllib import request, parse
import platform
import threading
from .version import __version__
from .util import log, sogou_proxy_server, get_filename, unescape_html
dry_run = False
force = False
player = None
sogou_pro... | None)
e | lse:
response = request.urlopen(url)
data = response.read()
if response.info().get('Content-Encoding') == 'gzip':
data = ungzip(data)
elif response.info().get('Content-Encoding') == 'deflate':
data = undeflate(data)
response.data = data
return response
# DEPRECATED in favor... |
apuigsech/BittrexAPI | BittrexAPI/__init__.py | Python | gpl-3.0 | 1,505 | 0.000664 | #!/usr/bin/env python
# BittrexAPI: Python Bittrex API implementatio | n
#
# Copyright (c) 2014 - Albert Puigsech Galicia ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights | to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions... |
buffer/peepdf | tests/test_pee.py | Python | gpl-3.0 | 1,359 | 0.000736 | # peepdf is a tool to analyse and modify PDF files
# http://peepdf.eternal-todo.com
# By Jose Miguel Esparza <jesparza AT eternal-todo.com>
#
# Copyright (C) 2016 Jose Miguel Esparza
#
# This file is part of peepdf.
#
# peepdf is free software: you can redistribute it and/or modify
# it und... | assert obj.object.errors != [
"Decoding error: Error de | compressing string"
]
|
metabrainz/listenbrainz-server | listenbrainz/db/tests/test_stats.py | Python | gpl-2.0 | 16,778 | 0.004232 | import json
from copy import deepcopy
from datetime import datetime, timezone
import listenbrainz.db.stats as db_stats
import listenbrainz.db.user as db_user
from data.model.common_stat import StatRange
from data.model.user_artist_map import UserArtistMapRecord
from data.model.user_daily_activity import DailyActivityR... | es_data))
result = db_stats.get_user_stats(user_id=self.user['id'], stats_range='all_time', stats_type='releases')
self.assertDictEqual(result.dict(exclude={'user_id', 'last_updated'}), releases_data)
|
def test_insert_user_recordings(self):
""" Test if recording stats are inserted correctly """
with open(self.path_to_data_file('user_top_recordings_db.json')) as f:
recordings_data = json.load(f)
db_stats.insert_user_jsonb_data(user_id=self.user['id'], stats_type='recordings',
... |
enthought/pikos | pikos/monitors/function_monitor.py | Python | bsd-3-clause | 3,191 | 0.000627 | # -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# Package: Pikos toolkit
# File: monitors/function_monitor.py
# License: LICENSE.TXT
#
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#--------------------------------------------------------------... | record_type : type
A class object to be used for r | ecords. Default is
:class:`~.FunctionRecord`.
"""
self._recorder = recorder
self._record = recorder.record
self._profiler = ProfileFunctionManager()
self._index = 0
self._call_tracker = KeepTrack()
if record_type is None:
self._record_type... |
jballanc/openmicroscopy | components/tools/OmeroPy/test/integration/scriptstest/test_make_movie.py | Python | gpl-2.0 | 1,111 | 0.0036 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Integration test which checks the various parameters for makemovie.py
Copyright 2010-2013 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import test.integration.library as lib
import os, sys
import om... | """
def setup_method(self, method):
lib.ITest.setup_method(self, method)
self.svc = self.client.sf.getScriptService()
def testNoParams(self):
makeMovieID = self.svc.getScriptID("/omero/export_scripts/Make_Movie.py")
imported_pix = ",".join(self.import_image())
imported_... | (%s)" % imported_pix, None)
inputs = {"IDs": omero.rtypes.rlist([imported_img.id])}
impl = omero.processor.usermode_processor(self.root)
try:
process = self.svc.runScript(makeMovieID, inputs, None)
finally:
impl.cleanup()
|
vengefuldrx/dillonhicks.io | render.py | Python | mit | 4,597 | 0.003482 | import argparse
import os
import re
from pathlib import Path, PurePath
from jinja2 import Template, FileSystemLoader, Environment
from collections import namedtuple, defaultdict, MappingView, OrderedDict
PhotoCredit = namedtuple('PhotoCredit', ('link', 'name'))
Link = namedtuple('Link', ('link', 'caption'))
Project... | n register_matched_ctx(self.string, func)
return register_named_ctx(self.string, func)
def create_context(name):
ctx_funcs = []
for pattern, func in ctx_by_match.items():
if re.match(pattern, name):
ctx_funcs.append(func)
ctx_funcs.append(ctx_by_name[name])
context = {}
... | '^.+html$', regex=True)
def base_ctx():
return {
'navigation' : navigation
}
@context_for('projects.html')
def proj_ctx():
dillonio = Project(
date='April 2016',
name='DillonHicks.io',
link='https://github.com/vengefuldrx/dillonhicks.io',
image='img/dillonhicksiofla... |
CartoDB/cartodb-python | examples/import_from_database.py | Python | bsd-3-clause | 2,669 | 0.001499 | import argparse
import json
import logging
import os
import re
import warnings
from carto.auth import APIKeyAuthClient
from carto.datasets import DatasetManager
warni | ngs.filterwarnings('ignore')
# python import_from_database.py --connection='{ \
# "connector": { \
# "provider": "hive", \
# "conn | ection": { \
# "server":"YOUR_SERVER_IP", \
# "database":"default", \
# "username":"cloudera", \
# "password":"cloudera" \
# },
# "schema": "default", \
# "table": "order_items" \
# }
# }'
# Logger (better than print)
logging.basicConfig(
level=logging.INFO,
format=' %(asc... |
matteocereda/RNAmotifs | m3_light/utils/__init__.py | Python | mit | 2,230 | 0.003139 | def merge_int | ervals(data):
"""
data = [(10,20), (15,30), (100, 200)]
out = [(10,30), (100,200)]
"""
if len(data)==0:
return data
result = []
saved = list(data[0])
for st, en in sorted([sorted(t) for t in data]):
if st <= saved[1]:
saved[1] = max(saved[1], en)
| else:
result.append((saved[0], saved[1]))
saved[0] = st
saved[1] = en
result.append(saved)
return result
class Bedgraph():
def __init__(self, filename):
self.data = {}
self.sites = 0
self.strand_file = {"+":"", "-": "-"}
self.load(fi... |
dimagi/commcare-hq | corehq/ex-submodules/dimagi/utils/couch/database.py | Python | bsd-3-clause | 6,069 | 0.001648 | from time import sleep
from django.conf import settings
from couchdbkit import ResourceConflict
from couchdbkit.client import Database
from memoized import memoized
from requests.models import Response
from requests.exceptions import RequestException
from dimagi.ext.couchdbkit import Document
from dimagi.utils.chunk... | n chunked(ids, chunksize):
for doc in get_docs(database, keys=doc_ids, **query_params):
yield doc
def iter_bulk_delete(database, ids, chunksize=100, doc_callback=None, wait_time=None,
max_fetch_attempts=1):
total_count = 0
for doc_ids in chunked(ids, chunksize):
for i in ra... | ocs(database, keys=doc_ids)
break
except RequestException:
if i == (max_fetch_attempts - 1):
raise
sleep(30)
if doc_callback:
for doc in doc_dicts:
doc_callback(doc)
total_count += len(doc_dicts... |
EdLogan18/logan-repository | plugin.video.exodus/resources/lib/sources/uflix_mv_tv.py | Python | gpl-2.0 | 5,626 | 0.009598 | # | -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any la... | ill 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. If not, see <http://ww... |
novirael/arkanoid-pygame | levels.py | Python | gpl-2.0 | 1,317 | 0.025816 | #-------------------------------------------------------------------------------
# Name: levels
# Purpose:
#
# Author: novirael
#
# Created: 17-04-2012
# Copyright: (c) novirael 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------... |
# Variables
SW, SH = 900, 600
k_width, k_height = 45, 20
def draw_level(n):
if n == 1:
# The top of the block (y position)
top = 80
for i in range(15):
block = Kafel(blue, kafelek[0], i*(k_width+2), top)
blocks.add(block)
allsprites.add(block)
return... | prites, blocks
# --- Create blocks
"""
# Five rows of blocks
for row in range(2):
for column in range(0,20):
block = Kafel(blue, kafelek[0], column*(k_width+2), top)
blocks.add(block)
allsprites.add(block)
# Move the top of the next row down
top += k_height + ... |
UPPMAX/nsscache | nss_cache/util/timestamps_test.py | Python | gpl-2.0 | 2,605 | 0.003839 | # Copyright 2011 Google Inc.
#
# 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 ho... | , 'w')
ts_file.write('1970-01-01T00:00:01Z\n')
ts_file.close()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(time.gmtime(1), ts)
def testReadTimestamp(self):
# TZ=UTC date -d @1306428781
# Thu May 26 16:53:01 UTC 2011
ts_filename | = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts_file.write('2011-05-26T16:53:01Z\n')
ts_file.close()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(time.gmtime(1306428781), ts)
def testReadTimestampInFuture(self):
ts_filename = os.path.join(self.workdir, ... |
nsnam/ns-3-dev-git | src/internet/test/examples-to-run.py | Python | gpl-2.0 | 607 | 0.003295 | #! /usr/bin/env python3
## -*- Mode | : python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
(... | ain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
|
MikeDacre/mike_tools | bin/wasp_pipeline.py | Python | unlicense | 13,352 | 0.000899 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run the entire WASP pipeline with either tophat or STAR.
============================================================================
FILE: wasp_pipeline.py
DIR: /scratch/users/dacre
AUTHOR: Michael D Dacre, [email protected]
ORGANIZA... | ormat(name + '_tophat')
command = command + ' -G ' + gtf if gtf else command
command = command + ' -p 16 {} {}\n'.format | (genome, infiles)
outbam = name + '_accepted_hits.bam'
command = command + 'mv {}/accepted_hits.bam {}'.format(
name + '_tophat', outbam)
modules = ['python/2.7.5', 'tophat']
else:
raise Exception('Invalid algorithm: {}'.format(algorithm))
return (slurmy.monitor_su... |
olivergs/pyevo | pyevo/api/googletranslate.py | Python | mit | 730 | 0.017833 | # -*- coding: utf-8 -*-
"""
===============================================
.. module::
:platform: Unix, Windows
:synopsis:
:deprecated:
.. moduleauthor:: (C) 2014 Oliver Gutiérrez
"""
from pyevo.http import nvp_request
def translate(apikey,text,from_lang,to_lang):
"""
Translation to english fu... | pass
retur | n None |
davidt/reviewboard | reviewboard/hostingsvcs/tests/test_hosting_service_auth_form.py | Python | mit | 16,079 | 0 | from __future__ import unicode_literals
from reviewboard.hostingsvcs.errors import (AuthorizationError,
TwoFactorAuthCodeRequiredError)
from reviewboard.hostingsvcs.forms import HostingServiceAuthForm
from reviewboard.hostingsvcs.models import HostingServiceAccount
from revi... | ingServiceAuthForm.save with new account"""
form = HostingServiceAuthForm(
{
'hosting_account_username': 'myuser',
'ho | sting_account_password': 'mypass',
},
hosting_service_cls=TestService)
self.assertTrue(form.is_valid())
hosting_account = form.save()
self.assertIsNotNone(hosting_account.pk)
self.assertEqual(hosting_account.service_name, 'test')
self.assertEqual(hostin... |
timqian/sms-tools | lectures/4-STFT/plots-code/window-size.py | Python | agpl-3.0 | 1,498 | 0.012016 | import math
import matplotlib.pyplot as plt
import numpy as np
import time, os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))
import dftModel as DF
import utilFunctions as UF
(fs, x) = UF.wavread('../../../sounds/oboe-A4.wav')
N = 128
start = .81*fs
x1 =... | b', lw=1.5)
plt.axis([start/fs, (start+N)/fs, min(x1*np.hamming(N)), max(x1*np.hamming(N))])
plt.title('x1, M = 128')
mX, pX = DF.dftAnal(x1, np.hamming(N), N)
plt.subplot(323)
plt.plot((fs/2.0)*np.arange(mX.size)/float(mX.size), mX, 'r', lw=1.5)
plt.axis([0,fs/2.0,-90,max(mX)])
plt.title('mX1')
plt.subplot(325)
plt.... | = x[start:start+N]
mX, pX = DF.dftAnal(x2, np.hamming(N), N)
plt.subplot(322)
plt.plot(np.arange(start, (start+N), 1.0)/fs, x2*np.hamming(N), 'b', lw=1.5)
plt.axis([start/fs, (start+N)/fs, min(x2), max(x2)])
plt.title('x2, M = 1024')
plt.subplot(324)
plt.plot((fs/2.0)*np.arange(mX.size)/float(mX.size), mX, 'r', lw=1.... |
Syncano/syncano-cli | syncano_cli/base/prompter.py | Python | mit | 536 | 0.003731 | import click
from syncano_cli.base.options import ColorSchema
class Promp | ter(object):
indent = ' '
def prompt(self, text, color=None, **kwargs):
styles_kwargs = {'fg': color or ColorSchema.PROMPT}
return click.prompt(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
def confirm(self, text, color=None, | **kwargs):
styles_kwargs = {'fg': color or ColorSchema.PROMPT}
return click.confirm(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
|
gonicus/gosa | backend/src/tests/backend/components/test_jsonrpc_service.py | Python | lgpl-2.1 | 6,629 | 0.00181 | # This file is part of the GOsa framework.
#
# http://gosa-project.org
#
# Copyright:
# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.
import unittest.mock
from tornado.web import Application
from gosa.common.gjson import dumps, loads
... | self.patcher.stop()
def test_login(self):
# successful login
with unittest.mock.patch.object(JsonRpcHandler, 'authenticate', return_value='cn=System Administrator,ou=people,dc=example,'
| 'dc=net') as m:
response = self.login()
assert response.code == 200
json = loads(response.body)
assert json['result']['state'] == AUTH_SUCCESS
assert json['error'] is None
assert json['id']... |
makinacorpus/django | tests/httpwrappers/tests.py | Python | bsd-3-clause | 23,131 | 0.001601 | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import copy
import os
import pickle
import unittest
import warnings
from django.core.exceptions import SuspiciousOperation
from django.core.signals import request_finished
from django.db import close_old_connections
from django.http import (QueryDict, ... | Raises(AttributeError, q.popitem)
self.assertRaises(AttributeError, q.clear)
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
self.assertRaises(AttributeError, q.__ | delitem__, 'vote')
if not six.PY3:
def test_invalid_input_encoding(self):
"""
Query |
tylere/earthengine-api | python/ee/tests/_cloud_api_utils_test.py | Python | apache-2.0 | 13,942 | 0.003228 | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import warnings
import unittest
from ee import _cloud_api_utils
from ee import ee_exception
class CloudApiUtilsTest(unittest.TestCase):
def setUp(self):
super(Cloud... | 45], [10, 45], [10, 60], [-105, 60], [-105, 45]]
]
}, geo_json_parsed)
def test_convert_asset_type_for_cre | ate_asset(self):
self.assertEqual(
'IMAGE_COLLECTION',
_cloud_api_utils.convert_asset_type_for_create_asset('ImageCollection'))
self.assertEqual(
'IMAGE_COLLECTION',
_cloud_api_utils.convert_asset_type_for_create_asset(
'IMAGE_COLLECTION'))
self.assertEqual(
... |
FlashXT/XJTU_WorkLog | 2017.10/Engineering/PythonCrawler/Crawler_cookielib2.py | Python | gpl-3.0 | 692 | 0.018456 | #coding=utf-8
#2017.10.6,Flash,cookielib
import urllib2
import cookielib
filename="cookiebd.txt"
#声明一个cookieJar对象实例来保存cookie
cookie = cookielib.MozillaCookieJar(filename)
#利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
handler = urllib2.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opene | r = urllib2.build_opener(handler)
#此处的open方法同urllib2的urlopen方法,也可以传入request
response = opener.open("http://www.baidu.com")
#for item in cookie:
# print "Name = " +item.name
# print "Value = " + item.value
#保存cookie到文件
cookie.save(ignore_discard=True | , ignore_expires=True)
print "OK !"
|
guanxiLi/django_check | d3jscluster/cluster/rewardprocess.py | Python | apache-2.0 | 373 | 0.034853 | imp | ort threading
import time
import os
class CheckThread(threading.Thread):
def __init__(self, files):
threading.Thread.__init__(self)
self.files = files
def check_reward(self,files):
os.remove("./cluster/log/checklog.log")
check_log = open('./cluster/log/checklog.log', 'a')
check_log.write("hehehehhfffff\n")... | |
alerta/alerta-contrib | integrations/consul/consulalerta.py | Python | mit | 2,770 | 0.002888 | #!/usr/bin/env python
import json
import os
import consul
import sys
import time
from alertaclient.api import Client
CONSUL_HOST = os.environ.get('CONSUL_HOST', '127.0.0.1')
CONSUL_PORT = int(os.environ.get('CONSUL_PORT', 8500))
client = consul.Consul(host=CONSUL_HOST, port=CONSUL_PORT, token=None, scheme='http', c... | 'default', dc=None, verify=True)
j = json.load(sys.stdin)
print("Request:")
print(j)
try:
url = client.kv.get('alerta/apiurl')[1]['Value']
except Exception:
print("No URL defined, exiting")
sys.exit(1)
try:
key = client.kv.get('alerta/apikey')[1]['Value']
except Exception:
| print("No key defined, exiting")
sys.exit(1)
try:
max_retries = int(client.kv.get('alerta/max_retries')[1]['Value'])
except TypeError:
print("No value defined, using default")
max_retries = 3
try:
sleep = int(client.kv.get('alerta/sleep')[1]['Value'])
except TypeError:
print("No value defin... |
gencer/python-phonenumbers | python/phonenumbers/shortdata/region_KM.py | Python | apache-2.0 | 547 | 0.009141 | """Auto-generated file, do not edit by hand. KM m | etadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_KM = PhoneMetadata(id='KM', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d', possible_length=(2,)), |
emergency=PhoneNumberDesc(national_number_pattern='1[78]', example_number='17', possible_length=(2,)),
short_code=PhoneNumberDesc(national_number_pattern='1[78]', example_number='17', possible_length=(2,)),
short_data=True)
|
haystack/eyebrowse-server | api/migrations/0046_auto__add_unique_ratings_user_page.py | Python | mit | 16,679 | 0.008394 | # -*- 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 unique constraint on 'Ratings', fields ['user', 'page']
db.creat... | st_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
' | api.eyehistoryraw': {
'Meta': {'object_name': 'EyeHistoryRaw'},
'domain': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '2000'}),
'end_event': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '40'}),
'end_time': ('django... |
alejandrobernardis/tornado-heroku | main.py | Python | mit | 385 | 0 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Asumi Kamikaze Inc.
# Licensed under | the MIT License.
# Author: Alejandro M. Bernardis
# Email: alejandro (dot) bernardis (at) asumikamikaze (dot) com
# Created: 08/Jun/2015 12:42
import os
# Global settin | gs
os.environ.setdefault('SERVER_SETTINGS_MODULE', 'settings_example')
if __name__ == '__main__':
pass
|
memtoko/django | django/db/utils.py | Python | bsd-3-clause | 9,585 | 0.000939 | import os
import pkgutil
from importlib import import_module
from threading import local
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils._os import upath
from django.utils.functional import cached_property
from django.utils.module_... | 109.
def inner(*args, **kwargs):
with self:
return func(*args, **kwargs)
return inner
def load_backend(backend_name):
# Look for a fully qualifie | d database backend name
try:
return import_module('%s.base' % backend_name)
except ImportError as e_user:
# The database backend wasn't found. Display a helpful error message
# listing all possible (built-in) database backends.
backend_dir = os.path.join(os.path.dirname(upath(__f... |
WubbaDuck/OverwatchTracker | graph.py | Python | gpl-3.0 | 3,048 | 0.00164 | import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import pyqtgraph as pg
import numpy as np
class SRGraph(QWidget):
def __init__(self):
super(SRGraph, self).__init__()
#self.setFixedSize(500,375)
#self.labelFont = QFont("Arial", 10)
# Initialize the RG... | get(self.ledPulseEnable,3,0)
self.grid.addWidget(self.ledSolidEnable,2,0)
self.grid.addWidget(self.ledPulseSpeed,3,1)
self.grid.addWidget(self.ledPulseLabel,3,2)
'''
x = np.random.normal(size=1000)
y = np.random.normal(size=1000)
plotWidget = pg.PlotWid... | )
self.setLayout(self.grid) # Set Gui layout
# Enable/Disbale the LED Pulse settings
def ledPulseState(self, state):
self.ledPulseLabel.setEnabled(state)
self.ledPulseSpeed.setEnabled(state)
# Button press output
def saveSettings(self):
pass
... |
elainenaomi/sciwonc-dataflow-examples | dissertation2017/Experiment 2/instances/11_2_wikiflow_1sh_1s_annot/sessioncompute_3/SessionCompute_3.py | Python | gpl-3.0 | 2,784 | 0.001796 | #!/usr/bin/env python
from sciwonc.dataflow.DataStoreClient import DataStoreClient
import ConfigDB_SessionCompute_3
imp | ort pprint
# connector and config
client = DataStoreClient("mo | ngodb", ConfigDB_SessionCompute_3)
config = ConfigDB_SessionCompute_3
# according to config
dataList = client.getData() # return an array of docs (like a csv reader)
output = []
ONE_HOUR_IN_SECONDS = 3600
if(dataList):
for i in dataList:
contributor_username = i[config.COLUMN]
current_user = con... |
simula67/Coding | python/AAD PoC/naive_fibinocci.py | Python | gpl-3.0 | 241 | 0.024896 | #!/usr/bin/python
import sys
def fib(n):
if(n<=2):
return (n-1)
else:
return fib(n-1)+fib(n-2)
if ( len(sys.argv) == 2 ): |
print fib(int(sys.argv[1]))
els | e:
print "Usage : "+sys.argv[0]+" <term required>"
|
baigk/compass-core | compass/hdsdiscovery/vendors/appliance/plugins/mac.py | Python | apache-2.0 | 1,508 | 0 | # Copyright 2014 Huawei Technologies Co. Ltd
#
# 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... | class Mac(base.BaseSnmpMacPlugin):
"""Processes MAC address."""
def __init__(self, host, credential):
self.host = host
# self.credential = credential
# return
d | ef scan(self):
"""Implemnets the scan method in BasePlugin class.
.. note::
Dummy scan function for compass appliance.
Returns fixed mac addresses.
"""
mac_list = None
machine_lists = util.load_configs(setting.MACHINE_LIST_DIR)
for items in mac... |
0todd0000/spm1d | spm1d/stats/normality/__init__.py | Python | gpl-3.0 | 637 | 0.032967 |
'''
Normality tests for 1D data
'''
# Copyright (C) 2016 Todd Pataky
from . import k2,sw
def dagostinoK2(x):
return k2.residuals(x) |
def shapirowilk(x):
return sw.residuals(x)
residuals = k2.residuals
anova1 = k2.anova1
anova1rm = k2.anova1rm
anova2 = k2.anova2
anova2nested = k2.anova2nested
anova2onerm = k2.anova2onerm
anova2rm = k2.anova2rm
anova3 = k2.anova3
anova3nested = k2.anova3nested
anova3onerm = k2... | est_paired = k2.ttest_paired
ttest2 = k2.ttest2
|
nop33/indico | indico/modules/rb/models/room_bookable_hours.py | Python | gpl-3.0 | 1,910 | 0 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PAR | TICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from datetime import time
from indico.core.db import db
from indico.util.string import return_ascii
class Bo... |
NilsGuo/nilsblog | app/main/__init__.py | Python | mit | 243 | 0.00823 | # -*- coding:utf-8 -*-
from flask import Blueprint
main = Blue | print('main', __name__)
from . import views, errors
from ..models import Permission
@main.app_context_processor
def inject_permissions():
return dict(Pe | rmission=Permission)
|
florensacc/snn4hrl | algos/npo_snn_rewards.py | Python | mit | 16,007 | 0.004123 | import collections
import numpy as np
import theano
import theano.tensor as TT
import rllab.misc.logger as logger
from rllab.algos.batch_polopt import BatchPolopt, BatchSampler
from rllab.algos.npo import NPO
from rllab.misc import ext
from rllab.misc.overrides import overrides
from rllab.sampler import parallel_samp... | # parallel_sampler._worker_collect_one_path_snn, # now this is defined | in parallel_sampler also!
self._worker_collect_one_path_snn, # now this is defined in parallel_sampler also!
threshold=max_samples,
args=(max_path_length, self.switch_lat_every, scope),
show_prog_bar=True
)
def obtain_samples(self, itr):
cur_params =... |
gentoo/layman | layman/overlays/overlay.py | Python | gpl-2.0 | 27,365 | 0.003545 | #!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
# LAYMAN OVERLAY BASE CLASS
################################################################################
# File: overlay.py
#
# Base class for the different overlay types.
#
#... | def from_dict(self, overlay, ignore):
'''
Process an overlay dictionary definition
'''
msg = 'Overlay from_dict(); overlay %(ovl)s' % {'ovl': str(overlay)}
self.ou | tput.debug(msg, 6)
_name = overlay['name']
if _name != None:
self.name = encode(_name)
else:
msg = 'Overlay from_dict(), "name" entry missing from dictionary!'
raise Exception(msg)
if 'source' in overlay:
_sources = overlay['source']
... |
pombredanne/marshmallow-polyfield | tests/shapes.py | Python | apache-2.0 | 2,889 | 0 | # -*- coding: utf-8 -*-
from marshmallow import Schema, fields, post_load
class Shape(object):
def __init__(self, color):
self.color = color
def __eq__(self, other):
return self.__dict__ == other.__dict__
class ShapeSchema(Schema):
color = fields.Str(allow_none=True)
class Triangle(Sh... | _dict.get("length"):
return RectangleSchema()
raise TypeError("Could not detect type. "
"Did not have a base or a length. "
"Are yo | u sure this is a shape?")
def shape_property_schema_deserialization_disambiguation(object_dict, data):
type_to_schema = {
'rectangle': RectangleSchema,
'triangle': TriangleSchema
}
try:
return type_to_schema[data['type']]()
except KeyError:
pass
raise TypeError("C... |
liruhua99/awesome-python3-webapp | www/config_override.py | Python | gpl-3.0 | 135 | 0.014815 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Li Ruhua'
configs = {
'db' : {
| 'host' : ' | 127.0.0.1'
}
}
|
abougouffa/node-gyp | gyp/pylib/gyp/easy_xml_test.py | Python | mit | 3,271 | 0.008254 | #!/usr/bin/env python2
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Unit tests for the easy_xml.py file. """
import gyp.easy_xml as easy_xml
import unittest
import StringIO
class TestSequenceFunctions... | ent',
['Parent1',
['Child']
],
['Parent2']
]
],
pretty=True),
| '<?xml version="1.0" encoding="utf-8"?>\n'
'<test3>\n'
' <GrandParent>\n'
' <Parent1>\n'
' <Child/>\n'
' </Parent1>\n'
' <Parent2/>\n'
' </GrandParent>\n'
'</test3>\n')
def test_EasyXml_complex(self):
# We want to create:
target = (
... |
gangadhar-kadam/verve_test_erp | erpnext/shopping_cart/test_shopping_cart.py | Python | agpl-3.0 | 7,585 | 0.026236 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from erpnext.shopping_cart import get_quotation, set_item_in_cart
class TestShoppingCart(unittest.TestCase):
"""
Note:... | _title": "_Test Cart Lead Address",
"address_type": "Office",
"city": "_Test City",
"country": "United States",
"lead": lead.name,
"lead_name": "_Test Website Lead",
"is_primary_address": 1,
"phone": "+91 0000000000"
}).insert(ignore_permissions=True)
frappe.get_doc({
"doctype": "Address",
... |
"address_type": "Personal",
"city": "_Test City",
"country": "India",
"lead": lead.name,
"lead_name": "_Test Website Lead",
"phone": "+91 0000000000"
}).insert(ignore_permissions=True)
def remove_all_items_from_cart(self):
quotation = get_quotation()
quotation.set("items", [])
quotation.s... |
portfoliome/pgawedge | pgawedge/ddl.py | Python | mit | 509 | 0 | """
Compiler objects for p | ostgres data definition langua | ge.
"""
from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext.compiler import compiles
class CreateTableAs(Executable, ClauseElement):
def __init__(self, name, query):
self.name = name
self.query = query
@compiles(CreateTableAs, "postgresql")
def _create_table_as(... |
home-assistant/home-assistant | homeassistant/components/hassio/sensor.py | Python | apache-2.0 | 3,165 | 0 | """Sensor platform for Hass.io addons."""
from __future__ import annotations
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE
from homeassistant.core impor... | for addon in coordinator.data[DATA_KEY_ADDONS].values():
for entity_description in ADDON_ENTITY_DESCRIPTIONS:
entities.append(
HassioAddonSensor(
addon=addon,
| coordinator=coordinator,
entity_description=entity_description,
)
)
if coordinator.is_hass_os:
for entity_description in OS_ENTITY_DESCRIPTIONS:
entities.append(
HassioOSSensor(
coordinator=coordinator... |
bumper-app/bumper-bianca | bianca/cas_manager.py | Python | mit | 7,075 | 0.033074 | """
file: cas_manager.py
authors: Christoffer Rosen <[email protected]>
date: Jan. 2014
description: This module contains the CAS_manager class, which is a thread that continously checks if there
is work that needs to | be done. Also contains supporting classes of Worker and ThreadPool used by
the CAS_Manager.
"""
from analyzer.analyzer import *
from ingest | er.ingester import *
from orm.repository import *
import calendar # to convert datetime to unix time
from caslogging import logging
from queue import *
import threading
import time
from monthdelta import *
BACKGROUND_INTERVAL = 60 # wait 1 minutes
class CAS_Manager(threading.Thread):
"""
Thread that continiously ... |
SimpleTax/merchant | example/app/urls.py | Python | bsd-3-clause | 2,389 | 0.005442 |
from django.conf.urls import *
from billing import get_integration
google_checkout_obj = get_integration("google_checkout")
pay_pal_obj = get_integration("pay_pal")
amazon_fps_obj = get_integration("fps")
fps_recur_obj = get_integration("fps")
world_pay_o | bj = get_integration("world_pay")
braintree_obj = get_integratio | n("braintree_payments")
stripe_obj = get_integration("stripe_example")
samurai_obj = get_integration("samurai_example")
urlpatterns = patterns('app.views',
url(r'^$', 'index', name='app_index'),
url(r'^authorize/$', 'authorize', name='app_authorize'),
url(r'^paypal/$', 'paypal', name='app_paypal'),
url... |
thismachinechills/minesqeeper | mines_pyglet.py | Python | gpl-3.0 | 4,042 | 0.026719 | import pyglet
from random import random as r
from board import Board
from math import floor
cursor = None
xi, yi = 30, 30
x, y = xi, yi
lvl = 5
starts = True
mines = Board(xi, yi, lvl)
flag_mode = False
brd = {(_x,_y) for _x in range(x) for _y in range(y)}
scale = 20
black = 0, 0, 0, 255
white = 255, 255, 255
pur... | board.unclicked_squares:
draw_square(sq, scale, unclicked_sq)
def get_visible_sqs(board):
draw_these_nums = board.numbers.keys() - board.unclicked_squares
draw_these_zeros = board.blan | k_board - board.unclicked_squares
return draw_these_nums, draw_these_zeros
def update_title(dt, board):
if not board.start:
return
if board.round:
board.time += 1
str_mines = "Mines: " + str(len(board.bombs))
str_flags = "Flags: " + str(len(board.flags))
str_time = "Time: " + str(board.time)
window.set_c... |
denys-duchier/Scolar | sco_bulletins_json.py | Python | gpl-2.0 | 13,221 | 0.011951 | # -*- mode: python -*-
# -*- coding: iso8859-15 -*-
##############################################################################
#
# Gestion scolarite IUT
#
# Copyright (c) 2001 - 2013 Emmanuel Viennet. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the term... | xml_with_decisions=False, # inclue les decisions même si non publiées
version='long'
):
"""Dictionnaire representant les informations _publiees_ du bulletin de notes
Utilisé pour JSON, devrait l'être aussi pour XML. (todo)
"""
d = {}
sem = context.get_formsemestre(formseme... | e = ''
else:
docdate = datetime.datetime.now().isoformat()
d.update( etudid=etudid, formsemestre_id=formsemestre_id,
date=docdate,
publie=published,
etape_apo=sem['etape_apo'] or '',
etape_apo2=sem['etape_apo2'] or '',
etape_apo3... |
Rapptz/discord.py | discord/types/activity.py | Python | mit | 2,827 | 0 | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... | animated: bool
class ActivityEmoji(_ActivityEmojiOptional):
name: str
class ActivityButton(TypedDict):
label: str
url: str
class _SendableActivityOptional(TypedDict, total=False):
url: Optional[str]
ActivityType = Literal[0, 1, 2, 4, 5]
class SendableActivity(_SendableActivityOptional):
n... | te: Optional[str]
details: Optional[str]
timestamps: ActivityTimestamps
assets: ActivityAssets
party: ActivityParty
application_id: Snowflake
flags: int
emoji: Optional[ActivityEmoji]
secrets: ActivitySecrets
session_id: Optional[str]
instance: bool
buttons: List[ActivityButt... |
antb/TPT----My-old-mod | src/python/stdlib/test/test_sax.py | Python | gpl-2.0 | 26,333 | 0.001443 | # regression test for SAX 2.0 -*- coding: utf-8 -*-
# $Id: test_sax.py 86637 2010-11-21 13:34:58Z ezio.melotti $
from xml.sax import make_parser, ContentHandler, \
SAXException, SAXReaderNotAvailable, SAXParseException
try:
make_parser()
except SAXReaderNotAvailable:
# don't try ... | le\" quotes"),
"\"Includes 'single' and "double" quotes\"")
# ===== make_parser
def test_make_parser(self):
# Creating a parser should succeed - it should fall back
# to the expatreader
p = make_parser(['xml.parsers.no_such_parser'])
# ===== XMLGener... | en = XMLGenerator(result)
gen.startDocument()
gen.startElement("doc", {})
gen.endElement("doc")
gen.endDocument()
self.assertEqual(result.getvalue(), start + "<doc></doc>")
def test_xmlgen_content(self):
result = StringIO()
gen = XMLGenerator(result)
... |
YufeiZhang/Principles-of-Programming-Python-3 | Labs/lab2/cycloidal_curves.py | Python | gpl-3.0 | 1,590 | 0.050943 | from turtle import *
from math import *
from os import system
def save():
getcanvas().postscript(file=name+".ps")
system("ps2pdf "+name+".ps "+name+".pdf")
def quit():
Screen().bye()
def hypotrochoid(R, r, d, iteration):
x, y, up = 0, 0, 1
penup(); fillcolor("green")
while iteration:
theta = iteration/... | = 5
end_fill()
def epitrochoid(R, r, d, iteration):
x, y, up = 0, 0, 1
penup(); fillcolor("green")
while iteration:
theta = iteration/180*pi
x = (R+ | r) * cos(theta) - d * cos((R+r)/r*theta)
y = (R+r) * sin(theta) - d * sin((R+r)/r*theta)
goto(x,y)
if up: pendown(); begin_fill(); up = 0
iteration -= 5
end_fill();
def main():
tp = textinput("Hypotrochoid or Epitrochoid","provide no input for an Epitrochoid, and any input for a Hypotrochoid")
if tp: tp... |
sebinthomas/pyvarnam | pyvarnam/library.py | Python | mit | 3,238 | 0.002471 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
""" Internal library class which holds all the bound functions
"""
# TODO : Comments,docstring, tests,code..
import ctypes as C
from ctypes.util import find_library
import os
import sys
from warnings import warn
from .utils import *
from .varnam_defs import *
class Inte... | riable and error code
self.__status = (0, '')
# Windowsine avaganikkan paadilello !
if sys.platform == 'win32':
libfunc = C.windll
self.libcallback = C.WINFUNCTYPE
else:
libfunc = C.cdll
self.libcallback = C.CFUNCTYPE
# Hard | coding a shared library's path during dev time is
# preferred by ctypes manual than using ctypes.util.find_library()
getlib = self.find_path()
if getlib is None:
msg = "Cannot load library. Are you sure varnam was installed correctly ?"
raise VarnamLibraryLoadErr... |
scylladb/scylla-cluster-tests | sdcm/results_analyze/base.py | Python | agpl-3.0 | 8,871 | 0.003269 | from test_lib.utils import get_data_by_path
class __DEFAULT__: # pylint: disable=invalid-name,too-few-public-methods
pass
class ClassBase:
"""
This class that is meant to be used as base for class that could be stored or loaded (in ES or any other backend)
"""
_es_data_mapping = {}
_data_ty... | while instances:
current_instance, data_path, es_data_path = instances.pop()
for data_name, data_instance in current_instance.__dict__.items():
if current_instance.__annotations__.get(data_name, None) is None: # pyl | int: disable=no-member
continue
es_data_name = current_instance._es_data_mapping.get( # pylint: disable=protected-access
data_name, None)
if es_data_name is None:
es_data_name = es_data_path + [data_name]
elif e... |
NetX-lab/RepNet | exp_code/0_setiplist.py | Python | apache-2.0 | 1,777 | 0.013506 | import os
serverA = open('serverlistA.list', 'r')
serverB = open('serverlistB.list', 'r')
numA = int(serverA.readline())
numB = i | nt( | serverB.readline())
iplistA = open('iplistA', 'w')
iplistB = open('iplistB', 'w')
sshconfig = open('/Users/iqua/.ssh/config', 'w')
csshconfig = open('/etc/clusters', 'w')
csshconfig.write("rackA ")
for i in range(numA):
port = int(serverA.readline())
content = "host A" + str(port) + "\n Hostname sing.cse.ust.hk... |
AIFDR/inasafe | safe/messaging/item/exceptions.py | Python | gpl-3.0 | 712 | 0 | """
InaSAFE Disaster risk assessment tool developed by AusAid - **Exceptions**
Contact : [email protected]
.. note:: 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 Softwar | e Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '[email protected]'
__revision__ = '$Format:%H$'
__date__ = '11/06/2013'
__copyright__ = ('Copyright 2012, Australia | Indonesia Facility for '
'Disaster Reduction')
class InvalidMessageItemError(Exception):
"""Custom exception for when the passed MessageElement is invalid."""
pass
|
tswicegood/steinie | examples/simple.py | Python | apache-2.0 | 269 | 0.007435 | import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from steinie import Stein | ie
app = Steinie()
@app.get("/")
def | handle(request, response):
return "Hello, World! This is Steinie.\n"
if __name__ == "__main__":
app.run()
|
isharacomix/tvtgj | core/log.py | Python | gpl-3.0 | 311 | 0.016077 |
import time
logfile = None
is_logging = False
def log(s):
global logfile
global is_logging
if is_logging:
if not logfile:
logfile = open("log_%d | "%time.time(),"w")
logfile.w | rite(s+"\n")
def toggle(flag):
global is_logging
is_logging = True if flag else False
|
devops2014/djangosite | django/contrib/gis/tests/geoapp/tests.py | Python | bsd-3-clause | 41,661 | 0.002664 | from __future__ import unicode_literals
import re
from tempfile import NamedTemporaryFile
from django.contrib.gis import gdal
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import (
no_oracle, oracle, postgis, spatialite,
)
from django.core.management import call_command
from dja... | (-98.493183 29.424170)', 4326), 41157))
# )
# FROM DUAL;
nad_wkt = 'POINT (300662.034646583 5416427.45974934)'
nad_srid = 41157
else:
# San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084)
# Used ogr.py in gdal 1.4.1... | this transform
nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)'
nad_srid = 3084
# Constructing & querying with a point from a different SRID. Oracle
# `SDO_OVERLAPBDYINTERSECT` operates differently from
# `ST_Intersects`, so contains is used instead.
... |
davidfergusonaz/davidtest | config57.py | Python | mit | 146 | 0.006849 | provider "aws" {
access_key = "AKIAIYBPEWJ6JU5UNKZQ"
secret | _key = "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"
region = "${va | r.region}"
}
|
noemis-fr/old-custom | e3z_compute_parent_left_right/__init__.py | Python | agpl-3.0 | 997 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the 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 Affero General Public Licen... | GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import wizard
|
tfroehlich82/koalixcrm | crm_core/__init__.py | Python | bsd-3-clause | 64 | 0.015625 | """
This mod | ule provides the Koalix CRM core functionality
""" | |
Konubinix/lazygal | lazygaltest/test_conf.py | Python | gpl-2.0 | 4,698 | 0.000426 | # Lazygal, a lazy static web gallery generator.
# Copyright (C) 2011-2012 Alexandre Rossi <[email protected]>
#
# This program is free software | ; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe | d 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,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Genera... |
chrys87/fenrir | src/fenrirscreenreader/commands/onSwitchApplicationProfile/inactive/bash.py | Python | lgpl-3.0 | 853 | 0.01524 | #!/bin/python
# -*- coding: utf-8 -*-
# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributers.
from fenrirscreenreader.core import debug
class command():
def __init__(self):
pass
def initialize(self, environment):
self.en | v = environment
def shutdown(self):
pass
def getDescription(self):
return 'No description found'
def load(self):
print('--------------')
print( | 'bash')
print('load new',self.env['screen']['newApplication'])
print('--------------')
def unload(self):
print('--------------')
print('bash')
print('unload old',self.env['screen']['oldApplication'])
print('--------------')
... |
codepotpl/codepot-backend | codepot/views/purchases/exceptions.py | Python | mit | 1,512 | 0.005952 | from codepot.exceptions import CodepotException
class PurchaseException(CodepotException):
pass
class UserPurchaseNotFoundException(PurchaseException):
def __init__(self, user_id):
super().__init__('No purchase found for user with ID: {}.'.format(user_id), 300)
class PromoCodeForPurchaseNotFoundEx... | rchase_id):
super().__init__('User: {} already has purchase: {}.'.format(user_id, purchase_id), 304)
class ProductNotFoundException(PurchaseException):
def __init__(self, product_id):
super().__init__('Product for ID: {}, not found.'.format(product_id), 305)
class ProductInactiveException(Purcha... | ().__init__('Product for ID: {} is not active.'.format(product_id), 306)
class InvalidPaymentInfoException(PurchaseException):
def __init__(self, message):
super().__init__(message, 307)
|
shanzi/tchelper | api/migrations/0003_auto_20150326_1435.py | Python | bsd-2-clause | 560 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migr | ation):
dependencies = [
('api', '0002_auto_20150326_1433'),
]
operations = [
migrations.RemoveField(
model_name='problem',
name='id',
),
migrations.AlterField(
model_name='problem',
name='problemId',
field=models.... | True,
),
]
|
joke2k/faker | faker/providers/lorem/de_DE/__init__.py | Python | mit | 9,092 | 0 | from .. import Provider as LoremProvider
class Provider(LoremProvider):
"""Implement lorem provider for ``de_DE`` locale.
Word list is based on the source below, and some words have been removed
because of some duplications.
Sources:
- https://www.gut1.de/grundwortschatz/grundwortschatz-500/
... | früh",
"früher",
"Fuß",
"Fußball",
"fährt",
"führen",
"fünf",
"für",
"gab",
"ganz",
"g | ar",
"Garten",
"geben",
"Geburtstag",
"gefährlich",
"gegen",
"gehen",
"gehören",
"gelb",
"Geld",
"genau",
"gerade",
"gern",
"Geschenk",
"Geschichte",
"Gesicht",
"gestern",
"gesund",
... |
MingdaMingda/WE060001-NMJKL | TT_io_weixin_auth.py | Python | unlicense | 1,327 | 0.008289 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging
import io_weixin_auth
def test_get_user_token_by_code():
#code = '0010bc8ec77f6972b66ad5cb143ceb4i'
code = '041709e7b1cff6ece362b81e8e071a1j'
token_info = io_weixin_auth.get_user_token_by_code(code)
return token_info
def test_... | en(token_info['openid'], token_info['access_token'])
if (not user_info is Non | e) and ('nickname' in user_info):
logging.info('openid: %s' % user_info['openid'])
logging.info('nickname: %s' % user_info['nickname'])
logging.info('headimgurl: %s' % user_info['headimgurl'])
else:
logging.error('bad token')
logging.info('Done')
#/* vim: set ai exp... |
coco-project/contract | src/coco/contract/errors.py | Python | bsd-3-clause | 3,806 | 0.001314 | class Error(Exception):
"""
Base error for all coco exceptions.
Only when throwing an instance of this error one can be sure it
will get caught by the application. All other exceptions might
be unhandled leading to crashes.
"""
pass
class BackendError(Error):
"""
Base error for... | or pass up the stack. Every error thrown from the backend
should be wrapped.
"""
pass
class Co | nnectionError(BackendError):
"""
Generic backend error meant to be thrown then a connection to the backend cannot be established.
"""
pass
class NotFoundError(BackendError):
"""
Generic (backend record) not found error.
Error meant to be raised when an operation can not be performed
... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractWwwFruitydeerCom.py | Python | bsd-3-clause | 548 | 0.034672 |
def extra | ctWwwFruitydeerCom(item):
'''
Parser for 'www.fruitydeer.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', ... | =tl_type)
return False
|
andris210296/andris-projeto | backend/venv/test/lib/python2.7/site-packages/gaeforms/__init__.py | Python | mit | 20 | 0.05 | __version__ | = '0.14' | |
alex/djangobench | djangobench/benchmarks/query_values/benchmark.py | Python | bsd-3-clause | 254 | 0.015748 | from djangobench.utils import run_benchmark
from query_values.mode | ls import Book
def benchmark():
list(Book.objects.values('title'))
run_benchmark(
benchmark,
| meta = {
'description': 'A simple Model.objects.values() call.',
}
)
|
jmgc/swift | utils/gyb_syntax_support/DeclNodes.py | Python | apache-2.0 | 37,155 | 0.000081 | # flake8: noqa I201
from .Child import Child
from .Node import Node
DECL_NODES = [
# type-assignment -> '=' type
Node('TypeInitializerClause', kind='Syntax',
children=[
Child('Equal', kind='EqualToken'),
Child('Value', kind='Type'),
]),
# typealias-declaration ... | enToken')
]),
Node('PoundWarningDecl', kind='Decl',
traits=['Par | enthesized'],
children=[
Child('PoundWarning', kind='PoundWarningToken'),
Child('LeftParen', kind='LeftParenToken'),
Child('Message', kind='StringLiteralExpr'),
Child('RightParen', kind='RightParenToken')
]),
Node('PoundSourceLocation', kind='De... |
martinschaef/grovepi | grovepi.py | Python | mit | 13,742 | 0.016737 | # grovepi.py
# v1.2.2
# This file provides the basic functions for using the GrovePi
#
# Karan Nayan
# Initial Date: 13 Feb 2014
# Last Updated: 22 Jan 2015
# http://www.dexterindustries.com/
#
# These files have been made available online through
# a Creative Commons Attribution-ShareAlike 3.0 license.
# (... |
def analogRead(pin):
bus.write_i2c_block_data(address, 1, aRead_cmd + [pin, unused, unused])
#time.sleep(.001)
bus.read_byte(address)
number = bus.read_i2c_block_data(address, 1)
return number[1] * 256 + number[2]
# Write PWM
def analogWrite(pin, value):
write_i2c_block(address, aWrite_cmd + [pin, v... | temp in Celsius from Grove Temperature Sensor
def temp(pin, model = '1.0'):
# each of the sensor revisions use different thermistors, each with their own B value constant
if model == '1.2':
bValue = 4250 # sensor v1.2 uses thermistor ??? (assuming NCP18WF104F03RC until SeeedStudio clarifies)
elif model == '1... |
lakshmi-kannan/st2 | st2api/tests/unit/controllers/v1/test_packs.py | Python | apache-2.0 | 10,101 | 0.002079 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | rtTrue('policy_ty | pes' in resp.json)
self.assertTrue('policies' in resp.json)
self.assertTrue('configs' in resp.json)
self.assertTrue(resp.json['actions'] >= 3)
self.assertTrue(resp.json['configs'] >= 3)
# Register resources from a specific pack
resp = self.app.post_json('/v1/packs/regis... |
lordappsec/ooni-probe | scripts/fabfile.py | Python | bsd-2-clause | 3,381 | 0.004734 | #-*- coding: utf-8 -*-
#
# :authors: Arturo Filastò, Isis Lovecruft
# :license: see included LICENSE file
import os
import sys
import yaml
import xmlrpclib
from StringIO import StringIO
from fabric.operations import get
from fabric.api import run, cd, sudo, env
api_auth = {}
# Set these values
api_auth['Username'] =... | nodeid)
api_server = xmlrpclib.ServerProxy('https://www.planet-lab.org/PLCAPI/')
node_filter = {'node_id': node_id}
return_fields = ['hostname', 'site_id']
nodes = api_server.GetNodes(api_auth, node_filter, return_fields)
print 'Adding nodes %s' % nodes
api_s | erver.AddNode(api_auth, node_id, slice_name)
def deployooniprobe(distro="debian"):
"""
This is used to deploy ooni-probe on debian based systems.
"""
run("git clone https://git.torproject.org/ooni-probe.git ooni-probe")
cd("ooni-probe")
if distro == "debian":
sudo("apt-get install git-c... |
pyshop/pyjobs | src/adverts/migrations/0012_auto_20151214_1910.py | Python | mit | 1,060 | 0.001887 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.d | b import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('adverts', '0011_auto_20151210_1116'),
]
operations = [
migrations.CreateModel(
name='UserActivationKey',
fields=[
('id', models.A... |
],
),
migrations.RemoveField(
model_name='userprofile',
name='user',
),
migrations.RemoveField(
model_name='user',
name='activation_key',
),
migrations.DeleteModel(
name='UserProfile',
),
... |
pebble/flotilla | src/flotilla/agent/db.py | Python | mit | 4,650 | 0 | import logging
import json
import time
from collections import defaultdict
from flotilla.model import FlotillaServiceRevision, FlotillaUnit, \
GLOBAL_ASSIGNMENT, GLOBAL_ASSIGNMENT_SHARDS
from Crypto.Cipher import AES
logger = logging.getLogger('flotilla')
class FlotillaAgentDynamo(object):
"""Database intera... | ct(unit_status)
data['service'] = self._service
data['instance_id'] = self._id
data['status_time'] = time.time()
self._status.put_item(data=data, overwrite=True)
logger.info('Store | d status of %s units as %s.', len(unit_status),
self._id)
def get_assignments(self):
assignments = self._assignments.batch_get([
{'instance_id': self._id}, {'instance_id': self._global_id}])
assigned_revisions = [assignment['assignment'] for assignment in
... |
probcomp/bayeslite | src/backends/nig_normal.py | Python | apache-2.0 | 19,474 | 0.001643 | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | """
import math
import random
import bayeslite.backend
import bayeslite.core as core
from bayeslite.backend import baye | sdb_backend_version
from bayeslite.exception import BQLError
from bayeslite.math_util import logmeanexp
from bayeslite.sqlite3_util import sqlite3_quote_name
from bayeslite.util import cursor_value
nig_normal_schema_1 = '''
INSERT INTO bayesdb_backend (name, version) VALUES ('nig_normal', 1);
CREATE TABLE bayesdb_nig... |
siddhism/GCompris-qt | tools/l10n-fetch-po-files.py | Python | gpl-3.0 | 1,862 | 0.003222 | import os
import re
import subprocess
# Copied from Trojita
"""Fetch the .po files from KDE's SVN for GCompris
Run me from GCompris's top-level directory.
"""
SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/"
SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po"
OUT | PUT_PO_PATH = "./po/"
OUTPUT_PO_PATTERN = "gcompris_%s.po"
fixer = re.compile(r'^#~\| ', re.MULTILINE)
re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE)
re_empty_line = re.compile('^$', re.MULTILINE)
re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') |
if not os.path.exists(OUTPUT_PO_PATH):
os.mkdir(OUTPUT_PO_PATH)
all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'],
stderr=subprocess.STDOUT)
all_languages = [x.strip() for x in all_languages.split("\n") if len(x)]
all_languages.remove("x-test")
f... |
AdriaGS/MTP-Group-C | Single Mode/Semi-Final/deviceTX_wC2.py | Python | gpl-2.0 | 8,154 | 0.035565 | try:
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
from math import *
import time
import spidev
import sys
import os.path
import numpy
import pickle
import sqlite3
import mat4py as m4p
import os
def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dicti... | we have not received anything we retransmit the handshake packet
if((time.time() + 0.2 | ) > timeout):
print("No Handshake ACK received resending message")
radio_Tx.write(str(numberofPackets) + "," + str(n))
timeout = time.time() + time_ack
#We iterate over every packet to be sent
dec_ready = 0
for message in packets:
flag = chr(ord(original_flag_data) + flag_n)
message2Send = ... |
giacomov/3ML | threeML/plugins/DispersionSpectrumLike.py | Python | bsd-3-clause | 8,596 | 0.002792 | import copy
import pandas as pd
from threeML.plugins.SpectrumLike import SpectrumLike
from threeML.utils.OGIP.response import InstrumentResponse
from threeML.utils.spectrum.binned_spectrum import (
BinnedSpectrumWithDispersion,
ChannelSet,
)
__instrument_name = "General binned spectral data with energy dispe... | served_spectrum)
if self._background_spectrum is not None:
| info["bak"] = copy.copy(self._background_spectrum)
info["rsp"] = copy.copy(self._rsp)
return info
def display_rsp(self):
"""
Display the currently loaded full response matrix, i.e., RMF and ARF convolved
:return:
"""
self._rsp.plot_matrix()
@property
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.