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 |
|---|---|---|---|---|---|---|---|---|
Art3mk4/python | process/pid.py | Python | gpl-3.0 | 58 | 0.017241 | import os
print os.p | ath.dirname(os.path.abspath(__file__)) | |
aquadrop/solr_py | client/find_multi_intention.py | Python | gpl-3.0 | 1,346 | 0.00075 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import _ | uniout
import sys
import csv
reload(sys)
sys.setdefaultencoding("utf-8")
data_path = '../data/business/business_train_v7'
classes = list()
inputs = dict()
results = dict()
if __name__ == '__main__':
with open(data_path, 'r') as f:
reader = csv.reader(f, delimiter='\t')
for line in reader:
... | print("classes:", _uniout.unescape(str(classes), 'utf8'))
with open(data_path, 'r') as f:
reader = csv.reader(f, delimiter='\t')
for line in reader:
a = line[0]
b = line[1]
a_slots = a.split(',')
if b not in inputs:
inputs[b] = []
... |
dbbhattacharya/kitsune | vendor/packages/selenium/py/selenium/webdriver/remote/webdriver.py | Python | bsd-3-clause | 25,947 | 0.00185 | # Copyright 2008-2014 Software freedom conservancy
#
# 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 ... | tup behavior.
"""
pass
def stop_client(self):
"""
| Called after executing a quit command. This method may be overridden
to define custom shutdown behavior.
"""
pass
def start_session(self, desired_capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_... |
conversationai/wikidetox | experimental/conversation_go_awry/prediction_utils/configure.py | Python | apache-2.0 | 2,644 | 0.016263 | """
Copyright 2017 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
dis... | ]
QUESTIONS[new_key].append({'action_id': action, 'question_type': np.argmin(val['normy_cluster_dist_vector'])})
with open("data/user_features.json") as f:
inp = json.load(f)
user | _features = {}
for conv, users in inp:
user_features[conv] = users
ARGS = [STATUS, ASPECTS, attacker_profile_ASPECTS, LEXICONS, QUESTIONS, UNIGRAMS_LIST, BIGRAMS_LIST]
return user_features, ARGS
|
twallace27603/robot_army | wheels.py | Python | gpl-3.0 | 3,797 | 0.008954 | from enum import Enum
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
import time
import atexit
Direction = Enum('Forward','Reverse','Spin','Left','Right','None')
class Wheels:
def __init__(self):
self.lc = 100 #Loop count
self.ld = .02 #Loop delay
self.mh = Adafruit_Mot... | )
self.speed = finalSpeed
self.direction = direction
def correct(self,direction,bump=20):
wheel = self.rightWheel
if(direction == Direction.Right):
wheel = self.leftWheel
wheel.setSpeed(self.speed + bump)
time.sleep(.25)
wheel.setSpeed(self.speed)... | def pulse(self,seconds=.25,bump=20):
self.rightWheel.setSpeed(self.speed + bump)
self.leftWheel.setSpeed(self.speed + bump)
time.sleep(seconds)
self.rightWheel.setSpeed(self.speed)
self.leftWheel.setSpeed(self.speed)
def test(self):
print("Forward!")
self.... |
huntxu/neutron | neutron/db/l3_dvr_ha_scheduler_db.py | Python | apache-2.0 | 1,967 | 0 | # Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
# 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/lic... | Rsch_db_mixin,
l3_ha_sch_db.L3_HA_scheduler_db_mixin):
def get_dvr_routers_to_remove(self, context, port_id):
"""Returns info about which routers should be removed
| In case dvr serviceable port was deleted we need to check
if any dvr routers should be removed from l3 agent on port's host
"""
remove_router_info = super(L3_DVR_HA_scheduler_db_mixin,
self).get_dvr_routers_to_remove(context,
... |
ianalis/treepy | treepy/plotting.py | Python | mit | 2,994 | 0.008016 | # Copyright (c) 2015 Christian Alis
#
# See the file LICENSE for copying permission.
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from urllib import unquote
from scipy.stats import zscore
def plot_corr(results):
"""
Plot t... | """
fig, ax = plt.subplots(figsize=(6,10)
| #subplot_kw=dict(left=0.05, right=0.95,
# bottom=0.03, top=0.97)
)
ax.barh(np.arange(len(results))+0.5, [r['r'] for r in results[::-1]], 0.3,
label='r')
ax.barh(range(len(results)), [r['p_bh']['double'] for r in resu... |
siosio/intellij-community | python/testData/optimizeImports/moduleLevelDunderWithImportFromFutureAbove.py | Python | apache-2.0 | 236 | 0.004237 | from __future__ import print_function
__author__ = "akniazev"
from datetime import date
from sys import path |
from foo import bar
from collections import OrderedDict
from datetime import time
date(1, 1, 1)
time(1)
OrderedDict()
bar( | ) |
liu-jian/seos1.0 | test/select_test.py | Python | apache-2.0 | 1,329 | 0.027293 | #!/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import json
import requests
url = "http://127.0.0.1:3000/api"
#登录并获取token
def login(username,password):
rep_url = "%s/login?username=%s&passwd=%s" % (url,username,password)
r = requests.get(rep | _url)
result = json.loads(r.content)
if result['code'] == 0:
token = result["authorization"]
| return json.dumps({'code':0,'token':token})
else:
return json.dumps({'code':1,'errmsg':result['errmsg']})
def rpc():
res=login('admin','123456')
result = json.loads(res)
if result['code'] ==0:
token=result['token']
headers = {'content-type': 'appli... |
irzaip/cipi | cp_speak.py | Python | lgpl-3.0 | 7,663 | 0.033146 | #!/usr/bin/python
import commons
from espeak import espeak
import mosquitto
import subprocess
from os import listdir
import random
from os.path import join
from twython import Twython
import ConfigParser
#import time
import moc
import math
from datetime import *
from pytz import timezone
import calendar
from dateutil.r... | qttc.on_log = on_log
mqttc.connect("127.0. | 0.1", 1883, 60)
#mqttc.subscribe("string", 0)
#mqttc.subscribe(("tuple", 1))
#mqttc.subscribe([("list0", 0), ("list1", 1)])
#Speak agenda
retrieve_agenda()
mycal = get_cal()
today_event()
while True:
mqttc.loop()
#loop reminder for every 5 minutes
btime = commons.getmillis()
if btime-atime > 300000:
at... |
mangosmoothie/dnla-playlists | dnla-playlists/playlists.py | Python | gpl-3.0 | 7,175 | 0.002927 | import mutagen
import os
import re
import sys
from optparse import OptionParser
music_file_exts = ['.mp3', '.wav', '.ogg']
seconds_re = re.compile('(\d+)(\.\d+)? seconds')
def main(argv):
(options, args) = build_parser().parse_args(argv)
validate_options(options)
print('playlist(s) will be written to ', ... | n p.items:
p_out.write(p.get_out_str(i, outdir))
def all_pass(x, predicates):
for p in predicates:
if not p(x):
return False
return True
def extract_metadata(path, extended=False):
meta = {'path': path, 'ti | tle': '', 'artist': '', 'seconds': '0'}
if extended:
f = mutagen.File(path)
if f:
match = re.search(seconds_re, f.info.pprint())
meta['seconds'] = match.group(1) if match else '0'
else:
f = {}
meta['title'] = f.get('title',
... |
eoinmurray/icarus | Icarus/Algorithms/__init__.py | Python | mit | 101 | 0.009901 | from aut | o import auto
from basis import basis
from cross import cross
from pow | er_dep import power_dep |
coolbombom/CouchPotatoServer | couchpotato/core/downloaders/sabnzbd/main.py | Python | gpl-3.0 | 4,865 | 0.007605 | from couchpotato.core.downloaders.base import Downloader, StatusList
from couchpotato.core.helpers.encoding import tryUrlencode, ss
from couchpotato.core.helpers.variable import cleanHost, mergeDicts
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import timedelta
from ur... | g.error('Failed deleting: %s', traceback.format_exc(0))
| return False
return True
def call(self, request_params, use_json = True, **kwargs):
url = cleanHost(self.conf('host')) + 'api?' + tryUrlencode(mergeDicts(request_params, {
'apikey': self.conf('api_key'),
'output': 'json'
}))
data = self.urlopen(url, timeou... |
mariecpereira/IA369Z | deliver/ia870/iaskelmrec.py | Python | mit | 482 | 0.018672 | # -*- encoding: utf-8 -*-
# Module iaskel | mrec
from numpy import *
def iaskelmrec(f, B=None):
from iabinary import iabinary
from iaintersec import iaintersec
from iadil import iadil
from iaunion import iaunion
| from iasecross import iasecross
if B is None:
B = iasecross(None)
y = iabinary( iaintersec(f, 0))
for r in range(max(ravel(f)),1,-1):
y = iadil( iaunion(y,iabinary(f,r)), B)
y = iaunion(y, iabinary(f,1))
return y
|
xuwenbao/suds | suds/client.py | Python | lgpl-3.0 | 26,012 | 0.002422 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) 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.
#
# This program is distributed in the hope that it will ... | suds object much like the
items() method works on I{dict}.
@param sobject: A suds object
@type sobject: L{Object}
@return: A list of items contained in I{sobject}.
@rtype: [(key, value),...]
"""
return sudsobject.items(sobject)
@classmetho | d
def dict(cls, sobject):
"""
Convert a sudsobject into a dictionary.
@param sobject: A suds object
@type sobject: L{Object}
@return: A python dictionary containing the
items contained in I{sobject}.
@rtype: dict
"""
return sudsobject.asdic... |
wscullin/spack | var/spack/repos/builtin/packages/lzma/package.py | Python | lgpl-2.1 | 1,935 | 0.000517 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | 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.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WAR... | # You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Lz... |
jeffbr13/python-ted | ted/client.py | Python | mpl-2.0 | 7,305 | 0.003012 | from collections import namedtuple
import logging
import re
from datetime import datetime, timedelta
from daterange import DateRange
from icalendar import | Calendar, Event
from lxml import html
from requests import Session
from .aspx_session import ASPXSession
from .course import Course
class Client:
"""
Main interface for interacting with T@Ed.
Attributes:
Client.session
Client.aspx_session
Client.courses
Client.week_dateranges
>>> ... | _url = 'https://www.ted.is.ed.ac.uk/UOE1314_SWS/default.aspx'
weeklist_url = 'https://www.ted.is.ed.ac.uk/UOE1314_SWS/weeklist.asp'
def __init__(self):
"""
Initialise T@Ed session and download course list.
"""
self.session = Session()
# Get ASPX session variables from ... |
xkmato/casepro | casepro/urls.py | Python | bsd-3-clause | 1,472 | 0.001359 | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.views import static
from casepro.backend import get_backend
from casepro.utils.views import PartialTemplate
urlpatterns = [
url(r'', include('casepro.cases.urls')),
... | += backend_urls
if settings.DEBUG: # pragma: no cover
try | :
import debug_toolbar
urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls)))
except ImportError:
pass
urlpatterns = [
url(r'^media/(?P<path>.*)$', static.serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib... |
akx/shoop | shoop_tests/admin/test_picotable.py | Python | agpl-3.0 | 4,680 | 0.003419 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import pytest
from django.contrib.auth import get_user_mode... | ta({"perPage": 100, "page": 1})
assert len(data["items"]) == get_user_model().objects.count()
@pytest.mark.django_db
@pytest.mark.usefixtures("regular_user")
def test_picotable_display(rf, admin_user, regular_user):
pico = get_pico(rf)
data = pico.get_data({"perPage": 100, "page": 1})
for item in data... |
if item["id"] == regular_user.pk:
assert item["is_superuser"] == "-"
@pytest.mark.django_db
@pytest.mark.usefixtures("regular_user")
def test_picotable_sort(rf, admin_user, regular_user):
pico = get_pico(rf)
data = pico.get_data({"perPage": 100, "page": 1, "sort": "-id"})
id = None
... |
hj3938/panda3d | contrib/src/sceneeditor/sePlacer.py | Python | bsd-3-clause | 33,063 | 0.010949 | """ DIRECT Nine DoF Manipulation Panel """
from direct.showbase.DirectObject import DirectObject
from direct.directtools.DirectGlobals import *
from direct.tkwidgets.AppShell import AppShell
from direct.tkwidgets.Dial import AngleDial
from direct.tkwidgets.Floater import Floater
from Tkinter import Button, Menubutton,... | itor.redo)
if SEditor.redoList:
self.redoButton['state'] = 'normal'
else:
self.redoButton['state'] = 'disabled'
self.redoButton | .pack(side = 'left', expand = 0)
self.bind(self.redoButton, 'Redo last operation')
# Create and pack the Pos Controls
posGroup = Pmw.Group(interior,
tag_pyclass = Menubutton,
tag_text = 'Position',
tag_font=(... |
eek6/squeakspace | www/proxy/scripts/proxy/group_quota.py | Python | gpl-3.0 | 2,328 | 0.006873 | import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.proxy.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def post_handler(environ):
query = ht.parse_post_request(environ)
cookies = ht.parse_cookies(env | iron)
user_id = ht.get_required_cookie(cookies, 'user_id')
session_id = ht.get_required_cookie(cookies, 'session_id')
node_name = ht.get_required(query, 'node_name')
group_id = ht.get_required(query, 'group_id')
new_size = ht.convert_int(ht.get_required(query, 'new_size'), 'new_size')
when_spa... | sh')
passphrase = ht.get_optional(query, 'passphrase')
conn = db.connect(config.db_path)
try:
c = db.cursor(conn)
resp = db.change_group_quota(c, user_id, session_id,
node_name, group_id, new_size, when_space_exhausted,
public_key_h... |
yaqiyang/autorest | src/generator/AutoRest.Python.Azure.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/operations/group_operations.py | Python | mit | 3,678 | 0.001903 | # 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 ... | resource_group_name: Resource Group name 'testgroup101'.
:type resource_group_name: str
:param dict custom_headers: headers that will be added to the request
:param bool | raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: :class:`SampleResourceGroup
<fixtures.acceptancetestssubscriptionidapiversion.models.SampleResourceGroup... |
ajduncan/downspout | setup.py | Python | mit | 721 | 0.001387 | #!/usr/bin/env python
from setuptools import setup
install_requires = [
'bandcamp-downloader==0.0.10',
'beautifulsoup4==4.10.0',
'Pafy==0.3.66',
'fudge==1.0.3',
'requests>=2.20.0',
'simplejson==3.6.5',
'slimit==0.8.1',
'stagger',
]
dependency_links = [
'git://github.com/ajduncan/stagger.git@master#... | ame='downspout',
version='v0.0.6',
description='Capture cloud based media for offline merrim | ent.',
license='MIT',
author='Andy Duncan',
author_email='[email protected]',
url='https://github.com/ajduncan/downspout/',
install_requires=install_requires,
dependency_links=dependency_links,
test_suite='tests.runtests'
)
|
zenweasel/pybuilder-djangoexample | pyb_django/catalog/urls.py | Python | bsd-3-clause | 253 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from views import CatalogListView
urlpatterns = patterns('',
| url(r'^$', Catal | ogListView.as_view(), name="list"),
)
|
weld-project/weld | weld-python/weld/grizzly/__init__.py | Python | bsd-3-clause | 105 | 0 |
from weld.grizzly.core.frame import GrizzlyDataFrame
from we | ld.gr | izzly.core.series import GrizzlySeries
|
jordanemedlock/psychtruths | temboo/core/Library/Zendesk/Groups/ListGroups.py | Python | apache-2.0 | 4,462 | 0.005379 | # -*- coding: utf-8 -*-
###############################################################################
#
# ListGroups
# List available groups.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in com... | horeography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class ListGroups(Choreography) | :
def __init__(self, temboo_session):
"""
Create a new instance of the ListGroups Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(ListGroups, self).__init__(temboo_session, '/Library/Zendesk/Groups/ListGroups')
... |
kbiscanic/apt_project | apt/features/kbiscanic/vector_space_similarity.py | Python | apache-2.0 | 815 | 0.001227 | __author__ = 'kbiscanic'
from collections impor | t Counter
from scipy.linalg import norm
from features.karlo.WWO import calc_ic
def _lsa(s):
w = Counter(s)
return {x: w[x] for x in w}
def _lsaic(s):
w = Counte | r(s)
return {x: calc_ic(x) * w[x] for x in w}
def _cosine_sim(da, db):
sol = 0.
for key in set(da.keys()).intersection(db.keys()):
sol += da[key] * db[key]
if sol == 0:
return 0.
return abs(sol / norm(da.values()) / norm(db.values()))
def vector_space_similarity(sa, sb, ic=False)... |
dstufft/sqlalchemy | test/requirements.py | Python | mit | 28,475 | 0.002669 | """Requirements specific to SQLAlchemy's own unit tests.
"""
from sqlalchemy import util
import sys
from sqlalchemy.testing.requirements import SuiteRequirements
from sqlalchemy.testing import exclusions
from sqlalchemy.testing.exclusions import \
skip, \
skip_if,\
only_if,\
only_on,\
fails_... | mysql', '<', (5, 0, 10), 'not supported by database'),
# huh? TODO: implement triggers for PG tests, remove this
no_support('postgresql',
'PG triggers need to be implemented for | tests'),
])
@property
def correlated_outer_joins(self):
"""Target must support an outer join to a subquery which
correlates to the parent."""
return skip_if("oracle", 'Raises "ORA-01799: a column may not be '
'outer-joined to a subquery"')
@property
... |
nirmeshk/oh-mainline | mysite/customs/migrations/0039_auto__add_field_tigrisquerymodel_startid__add_field_tigrisquerymodel_d.py | Python | agpl-3.0 | 26,529 | 0.00769 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'TigrisQueryModel.startid'
db.add_column('customs_tigrisquerymodel', 'startid', self.gf('dj... | 'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '1 | 00'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'customs.bugzillaquerymodel': {
... |
impactlab/eemeter | tests/ee/test_annualized_weather_normal.py | Python | mit | 849 | 0 | import tempfile
import pytest
from numpy.testing import assert_allclose
from eemeter.modeling.formatters import Mode | lDataFormatter
from eemeter.ee.derivatives import annualized_weather_normal
from eemeter.testing.mocks import MockModel, MockWeatherClient
from eemeter.weathe | r import TMY3WeatherSource
@pytest.fixture
def mock_tmy3_weather_source():
tmp_dir = tempfile.mkdtemp()
ws = TMY3WeatherSource("724838", tmp_dir, preload=False)
ws.client = MockWeatherClient()
ws._load_data()
return ws
def test_basic_usage(mock_tmy3_weather_source):
formatter = ModelDataForm... |
nickhargreaves/AfricanSpending | setup.py | Python | mit | 952 | 0 | from setuptools import setup, find_packages
setup(
name='af | ricanspending',
version='1.0',
description="Mapping the money, across the African continent",
long_description='',
classifiers=[],
keywords='',
author='Code for Africa',
author_email='[email protected]',
url='http://www.africanspending.org',
license='MIT',
packages=find_packages... | install_requires=[
"Flask==0.10.1",
"Flask-Assets==0.10",
"Flask-FlatPages==0.5",
"Flask-Script==2.0.5",
"Frozen-Flask==0.11",
"PyYAML==3.11",
"Unidecode==0.04.16",
"awscli==1.4.4",
"cssmin==0.2.0",
"python-dateutil==2.2",
"pytho... |
adamcunnington/OlympianAdmin | cstrike/addons/eventscripts/admin/mods/rpg/perks/long_jump/long_jump.py | Python | gpl-3.0 | 539 | 0.003711 | # <path to game directory>/addons/eventscipts/admin/mods/rpg/perks/
# long_jump/long_jump.py
# by | Adam Cunnington
import ps | yco
psyco.full()
from esutils import players
from rpg import rpg
def player_jump(event_var):
user_ID = int(event_var["userid"])
long_jump_level = rpg.get_level(user_ID, _long_jump)
if long_jump_level == 0:
return
players.Player(user_ID).push(float(long_jump_level * 0.1), 0)
_long_jump = rpg... |
pliniopereira/ccd3 | src/utils/rodafiltros/Leitura_portas.py | Python | gpl-3.0 | 920 | 0 | import glob
import sys
import serial
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = [... | elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupporte... | result.append(port)
except (OSError, serial.SerialException):
pass
return result
|
google/clusterfuzz | src/clusterfuzz/_internal/base/modules.py | Python | apache-2.0 | 2,700 | 0.00963 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | uth_app_engine.app_identity:
auth_app_engine.app_identity | = None
except ImportError:
pass
def fix_module_search_paths():
"""Add directories that we must be able to import from to path."""
root_directory = os.environ['ROOT_DIR']
source_directory = os.path.join(root_directory, 'src')
python_path = os.getenv('PYTHONPATH', '').split(os.pathsep)
third_party_li... |
smlacombe/sageo | app/lib/livestatusconnection.py | Python | gpl-3.0 | 142 | 0.007042 | from app.lib import livestat | us
from app import app
enabled_sites = app.config['SITES']
live = livestatus.MultiSiteConnection(enabled_si | tes)
|
ricardog/raster-project | user-scripts/katia/bii.py | Python | apache-2.0 | 3,202 | 0.002498 | #!/usr/bin/env python
import argparse
import time
import fiona
import multiprocessing
from rasterio.plot import show
import math
import os
import click
#import matlibplot.pyplot as plt
import numpy as np
import numpy.ma as ma
import rasterio
from rasterio.plot import show, show_hist
from projections.rasterset impor... | utils.outfn('katia',
'sr-cs-%s.tif' % suffix)),
'clip_sr': SimpleExpr('clip_sr',
| 'clip(sp_rich, 0, %f)' % sr_max),
'bii_sr': SimpleExpr('bii_sr', 'sp_rich * comp_sim'),
'bii_sr2': SimpleExpr('bii_sr2', 'clip_sr * comp_sim')})
# write out bii raster
bii_rs.write('bii_sr' if args.clip else 'bii_sr2',
utils.outfn('katia... |
miurahr/seahub | tools/seahub-admin.py | Python | apache-2.0 | 2,395 | 0.002923 | #!/usr/bin/env python
# encoding: utf-8
# Copyright (c) 2012-2016 Seafile Ltd.
import sqlite3
import os
import sys
import time
import hashlib
import getpass
# Get .ccnet directory from argument or user input
if len(sys.argv) >= 2:
ccnet_dir = sys.argv[1]
else:
home_dir = os.path.join(os.path.expanduser('~... |
# Create admin user
choice = input('Would you like to create admin user?[y/n]')
if choice != 'y':
conn.close()
sys.exit(0)
username = input('E-mail address:')
passwd = getpass.getpass('Password:')
passwd2 = getpass.getpass('Password (again):')
if passwd != passwd2:
print("Two passwords NOT same.")
sys... |
enc_passwd = mySha1.hexdigest()
sql = "INSERT INTO EmailUser(email, passwd, is_staff, is_active, ctime) VALUES ('%s', '%s', 1, 1, '%d');" % (username, enc_passwd, time.time()*1000000)
try:
c = conn.cursor()
c.execute(sql)
conn.commit()
except sqlite3.Error as e:
print("An error occured:", e.args[0])
... |
AndrBecker/conference-central | utils.py | Python | apache-2.0 | 1,577 | 0 | import json
import os
import time
import uuid
from google.appengine.api import urlfetch
from models import Profile
def getUserId(user, id_type="email"):
if id_type == "email":
return user.email()
| if id_type == "oauth":
"""A workaround implementation for getting userid."""
auth = os.getenv('HTTP_AUTHORIZATION')
bearer, token = auth.split()
token_type = 'id_token'
if 'OAUTH_USER_ID' in os.environ:
token_type = 'access_token'
| url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s'
% (token_type, token))
user = {}
wait = 1
for i in range(3):
resp = urlfetch.fetch(url)
if resp.status_code == 200:
user = json.loads(resp.content)
break
... |
google/deepvariant | third_party/nucleus/util/errors_test.py | Python | bsd-3-clause | 3,169 | 0.003787 | # Copyright 2018 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the f | ollowing conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the | above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from this
# soft... |
sensysnetworks/uClinux | user/python/Tools/scripts/pathfix.py | Python | gpl-2.0 | 3,851 | 0.033238 | #! /usr/bin/env python
# Cha | nge the #! line occurring in Python scr | ipts. The new interpreter
# pathname must be given with a -i option.
#
# Command line arguments are files or directories to be processed.
# Directories are searched recursively for files whose name looks
# like a python module.
# Symbolic links are always ignored (except as explicit directory
# arguments). Of course,... |
z9484/ALoMA | pytmx/tmxloader3.py | Python | gpl-3.0 | 18,775 | 0.003941 | """
Map loader for TMX Files
bitcraft (leif.theden at gmail.com)
v.7 -- for python 3.x
If you have any problems, please contact me via email.
Tested with Tiled 0.7.1 for Mac.
released under the LGPL v3
======================================================================
Design Goals:
Simple api
Memory eff... | rray, os
# used to change the unicode string returned from minidom to
# proper python variable types.
types = {
"version": float,
"orientation": str,
"width": int,
"height": int,
"tilewidth": int,
"tileheight": int,
"firstgid": int,
"source": ... | float,
"visible": bool,
"encoding": str,
"compression": str,
"gid": int,
"type": str,
"x": int,
"y": int,
"value": str,
}
def pairwise(iterable):
# return a list as a sequence of pairs
a, b = tee(iterable)
next(b, None)
... |
sargam111/python | textblob/en/np_extractors.py | Python | mit | 6,734 | 0.000446 | # -*- coding: utf-8 -*-
'''Various noun phrase extractors.'''
from __future__ import unicode_literals, absolute_import
import nltk
from textblob.taggers import PatternTagger
from textblob.decorators import requires_nltk_corpus
from textblob.utils import tree2str, filter_insignificant
from textblob.base import BaseNPE... | efficient-way-to-extract-the-main-topics-of-a-sentence/
'''
CFG = {
('NNP', 'NNP'): 'NNP',
('NN', 'NN'): 'NNI',
('NNI', 'NN'): 'NNI',
('JJ', 'JJ'): 'JJ',
('JJ', ' | NN'): 'NNI',
}
def __init__(self):
self._trained = False
@requires_nltk_corpus
def train(self):
train_data = nltk.corpus.brown.tagged_sents(categories='news')
regexp_tagger = nltk.RegexpTagger([
(r'^-?[0-9]+(.[0-9]+)?$', 'CD'),
(r'(-|:|;)$', ':'),
... |
kbrannan/PyHSPF | examples/advanced/preprocess_02040101.py | Python | bsd-3-clause | 1,347 | 0.020787 | # preprocess_02040101.py
#
# David J. Lampert ([email protected])
#
# last updated: 08/09/2015
#
# Purpose: Extracts GIS data from sources and builds the input file for HSPF
# for a given set of assumptions for HUC 02040101, Delaware River, NY + DE.
import os, datetime
source = | 'Z:'
destination = 'C:/HSPF_data'
from pyhspf.preprocessing import Preprocessor
# 8-digit hydrologic unit code of int | erest; the lists here of states, years,
# and RPUs are just used to point to location of the data files below
HUC8 = '02040101'
state = 'Delaware'
start = datetime.datetime(1980, 1, 1)
end = datetime.datetime(2011, 1, 1)
drainmax = 400
aggregation = 'cdlaggregation.csv'
landuse = 'luc... |
edwinsteele/biblebox-pi | ansible/plugins/mitogen-0.2.2/ansible_mitogen/services.py | Python | apache-2.0 | 16,202 | 0.000062 | # Copyright 2017, David Wilson
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2.... |
:param str key:
Result of :meth:`key_from_kwargs`
:param dict response:
Response dictionary
:returns:
Number of waiters that were replied to.
| """
self._lock.acquire()
try:
latches = self._latches_by_key.pop(key)
count = len(latches)
for latch in latches:
latch.put(response)
finally:
self._lock.release()
return count
def _shutdown(self, context, lru=None, n... |
Swordf1sh/Moderat | map_demo/test.py | Python | gpl-2.0 | 4,307 | 0.003715 | from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from mapstyle import style
maphtml = '''
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0... | icon: "C:/Users/uripa/Desktop/moderat/assets/hacked.png",
ip_address: ip_address,
alias: alias,
| id: id,
});
clients[id].setMap(map)
addInfoWindow(clients[id]);
}
function addInfoWindow(client) {
var header = "<p align='center' style='background: #2c3e50; color: #c9f5f7; padding: 10px;'>" + client.alias + "<br>" + client.ip_address + "</p>"
... |
mbuesch/cnc-control | driver/setup_driver.py | Python | gpl-2.0 | 215 | 0.097674 | from | distutils.core import setup
setup(
name = "cnccontrol-driver",
description = "CNC-Control device driver",
author = "Michael Buesch",
author_email = "[email protected]",
py_module | s = [ "cnccontrol_driver", ],
)
|
gedhe/sidesa2.0 | input_data_kemiskinan.py | Python | gpl-2.0 | 13,554 | 0.014092 | #Boa:Frame:input_data_kemiskinan
import wx
import wx.lib.buttons
import frm_sideka_menu
import sqlite3
db = sqlite3.connect('/opt/sidesa/sidesa')
cur = db.cursor()
def create(parent):
return input_data_kemiskinan(parent)
[wxID_INPUT_DATA_KEMISKINAN, wxID_INPUT_DATA_KEMISKINANBUTTON1,
wxID_INPUT_DATA_KEMISKINA... | DATA_KEMISKINANSTATICTEXT2, wxID_INPUT_DATA_KEMISKINANSTATICTEXT3,
wxID_INPUT_DATA_KEMISKINANSTATICTEXT4, wxID_INPUT_DATA_KEMISKINANSTATICTEXT5,
wxID_INPUT_DATA_KEMISKINANSTATICTEXT6, wxID_INPUT_DATA_KEMISKINANSTATICTEXT7,
wxID_INPUT_DATA_KEMISKINANSTATICTEXT8, wxID_INPUT_DATA_KEMISKINANSTATICTEXT9,
wxID_INPUT_... |
def _init_coll_isipenduduk_Columns(self, parent):
# generated method, don't edit
parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,
heading='Nomor KK', width=150)
parent.InsertColumn(col=1, format=wx.LIST_FORMAT_LEFT,
heading='Nama Kepala Keluarga', wid... |
facebookexperimental/eden | eden/scm/edenscm/hgext/stat.py | Python | gpl-2.0 | 1,158 | 0 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from edenscm.mercurial import error, patch, registrar, templatekw, util
from edenscm.mercurial.i18n import _
templatefunc = registrar.templatefunc()... | hich case "added",
"changed", "removed" will be shown before file names.
"""
if "style" in args:
style = args["style"][1]
else:
style = "none"
repo = mapping["repo"]
ctx = mapping["ctx"]
revcache = mapping["revcache"]
width = repo.ui.termwidth()
if style == "none":
... | e:
raise error.ParseError(_("stat does not support style %r") % (style,))
return patch.diffstat(
util.iterlines(ctx.diff(noprefix=False)), width=width, status=status
)
|
haoyuchen1992/osf.io | website/project/licenses/__init__.py | Python | apache-2.0 | 3,350 | 0.00209 | import functools
import json
import os
import warnings
from modularodm import fields, Q
from modularodm.exceptions import NoResultsFound
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website import settings
def _serialize(fields, instance):
return {
field:... | holders = fields.StringField | (list=True)
@property
def name(self):
return self.node_license.name if self.node_license else None
@property
def text(self):
return self.node_license.text if self.node_license else None
@property
def id(self):
return self.node_license.id if self.node_license else None
... |
boris-p/ladybug | src/Ladybug_GenCumulativeSkyMtx.py | Python | gpl-3.0 | 16,430 | 0.011625 | # GenCumulativeSkyMtx
#
# Ladybug: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Ladybug.
#
# Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <[email protected]>
# Ladybug is free software; you can redistribute it and/or modify
# it under the ... | 04, 334, 365]
numOfHours = [24 * numOfDay for numOfDay in numOfDays]
for h in range(len(numOfHours)-1):
if | hour <= numOfHours[h+1]: month = h + 1; break
if hour == 0: day = 1
elif (hour)%24 == 0: day = int((hour - numOfHours[h]) / 24)
else: day = int((hour - numOfHours[h]) / 24) + 1
time = hour%24 + 0.5
return str(day), str(month), str(time)
def getRadiationValues(epw_file, analysisPeriod, we... |
X-dark/Flexget | flexget/plugins/output/rapidpush.py | Python | mit | 6,710 | 0.001192 | from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
from flexget.utils import json
from flexget.utils.template import RenderError
log = logging.getLogger('rapidpush')
__version__ = 0.4
headers = {'User-Agent': "FlexGet RapidPush... | message)
except RenderError as e:
log.error('Error setting RapidPush message: %s' % e)
# Check if we have to send a normal or a broadcast notification.
if not config['channel']:
priority = entry.get('priority', config['priority'])
cat... | except RenderError as e:
log.error('Error setting RapidPush category: %s' % e)
group = entry.get('group', config['group'])
try:
group = entry.render(group)
except RenderError as e:
log.error('Error s... |
MoonShineVFX/core | avalon/tools/cbloader/app.py | Python | mit | 10,714 | 0 | import sys
import time
from ..projectmanager.widget import AssetWidget, AssetModel
from ...vendor.Qt import QtWidgets, QtCore, QtGui
from ... import api, io, style
from .. import lib
from .lib import refresh_family_config
from .widgets import SubsetWidget, VersionWidget, FamilyListWidget
module = sys.modules[__name... | "silo"]
self.echo("Duration: %.3fs" % (time.time() - t1))
|
def _versionschanged(self):
subsets = self.data["model"]["subsets"]
selection = subsets.view.selectionModel()
# Active must be in the selected rows otherwise we
# assume it's not actually an "active" current index.
version = None
active = selection.currentIndex()
... |
vrtsystems/hszinc | hszinc/zoneinfo.py | Python | bsd-2-clause | 6,577 | 0.002433 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Project Haystack timezone data
# (C) 2016 VRT Systems
#
# vim: set ts=4 sts=4 et tw=78 sw=4 si:
import pytz
import datetime
from .version import LATEST_VER
# The official list of timezones as of 6th Jan 2016:
# Yes, that's *without* the usual country prefix.
HAYSTACK_TIME... | ianak
Port-au-Prince
Port_Moresby
Port_of_Spain
Porto_Velho
Prague
Puerto_Rico
Pyongyang
Qatar
Qyzylorda
Rainy_River
Rangoon
Rankin_Inlet
Rarotonga
Recife
Regina
Rel
Resolute
Reunion
Reykjavik
Riga
Rio_Branco
Rio_Gallegos
Riyadh
Rome
Rothera
Saipan
Sakhalin
Salt | a
Samara
Samarkand
San_Juan
San_Luis
Santa_Isabel
Santarem
Santiago
Santo_Domingo
Sao_Paulo
Scoresbysund
Seoul
Shanghai
Simferopol
Singapore
Sitka
Sofia
South_Georgia
Srednekolymsk
St_Johns
Stanley
Stockholm
Swift_Current
Sydney
Syowa
Tahiti
Taipei
Tallinn
Tarawa
Tashkent
Tbilisi
Tegucigalpa
Tehran
Tell_City
Thimphu
Th... |
eHealthAfrica/ureport | ureport/assets/urls.py | Python | agpl-3.0 | 74 | 0.013514 | from .views import ImageCRUDL
urlpatte | rns = ImageCRUDL().as_url | patterns() |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/code/browser/branchsubscription.py | Python | agpl-3.0 | 11,371 | 0.000264 | # Copyright 2009-2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
__all__ = [
'BranchPortletSubscribersContent',
'BranchSubscriptionAddOtherView',
'BranchSubscriptionAddView',
'BranchSubscriptionEditOwnV... | subscription.max_diff_lines = self.optional_max_diff_lines(
subscription.notification_level,
data['max_diff_lines'])
subscription.review_level = data['review_level']
self.add_notification_message(
'Subscription updated to: ',
... | self.request.response.addNotification(
'You are not subscribed to this branch.')
@action("Unsubscribe")
def unsubscribe(self, action, data):
# Be proactive in the checking to catch the stale post problem.
if self.context.hasSubscription(self.user):
self.cont... |
projecthamster/hamster | src/hamster-cli.py | Python | gpl-3.0 | 18,772 | 0.002184 | #!/usr/bin/env python3
# - coding: utf-8 -
# Copyright (C) 2010 Matías Ribecky <matias at mribecky.com.ar>
# Copyright (C) 2010-2012 Toms Bauģis <[email protected]>
# Copyright (C) 2012 Ted Smith <tedks at cs.umd.edu>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribut... | ata.get_int32() if data else None
self.fact_controller = CustomFactController(name, fact_id=fact_id)
logger.debug("new CustomFactController")
co | ntroller = self.fact_controller
elif name == "overview":
if not self.overview_controller:
self.overview_controller = Overview()
logger.debug("new Overview")
controller = self.overview_controller
elif name == "preferences":
if not self.p... |
mvidalgarcia/indico | indico/modules/events/registration/models/registrations.py | Python | mit | 22,495 | 0.002223 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import posixpath
import time
from collections import OrderedDict
... | ed with this registration
transaction_id = db.Column(
db.Integer,
db.ForeignKey('events.payment_transactions.id'),
index=True,
unique=True,
nullable=True
)
#: The state a registration | is in
state = db.Column(
PyIntEnum(RegistrationState),
nullable=False,
)
#: The base registration fee (that is not specific to form items)
base_price = db.Column(
db.Numeric(8, 2), # max. 999999.99
nullable=False,
default=0
)
#: The price modifier applie... |
tinloaf/home-assistant | tests/components/mqtt/test_config_flow.py | Python | apache-2.0 | 4,724 | 0 | """Test config flow."""
from unittest.mock import patch
import pytest
from homeassistant.setup import async_setup_component
from tests.common import mock_coro, MockConfigEntry
@pytest.fixture(autouse=True)
def mock_finish_setup():
"""Mock out the finish setup method."""
with patch('homeassistant.components... | ] == 'abort'
async def test_user_single_instance(hass):
"""Test we only allow a single config flow."""
MockConfigEntry(domain='mqtt').add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
'mqtt', context={'source': 'user'})
assert result['type'] == 'abort'
assert result['r... | ConfigEntry(domain='mqtt').add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
'mqtt', context={'source': 'hassio'})
assert result['type'] == 'abort'
assert result['reason'] == 'single_instance_allowed'
async def test_hassio_confirm(hass, mock_try_connection,
... |
dongweiming/data-analysis | data_analysis/models.py | Python | apache-2.0 | 603 | 0.004975 | from data_analysis import db
class Apidist(db.Document):
name = db.StringField(max_length=255, required=True)
call = db.IntField(required=True)
include = db.StringField(max_length=255, required=True)
class Celery(db.Document):
cost = db.FloatField(required=True)
time = db.DateTimeF | ield(required=True)
file = db.StringField(max_length=25, required=True)
task = db.StringField(max_length=255, required=True)
class Mongo(db.Document):
total = db.IntField(required=True)
database = db.StringField(max_length=255, required=True)
hour = db.DictField(required= | True)
|
gazeti/aleph | docs/conf.py | Python | mit | 10,610 | 0.000189 | # -*- coding: utf-8 -*-
#
# Aleph documentation build configuration file, created by
# sphinx-quickstart on Fri Dec 2 16:22:48 2016.
#
# 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.
#
# All... | eauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system mes... | lse
# -- Options for HTML output ----------------------------------------------
import sphinx_rtd_theme
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'default'
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize ... |
GoodCloud/johnny-cache | johnny/cache.py | Python | mit | 21,360 | 0.002949 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Johnny's main caching functionality."""
import sys
import re
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
from uuid import uuid4
try:
from hashlib import md5
except ImportError:... | generate keys. Some of these keys will be used
# directly in the cache, while others are only general purpose functions to
# generate hashes off of one or more values.
clas | s KeyGen(object):
"""This class is responsible for generating keys."""
def __init__(self, prefix):
self.prefix = prefix
def random_generator(self):
"""Creates a random unique id."""
return self.gen_key(str(uuid4()))
def gen_table_key(self, table, db='default'):
"""Retu... |
earonne/nadb-sample-site | nadb-sample-site/settings.py | Python | bsd-3-clause | 4,940 | 0.001619 | # Django settings for nadbproj project.
import os.path
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'orac... | ive paths.
os.path.join(os.path.dirname(__ | file__), 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'nadb',
'django.contrib.markup',
'django.contrib.admin',
'django.contrib.... |
keflavich/pyspeckit-obsolete | pyspeckit/spectrum/models/gaussfitter.py | Python | mit | 10,557 | 0.019703 | """
===============
Gaussian fitter
===============
.. moduleauthor:: Adam Ginsburg <[email protected]>
Created 3/17/08
Original version available at http://code.google.com/p/agpy/source/browse/trunk/agpy/gaussfitter.py
(the version below uses a Class instead of independent functions)
"""
import numpy
from nu... | mpfit
import matplotlib.cbook as mpcb
from . import mpfit_messages
| from . import model
class gaussian_fitter(model.SpectralModel):
"""
A rather complicated Gaussian fitter class. Inherits from, but overrides
most components of, :mod:`model.SpectralModel`
"""
def __init__(self,multisingle='multi'):
self.npars = 3
self.npeaks = 1
self.onepe... |
vbelakov/h2o | py/testdir_multi_jvm/test_storeview_diff.py | Python | apache-2.0 | 3,338 | 0.006591 | import unittest, time, random, sys, json
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_glm, h2o_browse as h2b, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
# assume we're at 0xdata... | elapsed = time.time() - start
print "parse end on ", csvFilename, 'took', elapsed, 'seconds',\
"%d pct. of timeout" % ((elapsed*100)/timeoutSecs)
print "parse result:", parseResult['destination_key']
|
# INSPECT******************************************
start = time.time()
inspect = h2o_cmd.runInspect(None, parseResult['destination_key'], timeoutSecs=360)
print "Inspect:", parseResult['destination_key'], "took", time.time() - start, "seconds"
h2o_cmd.infoFr... |
fnp/edumed | forum/search_indexes.py | Python | agpl-3.0 | 226 | 0 | from haystack i | mport | indexes
from pybb.models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return Post
|
lolotux/cabot-docker | cabot/cabotapp/models.py | Python | mit | 32,605 | 0.001564 | from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from polymorphic import PolymorphicModel
from django.db.models import F
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from celery.exceptions import SoftTimeLimitExc... | dgement(self):
try:
return self.unexpired_acknowledgements()[0]
except:
return None
@property
def recent_snapshots(self):
snapshots = self.snapshots.filter(
time__gt=(timezone.now() - timedelta(minutes=60 * 24)))
snapshots = list(snapshots.val... | ots
def graphite_status_checks(self):
return self.status_checks.filter(polymorphic_ctype__model='graphitestatuscheck')
def http_status_checks(self):
return self.status_checks.filter(polymorphic_ctype__model='httpstatuscheck')
def jenkins_status_checks(self):
return self.status_che... |
x3rj/watransport | XMPPLayer.py | Python | gpl-3.0 | 3,760 | 0.009574 |
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks... | , "receipt"
, entity.getType()
, entity.getFrom()
)
self.toLower(ack)
self.account.incomingWAReceipt(entity)
@ProtocolEntityCal | lback("message")
def onMessage(self, messageProtocolEntity):
receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
self.toLower(receipt)
if not messageProtocolEntity.isGroupMessage():
if messageProtocolEntity.getType() == "text":
... |
marbu/pylatest | contrib/convertdirectives.py | Python | gpl-3.0 | 2,851 | 0.001052 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
This script changes given rst document in place, converting old test action
directives ``test_step`` and ``test_result`` into ``test_action``.
It's a best effort hack, not an official part of pylatest (-: I realized that
such tool could be quite straighforward given a... |
actions.add(action.action_name, action, action.action_id)
# list with content of rstfile
rstcontent = rstsource.splitline | s()
# number of next line in rstfile to go to output, zero indexed
next_line_number = 0
with open(args.rstfile, "w") as rstfile:
for action_id, test_step, test_result in actions:
# make the assumptions clear
assert test_step is not None
assert test_step.start_line > next_line_number
... |
OpenSoccerManager/opensoccermanager | structures/shortlist.py | Python | gpl-3.0 | 1,561 | 0 | #!/usr/bin/env python3
# This file is part of OpenSoccerManager.
#
# OpenSoccerManager is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later ver... | f.shortlist = set()
def get_shortlist(self):
'''
Return complete set of shortlisted players.
'''
return self.shortlist
def get_player_in_shortlist(self, player):
'''
Return whether given player id is already in the shortlist.
'''
return player in... | layer):
'''
Add specified player id to the shortlist.
'''
self.shortlist.add(player)
def remove_from_shortlist(self, player):
'''
Remove specified player id from shortlist.
'''
if player in self.shortlist:
self.shortlist.remove(player)
|
rande/tornado-flowdock | tornadoflowdock/push.py | Python | mit | 1,605 | 0.003738 | from tornado.httpclient import HTTPRequest, AsyncHTTPClient
import json
class Flow(object):
def __init__(self, id, token, external_user_name=None):
self.id = id
self.token = token
self.external_user_name = external_user_name
self.http_client = Asyn | cHTTPClient()
def _post(self, push_type, body, callback=None):
request = | HTTPRequest("https://api.flowdock.com/v1/messages/%s/%s" % (push_type, self.token), **{
'headers': {
'Content-Type': 'application/json'
},
'method': "POST",
'body': json.dumps(body)
})
self.http_client.fetch(request, callback)
def c... |
bluebreezecf/kafka | tests/kafkatest/services/mirror_maker.py | Python | apache-2.0 | 8,150 | 0.002577 |
# 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 use... | mption streams.
threads> (default: 1)
--offset.commit.interval.ms <Integer: Offset commit interval in ms (default:
offset com | mit interval in 60000)
millisecond>
--producer.config <config file> Embedded producer config.
--rebalance.listener.args <Arguments Arguments used by custom rebalance
passed to custom rebalance listener listener for mirror maker consumer
constructor as a string.>
--whitelist <Java rege... |
wutron/compbio | compbio/vis/argvis.py | Python | mit | 29,618 | 0.00368 | """
Visualization of ARGs (Ancestral Recombination Graphs)
"""
# python imports
from itertools import chain, izip
import random
from math import *
# rasmus imports
from rasmus import util, treelib, stats, sets
# compbio imports
from compbio import arglib
# summon imports
import summon
from summon import sumtr... | branch_click=branch_click))
# draw mutations
if mut:
g = group()
for node, parent, pos, t in mut:
x1, y1, x2, y2 = get_branch_layout(layout, node, parent)
g.append(group(draw_mark(x1, t, col=(0,0,1)), color(1,1,1)))
w | in.add_group(g)
return win
def draw_arg(arg, layout, recomb_width=.4, branch_click=None):
def branch_hotspot(node, parent, x, y, y2):
def func():
branch_click(node, parent)
return hotspot("click", x-.5, y, x+.5, y2, func)
# draw branches
g = group(color(1,1,1))
for no... |
eelcovv/vapory | examples/pawn.py | Python | mit | 1,312 | 0.046494 | """ Just a purple sphere """
from vapory import *
objects = [
# SUN
LightSource([1500,2500,-2500], 'color',1),
# SKY
Sphere( [0,0,0],1, 'hollow',
Texture(
Pigment( 'gradient', [0,1,0],
'color_map{[0 color White] [1 color Blu... | ),
Finish( 'ambient', 1, 'diffuse', 0)
),
'scale', 10000
),
# GROUND
Plane( [0,1,0], 0 ,
Texture( Pigment( 'color', [1.1*e for e in [0.80,0.55,0.35]])),
Normal( 'bumps', 0.75, 'scale', 0.035),
Fini... | ],0.0),
Texture( Pigment( 'color', [1,0.65,0])),
Finish( 'phong', 0.5)
)
]
scene = Scene( Camera( 'ultra_wide_angle',
'angle',45,
'location',[0.0 , 0.6 ,-3.0],
'look_at', [0.0 , 0.6 , 0.0]
),
... |
shakamunyi/solum | solum/objects/sqlalchemy/__init__.py | Python | apache-2.0 | 1,920 | 0 | # Copyright 2013 - 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 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... | as abstract_extension
from solum.objects import operation as abstract_operation
from solum.objects import plan as abstract_plan
from solum.objects import sensor as abstract_sensor
from solum.objects import service as abstract_srvc
from solum.objects.sqlalchemy import extension
from solum.objects.sqlalchemy import oper... |
ThePerkinrex/PercOS | PercOS_filesystem/bin/cd.py | Python | gpl-3.0 | 709 | 0 | from command import Command
from os import path
class cd(Command):
name = 'cd'
desc = 'Changes the working directory'
u | sage = 'cd <place to go>'
author = 'native'
def call(self, args=None):
if args is not None:
if len(arg | s) == 0:
print('I need at least the place to go to work')
else:
toGo = self.dire.cd(args[0], True)
if path.exists(toGo.realdir):
if path.isdir(toGo.realdir):
self.dire.cd(args[0], False)
else:
... |
affordablewindurbines/jarvisproject | client/modules/knowledged.py | Python | gpl-3.0 | 982 | 0.003055 | # -*- coding: utf-8-*-
import random
import re
import wolframalpha
import time
import sys
from sys import maxint
from client import jarvispath
WORDS = ["WHO", "WHAT", "WHERE", "HOW MUCH" | ]
def handle(text, mic, profile):
app_id=profile['keys']['WOLFRAMALPHA']
client = wolframalpha.Client(app_id)
query = client.query(text)
if len(query.pods) > 0:
tex | ts = ""
pod = query.pods[1]
if pod.text:
texts = pod.text
else:
texts = "I can not find anything"
mic.say(texts.replace("|",""))
else:
mic.say("Sorry, Could you be more specific?.")
def isValid(text):
if re.search(r'\bwho\b', text, re.IGNORECA... |
wdv4758h/ZipPy | edu.uci.python.benchmark/src/benchmarks/sympy/sympy/functions/special/tests/test_error_functions.py | Python | bsd-3-clause | 24,044 | 0.00287 | from sympy import (
symbols, expand, expand_func, nan, oo, Float, conjugate, diff,
re, im, Abs, O, factorial, exp_polar, polar_lift, gruntz, limit,
Symbol, I, integrate, S,
sqrt, sin, cos, sinh, cosh, exp, log, pi, EulerGamma,
erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv,
gamma, uppergamma, l... | ert erfc(nan) == nan
assert erfc(oo) == 0
assert erfc(-oo) == 2
assert erfc(0) == 1
assert erfc(I*oo) == -oo*I
assert erfc(-I*oo) == oo | *I
assert erfc(-x) == S(2) - erfc(x)
assert erfc(erfcinv(x)) == x
assert erfc(I).is_real is False
assert erfc(0).is_real is True
assert conjugate(erfc(z)) == erfc(conjugate(z))
assert erfc(x).as_leading_term(x) == S.One
assert erfc(1/x).as_leading_term(x) == erfc(1/x)
assert erfc(z)... |
btat/Booktype | lib/booki/bookizip.py | Python | agpl-3.0 | 5,243 | 0.001717 | # This file is part of Booktype.
# Copyright (c) 2012 Douglas Bagnall
#
# Booktype is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | scheme | . If the ns or scheme are not set, they default to Dublin
Core and an empty string, respectively.
If no values are set, an empty list is returned, unless the
default argument is given, in which case you get that.
"""
values = metadata.get(ns, {}).get(key, {})
if scheme == '*':
return s... |
commaai/openpilot | selfdrive/locationd/test/test_calibrationd.py | Python | mit | 739 | 0.002706 | #!/usr/bin/env python3
import random
import unittest
import numpy as np
import cereal.messaging as messaging
from common.params import Params
from selfdrive.locationd.calibrationd import Calibrator
class TestCalibrationd(unittest.TestCase):
def test_read_saved_params(self):
msg = messaging.new_message('liveC... | Calib, c.rpy)
self.assertEqua | l(msg.liveCalibration.validBlocks, c.valid_blocks)
if __name__ == "__main__":
unittest.main()
|
sixuanwang/SAMSaaS | wirecloud-develop/src/wirecloud/platform/tests/__init__.py | Python | gpl-2.0 | 2,777 | 0.005764 | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either v... | recloud.commons.utils.testcases import build_selenium_test_cases
build_selenium_test_cases(('wirecloud.platform.tests.selenium_tests.BasicSeleniumTests',), locals())
build_selenium_test_cases(('wirecloud.platform.tests.base.BasicViewsSeleniumTestC | ase',), locals())
build_selenium_test_cases(('wirecloud.platform.localcatalogue.tests.LocalCatalogueSeleniumTests',), locals())
build_selenium_test_cases(('wirecloud.platform.wiring.tests.WiringSeleniumTestCase',), locals())
build_selenium_test_cases(('wirecloud.platform.wiring.tests.WiringRecoveringTestCase',), locals... |
darthryking/simpleisa | simplesim_fsm.py | Python | bsd-3-clause | 28,564 | 0.009628 | """
simplesim_fsm.py
By Ryan Lam
Defines the Finite State Machine (Flying Spaghetti Monster) controller element
for the datapath.
"""
from simplesim_elements import Element, bits_required
from constants import State, Flags, ALUSelA, ALUSelB, ALUOp, Op
class Controller(Element):
def __init__(self,
... | DM_0,
Op.STM : State.STM_0,
Op.INC : State.INC_0,
Op.DEC : State.DEC_0,
Op.NEG : State.NEG_0,
Op.BCM : State.BCM_0,
Op.USR : State.USR_0,
Op.SSR : State.SSR_0,... | Op.AND : State.AND_0,
Op.OR : State.OR_0,
Op.CMP : State.CMP_0,
Op.JMP : State.JMP_0,
Op.JEQ : State.JEQ_0,
Op.JUL : State.JUL_0,
Op.JUG : State.JUG_0,
... |
qedsoftware/commcare-hq | corehq/blobs/atomic.py | Python | bsd-3-clause | 2,197 | 0 | from corehq.blobs import DEFAULT_BUCKET
from corehq.blobs.exceptions import InvalidContext
class AtomicBlobs(object):
"""A blob db wrapper that can put and delete blobs atomically
Usage:
with AtomicBlobs(get_blob_db()) as db:
# do stuff here that puts or deletes blobs
db.dele... | deletes = None
if exc_type is None:
for args, kw in deletes:
self.db.delete(*args, **kw)
else:
for info, bucket in puts:
self.db.dele | te(info.identifier, bucket)
|
universalcore/unicore-cms-django | project/wsgi.py | Python | bsd-2-clause | 1,424 | 0.000702 | """
WSGI config for skeleton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | ne
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi proc... | iron.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_applicatio... |
tchellomello/home-assistant | tests/components/homeassistant/triggers/test_numeric_state.py | Python | apache-2.0 | 41,794 | 0.000455 | """The tests for numeric state automation."""
from datetime import timedelta
import pytest
import voluptuous as vol
import homeassistant.components.automation as automation
from homeassistant.components.homeassistant.triggers import (
numeric_state as numeric_state_trigger,
)
from homeassistant.core import Contex... | "platform": "numeric_state",
"entity_id": "test.entity",
"below": 10,
},
"action": {"service": "test.aut | omation"},
}
},
)
# 10 is not below 10 so this should not fire again
hass.states.async_set("test.entity", 10)
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_fires_on_initial_entity_below(hass, calls):
"""Test the firing when starting with a mat... |
jainaman224/Algo_Ds_Notes | Rain_Water_Trapping/Rain_Water_Trapping.py | Python | gpl-3.0 | 1,208 | 0.044702 | # Rain_Water_Trapping
def trappedWater(a, size) :
# left[i] stores height of tallest bar to the to left of it including itself
left = [0] * size
# Right [i] stores height of tallest bar to the to right of it including itself
right = [0] * size
# Initialize result
waterVol... | accumulated water element by element
for i in range(0, size):
waterVolume += min(left[i],right[i]) - a[i]
return waterVolume
# main program
arr =[]
n = int(input()) #input the number of towers
for i in range(n):
arr.append(int(input())) #storing... | )
#Input:
#12
#0
#1
#0
#2
#1
#0
#1
#3
#2
#1
#2
#1
#Output:
#The maximum water trapped is 6
|
unnikrishnankgs/va | venv/lib/python3.5/site-packages/external/org_mozilla_bleach/bleach/encoding.py | Python | bsd-2-clause | 2,277 | 0 | import datetime
from decimal import Decimal
import types
import six
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_unicode(strings_only=True).
"""
return isinstance(obj, (
six.inte... | .
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise UnicodeDecodeError(*e.args)
else:
# If we get to here, the caller has passed in an Exception
# subclass populated with non-ASCII bytestring data wit... | tion args
# to unicode.
s = ' '.join([force_unicode(arg, encoding, strings_only,
errors) for arg in s])
return s
|
boar/boar | boar/uploads/manager.py | Python | bsd-3-clause | 227 | 0.008811 | from django.db import models
class UploadManager(mode | ls.Manager):
def published(self):
return self.get_query_set().annotate(
article_count=models.Count('article')
| ).filter(article_count__gt=0)
|
Amitmund/quick_tools | tellWords/tellWords.py | Python | mit | 438 | 0.006849 | #!/usr/bin/env python
import subprocess
# Example on how to use this script.
# ./tellWords.py [ and press enter]
# In the prompt line type what you want and press enter again.
command = "say"
text = raw_input("Enter word or a sentence and press enter: ")
characters = list(text)
for c1 i | n characters:
if c1 == " ":
subprocess.call([command, ",,"])
else:
subprocess.call([command, | c1])
subprocess.call([command, text])
|
lubomir/productmd | productmd/compose.py | Python | lgpl-2.1 | 4,093 | 0.001222 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Red Hat, Inc.
#
# 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; either
# version 2.1 of the License, or (at your option) any later version.... | YYYYMMDD.0/1.0/metadata (legacy location)
for i in os.listdir(compose_path):
path = os.path.join(compose_path, i)
metadata_path = os.path.join(path, "metadata")
if _file_exists(metadata_path):
self.compose_path = path
br... | None
def _find_metadata_file(self, paths):
for i in paths:
path = os.path.join(self.compose_path, i)
if _file_exists(path):
return path
raise RuntimeError('Failed to load metadata from %s' % self.compose_path)
@property
def info(self):
"""(:... |
Elbandi/PyMunin | pysysinfo/varnish.py | Python | gpl-3.0 | 2,163 | 0.012483 | """Implements VarnishInfo Class for gathering stats from Varnish Cache.
The statistics are obtained by running the command varnishstats.
"""
import re
import util
__author__ = "Ali Onur Uyar"
__copyright__ = "Copyright 2011, Ali Onur Uyar"
__credits__ = []
__license__ = "GPL"
__version__ = "0.9.24"
__maintainer__ =... | fo:
"""Class to retrieve stats from Varnish Cache."""
_descDict = | {}
def __init__(self, instance=None):
"""Initialization for monitoring Varnish Cache instance.
@param instance: Name of the Varnish Cache instance.
(Defaults to hostname.)
"""
self._instance = instance
def getStats(self):
... |
tamasgal/km3pipe | km3pipe/style/km3pipe_notebook.py | Python | mit | 49 | 0 | fr | om ..style import use
use("km3pi | pe-notebook")
|
keithhendry/treadmill | treadmill/bootstrap/vagrant_aliases.py | Python | apache-2.0 | 1,513 | 0 | """Vagrant aliases."""
ALIASES = {
'pid1': '/opt/treadmill-pid1/bin/pid1',
'treadmill': '/opt/treadmill',
'treadmill_bin': '/opt/treadmill/bin/treadmill',
# openldap
'slapd': '/usr/sbin/slapd',
'slapadd': '/usr/sbin/slapadd',
'dnscache': None,
'java_home': None,
'kafka_run_class'... | rt': '/opt/s6/bin/import',
'importas': '/opt/s6/bin/importas',
'redirfd': '/opt/s6/bin/redirfd',
's6_envdir': '/opt/s6/bin/s6-e | nvdir',
's6_envuidgid': '/opt/s6/bin/s6-envuidgid',
's6_log': '/opt/s6/bin/s6-log',
's6_setuidgid': '/opt/s6/bin/s6-setuidgid',
's6_svc': '/opt/s6/bin/s6-svc',
's6_svok': '/opt/s6/bin/s6-svok',
's6_svscan': '/opt/s6/bin/s6-svscan',
's6_svscanctl': '/opt/s6/bin/s6-svscanctl',
's6_svwait':... |
LosFuzzys/CTFd | tests/api/v1/test_flags.py | Python | apache-2.0 | 4,159 | 0.00024 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from tests.helpers import (
create_ctfd,
destroy_ctfd,
gen_challenge,
gen_flag,
login_as_user,
)
def test_api_flags_get_non_admin():
app = create_ctfd()
with app.app_context():
gen_challenge(app.db)
gen_flag(app.db, 1)
... | ith app.app_context():
with login_as_user(app, "admin") as client:
r = client.get("/api/v1/flags/types", json="")
assert r.status_code == 200
r = client.get("/api/v1/flags/types/static", json="")
assert r.status_code == 200
destroy_ctfd(app)
def test_api_fla... | gen_flag(app.db, 1)
with login_as_user(app, "admin") as client:
r = client.get("/api/v1/flags/1", json="")
assert r.status_code == 200
destroy_ctfd(app)
def test_api_flag_patch_admin():
"""Can a user patch /api/v1/flags/<flag_id> if admin"""
app = create_ctfd()
... |
TheGurke/Progenitus | sleekxmpp/features/feature_mechanisms/stanza/failure.py | Python | gpl-3.0 | 2,500 | 0.0016 | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza import StreamFeatures
from sleekxmpp.xmlstream import ElementBase, StanzaBase, ET
from sleekxmpp.xmlstream import register... | ype and condition, and changes the
parent stanza's type to 'error'.
Arguments:
xml -- Use an existing XML object for the stanza's values.
"""
# StanzaBase overrides self.namespace
self.namespace = Failure.namespace
if StanzaBase.setup(self, xml):
... | et_condition(self):
"""Return the condition element's name."""
for child in self.xml.getchildren():
if "{%s}" % self.namespace in child.tag:
cond = child.tag.split('}', 1)[-1]
if cond in self.conditions:
return cond
return 'not-auth... |
sanguinariojoe/FreeCAD | src/Mod/Fem/femobjects/constraint_electrostaticpotential.py | Python | lgpl-2.1 | 4,421 | 0.000452 | # ***************************************************************************
# * Copyright (c) 2017 Markus Hovorka <[email protected]> *
# * Copyright (c) 2020 Bernd Hahnebach <[email protected]> *
# * *
# * Th... | c License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, w | rite to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ******************************************************... |
voc/voctomix | example-scripts/ffmpeg/record-all-audio-streams.py | Python | mit | 2,097 | 0 | #!/usr/bin/env python3
import socket
import sys
import json
import shlex
import subprocess
import logging
from configparser import SafeConfigParser
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('record-all-audio-streams')
host = 'localhost'
port = 9999
log.info('Connecting to %s:%u', host, port)
c... | d:
if line.startswith('server_config'):
[cmd, arg] = line.split(' ', 1)
server_config_json = arg
log.info('Received Config from Server')
break
log.info('Parsing Server-Config')
server_config = json.loads(server_config_json)
def getlist(self, section, option):
return [x.strip()... | option).split(',')]
SafeConfigParser.getlist = getlist
config = SafeConfigParser()
config.read_dict(server_config)
sources = config.getlist('mix', 'sources')
inputs = []
maps = []
for idx, source in enumerate(sources):
inputs.append('-i tcp://localhost:{:d}'.format(13000 + idx))
maps.append('-map {0:d}:a -... |
barsi/odoo-rtl | report_rtl/__init__.py | Python | agpl-3.0 | 952 | 0.00105 | # -*- coding: utf-8 -*-
########################################################### | ###################
#
# Odoo RTL support
# Copyright (C) 2014 Mohammed Barsi.
#
# This program is free software: you can redistribute it and/or modify
# it under the te | rms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MER... |
zeropool/crosswalk | build/android/generate_xwalk_core_library_aar.py | Python | bsd-3-clause | 2,953 | 0.009143 | #!/usr/bin/env python
#
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import sys
import zipfile
def main():
option_parser = optparse.OptionParser()
option_parser.add_opti... | f i | n files:
real_path = os.path.join(root, f)
zip_path = os.path.join(dest, os.path.relpath(root, src), f)
if real_path in exclude_files:
continue
aar_file.write(real_path, zip_path)
return 0
if __name__ == '__main__':
sys.exit(main())
|
Sarthak30/User-Registration | source/manage.py | Python | gpl-2.0 | 768 | 0.00651 | #!/usr/bin/env python
import os
from app import create_app, db
from app.models import User, Role
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_... | text():
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.T... | all()
manager.run()
|
percyfal/bokeh | sphinx/source/conf.py | Python | bsd-3-clause | 9,863 | 0.004157 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from os.path import abspath, dirname, join
#
# Bokeh documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 12 23:43:03 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note ... | ehPlots'),
('YouTube', '//www.youtube.com/channel/UCK0rSk29mmg4UT4bIOvPYhw')
),
# Links for the docs sub navigation
'N | AV_DOCS': (
('Installation', 'installation'),
('User Guide', 'user_guide'),
('Gallery', 'gallery'),
('Reference', 'reference'),
('Releases', 'releases/%s' % version),
('Developer Guide', 'dev_guide'),
),
'ALL_VERSIONS': all_versions,
'css_server': os.environ.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.