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 |
|---|---|---|---|---|---|---|---|---|
zstackorg/zstack-woodpecker | integrationtest/vm/arm/test_arm_vm.py | Python | apache-2.0 | 1,342 | 0.008942 | '''
New Integration Test for creating KVM VM.
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import os
# import arm.test_stub as test_stub
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_st... | )
l3_name=os.environ.get('l3PublicNetworkName')
l3_uuid = test_lib.lib_get_l | 3_by_name(l3_name).uuid
vm.add_nic(l3_uuid)
# vm.check()
cpuNum = 2
memorySize = 666 * 1024 * 1024
new_offering = test_lib.lib_create_instance_offering(cpuNum = cpuNum,\
memorySize = memorySize)
test_obj_dict.add_instance_offering(new_offering)
vm.stop()
vm.change_instance_o... |
phatblat/AbletonLiveMIDIRemoteScripts | Push2/settings.py | Python | mit | 404 | 0.034653 | # Source Generated with Decompyle++
# File: settings.p | yc (Python 2.5)
from pushbase.setting import OnOffSetting
def create_settings(preferences = None):
if preferences is not None:
pass
1
preferences = { }
return {
'workflow': OnOffSetting(name = 'Workflow', value_labels = [
'Scene',
'Clip'], default_ | value = True, preferences = preferences) }
|
pybursa/homeworks | m_zhelyaskoff/hw1/L01_task10.py | Python | gpl-2.0 | 2,316 | 0.011226 | # -*- coding: cp1251 -*-
# Çàäàíèå 10: èíòåðàêòèâíûé ïîäñ÷åò ãëàñíûõ.
# ÓÑËÎÂÈÅ:
# Íàïèñàòü ïðîãðàììó (python script), êîòîðàÿ ïðè çàïóñêå áóäåò
# çàïðàøèâàòü ïîëüçîâàòåëÿ ââåñòè ïðîèçâîëüíóþ ñòðîêó è
# âûäàâàòü â îòâåòå êîëè÷åñòâî ãëàñíûõ áóêâ.
# Ïðèìå÷àíèå:
# - äëÿ ðó÷íîãî ââîäà èñïîëüçóåì âñòðîåííóþ ôóíêöèþ... | wer <> y:
print "Please, enter corren | t answer. Continue? (yes/no) "
answer = None
continue
print "Hurray! :-)"
print "Please, enter your string: "
input_str = raw_input()
res = vowels_count(input_str);
if bool(res):
print "The string contains", res, "vowels"
... |
aaren/pywt | pywt/tests/data/generate_matlab_data.py | Python | mit | 2,444 | 0 | """ This script was used to generate dwt_matlabR2012a_result.npz by storing
the outputs from Matlab R2012a. """
from __future__ import division, print_function, absolute_import
import numpy as np
import pywt
try:
from pymatbridge import Matlab
mlab = Matlab()
_matlab_missing = False
except ImportError:
... | "package installed.")
_matlab_missing = True
if _matlab_missing:
raise EnvironmentError("Can't generate matlab data files without MATLAB")
size_set = 'reduced'
# list of mode names in pywt and matlab
modes = [('zero', 'zpd'),
('constant', 'sp0'),
('symmetric', 'sym'),
('per... | m', 'coif', 'bior', 'rbio')
wavelets = sum([pywt.wavelist(name) for name in families], [])
rstate = np.random.RandomState(1234)
mlab.start()
try:
all_matlab_results = {}
for wavelet in wavelets:
w = pywt.Wavelet(wavelet)
mlab.set_variable('wavelet', wavelet)
if size_set == 'full':
... |
weylin/CloudBot | cloudbot/util/timeparse.py | Python | gpl-3.0 | 6,244 | 0.000961 | """
timeparse.py
Implements a single function, `timeparse`, which can parse various
kinds of time expressions.
Created By:
- Will Roberts <wildwilhelm@gmail.com>
Maintainer:
- Luke Rogers <https://github.com/lukeroge>
License:
MIT License
Copyright Will Roberts <wildwilhelm@gmail.com> - 1 February, ... | TORS)
OPT_SEP = lambda x: r'(?:{x}\s*(?:{SEPARATORS | }\s*)?)?'.format(
x=x, SEPARATORS=SEPARATORS)
TIME_FORMATS = [
r'{WEEKS}\s*{DAYS}\s*{HOURS}\s*{MINS}\s*{SECS}'.format(
# YEARS=OPT_SEP(YEARS),
# MONTHS=OPT_SEP(MONTHS),
WEEKS=OPT_SEP(WEEKS),
DAYS=OPT_SEP(DAYS),
HOURS=OPT_SEP(HOURS),
MINS=OPT_SEP(MINS),
SE... |
mattja/sdeint | sdeint/wiener.py | Python | gpl-3.0 | 10,384 | 0.001637 | # Copyright 2015 Matthew J. Aburn
#
# 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 later version. See <http://www.gnu.org/licenses/>.
... | factor1 = np.dot(Km0, Pm0 - np.eye(m**2))
factor1 = broadcast_to(factor1, (N, M, m**2))
factor2 = _kp(Yk + np.sqrt(2.0/h)*dW, Xk)
return _dot(factor1, factor2)/k
de | f _sigmainf(N, h, m, dW, Km0, Pm0):
r"""Asymptotic covariance matrix \Sigma_\infty Wiktorsson2001 eqn (4.5)"""
M = m*(m-1)//2
Im = broadcast_to(np.eye(m), (N, m, m))
IM = broadcast_to(np.eye(M), (N, M, M))
Ims0 = np.eye(m**2)
factor1 = broadcast_to((2.0/h)*np.dot(Km0, Ims0 - Pm0), (N, M, m**2))... |
storytime/openvpn-server-utils | openvpn/conf_generator.py | Python | mit | 1,782 | 0.004489 | #!/usr/bin/python
import sys
import subprocess
import os
import commands
CLIENT_CN = sys.argv[1]
SEP = '==========> '
OVPN_ROOT='/etc/openvpn/'
ERSA=OVPN_ROOT+'easy-rsa-release-2.x/easy-rsa/2.0/keys/'
IP_PLACEHOLDER = 'placeholder_ip'
TA_PLACEHOLDER = 'placeholder_ta'
CA_PLACEHOLDER = 'placeholder_ca'
CL_KEY_PLACEHO... |
#contents = open(CONFIG_TEMPLATE, "r+").read()
conf = open(RES_FILE, 'w+')
# tls key
taKey = open(TA_FILE, 'r').read()[:-1]
# CA isnt encrypted
serverCa = open(CA, 'r').read()[:-1]
# client key
clientKey = open(CLIENT_KEY_FILE, 'r').read()[:-1]
# client cert
clientCert = open(CLIENT_CER_FILE, 'r').read()[:-1]
# serve... | ultConfig.replace(CA_PLACEHOLDER, serverCa)
resultConfig = resultConfig.replace(CL_KEY_PLACEHOLDER, clientKey)
resultConfig = resultConfig.replace(CL_CR_PLACEHOLDER, clientCert)
resultConfig = resultConfig.replace(IP_PLACEHOLDER, serverIp)
conf.write(resultConfig)
conf.close()
open(OVPN_ROOT+'ccd/'+CLIENT_CN, 'w').clo... |
amaiagiralt/amaiagiralt | upload.py | Python | mit | 140 | 0.014286 | #!/usr/bin/python
import os
os.s | ystem('git add -A && git commit -m "Working on changes in my website ( | Amaia)" && git push origin master');
|
ndparker/rcssmin | gen_chartable.py | Python | apache-2.0 | 2,753 | 0.000363 | #!/usr/bin/env python
u"""
=========================================
Character table generator for rcssmin.c
=========================================
Character table generator for rcssmin.c
:Copyright:
Copyright 2011 - 2021
Andr\xe9 Malo or his licensors, as applicable
:License:
Licensed under the Apache Lice... | if _re.match(escaped, c):
mask |= 4
if _re.match(space, c):
mask |= 8
if _re.match(string_dull, c):
mask |= 16
if _re.match(nmchar, c):
mask |= 32
if _re.match(uri_dull, c):
mask |=... | 56
if mask < 10:
mask = ' ' + str(mask)
elif mask < 100:
mask = ' ' + str(mask)
maskline.append(str(mask))
if y == 7:
charmask.append(', '.join(maskline))
maskline = []
charmask.append(', '.join(mas... |
neilswainston/PathwayGenie | twist/client.py | Python | mit | 7,797 | 0 | '''
PathwayGenie (c) GeneGenie Bioinformatics Ltd. 2018
PathwayGenie is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
import random
import sys
... | 'name': name,
'type': typ,
'insertion_point_mes_uid': 'na',
'vector_mes_uid': 'na',
'column': idx / 8,
'row': idx | % 8,
'plate': idx / 96}
constructs.append(construct)
return constructs
def main(args):
'''''main method.'''
client = TwistClient(args[0], args[1])
addresses = client.get_addresses()
payments = client.get_payments()
print('Accounts\t' + str(client... |
appu1232/Selfbot-for-Discord | cogs/emoji.py | Python | mit | 7,238 | 0.00373 | import discord
import requests
import io
import re
from discord.ext import commands
'''Tools relating to custom emoji manipulation and viewing.'''
class Emoji:
def __init__(self, bot):
self.bot = bot
def find_emoji(self, msg):
msg = re.sub("<a?:(.+):([0-9]+)>", "\\2", msg)
color_mod... | ()
@emoji.command(pass_context=True, aliases=["steal"])
@commands.has_permissions(manage_emojis=True)
async def copy(self, ctx, *, msg):
aw | ait ctx.message.delete()
msg = re.sub("<:(.+):([0-9]+)>", "\\2", msg)
match = None
exact_match = False
for guild in self.bot.guilds:
for emoji in guild.emojis:
if msg.strip().lower() in str(emoji):
match = emoji
if msg.stri... |
nirvn/QGIS | python/plugins/processing/algs/grass7/ext/r_null.py | Python | gpl-2.0 | 2,191 | 0.000458 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_null.py
---------------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
****************************... | *********************************************************************
"""
from builtins im | port str
__author__ = 'Médéric Ribreux'
__date__ = 'February 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
def checkParameterValuesBeforeExecuting(alg, parameters, context):
""" Verify if we have the right param... |
cooncesean/remotestatus | build/lib/remotestatus/conf.py | Python | mit | 376 | 0.007979 | from django.conf import settings
STATUS | _DOWN = 'down'
STATUS_UP = 'up'
# Frequency with which checks will be made to the remote boxes (default is 10 min.)
REMOTE_CHECK_FREQUENCY = getattr(settings, 'RS_REMOTE_CHECK_FREQUENCY', 10 * 60 * 60)
DEFAULT_KEY_FILE = getattr(settings, 'RS_KEY_FILE', None)
DEFAULT_ | KNOWN_HOSTS_FILE = getattr(settings, 'RS_KNOWN_HOSTS_FILE', None)
|
logust79/phenopolis | views/igv.py | Python | mit | 3,126 | 0.019194 | from views import *
from lookups import *
import requests
import re
from utils import *
import itertools
from config import config
if config.IMPORT_PYSAM_PRIMER3:
import pysam
import csv
#hpo lookup
import random
from flask import Response, request
import os
from werkzeug.datastructures import Headers
import re
@a... | print(request.method)
headers=Headers()
#headers.add('Content-Type','application/octet-stream')
headers.add('Content-Transfer-Encoding','binary')
#Date:Wed, 06 Jul 2016 17:19:52 GMT
#ETag:"flask-1446310274.0-12661331-649139018"
#Expires:Thu, 07 Jul 2016 05:19:52 GMT
#Keep-Alive:timeout=5, ... | mod_wsgi/3.4 Python/2.7.8
headers.add('X-Frame-Options','SAMEORIGIN')
if sample=='gencode.v19.sorted.bed':
bamfile=BAM_FILES+'/gencode.v19.sorted.bed'
elif sample=='gencode.v19.sorted.bed.idx':
bamfile=BAM_FILES+'/gencode.v19.sorted.bed.idx'
elif sample.endswith('.bai'):
bamfile... |
xrmx/pylokit | setup.py | Python | mpl-2.0 | 1,072 | 0.002799 | from setuptools import setup, find_packages
import os
VERSION = "0.8.1"
CLASSIFIERS = [
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Licen | se :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Operating System :: OS Independent',
'Programmin | g Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Office/Business :: Office Suites',
]
setup(
author="Riccardo Magliocchetti",
author_email="riccardo.magliocchetti@gmail.com",
name='pylokit',
version=VERSION,
description='Python CFFI wrapper fo... |
alirizakeles/zato | code/zato-server/src/zato/server/service/internal/http_soap.py | Python | gpl-3.0 | 31,245 | 0.005249 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2011 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
from contextlib import closing
from json import dumps
from traceback imp... | with closing(self.odb.session()) as session:
self.response.payload[:] = self.get_data(session)
class _CreateEdit(AdminService, _HTTPSOAPService):
def add_tls_ca_cert(self, input, sec_tls_ca_cert_id):
with closing(self.odb.session()) as session:
input.sec_tls_ca_cert_name = s... |
"""
class SimpleIO(AdminSIO):
request_elem = 'zato_http_soap_create_request'
response_elem = 'zato_http_soap_create_response'
input_required = ('cluster_id', 'name', 'is_active', 'connection', 'transport', 'is_internal', 'url_path')
input_optional = ('service', 'security_id', 'm... |
ntduong/ML | Misc/naivebayes.py | Python | mit | 2,081 | 0.010091 | """ Simple implementation of mutinomial Naive Bayes for text classfification.
TODO: Apply to 20 Newsgroups, Reuters-21578 datasets
"""
__author__ = 'Duong Nguyen'
__version__ = '0.0'
import math
import sys
from collections import defaultdict
class NaiveBayes(object):
""" Multinomial Naive Bayes"""
def... | cat)) # + sum_i log P(word_i|ca | t)
return score
def classify(self, doc):
""" Classify doc by argmax_cat log P(cat|doc).
"""
best = None
maxP = -sys.maxint
for cat in self.categories:
p = self.docProb(doc, cat)
if p > maxP:
maxP =... |
czhengsci/pymatgen | pymatgen/core/bonds.py | Python | mit | 4,331 | 0.000231 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of | the MIT License.
from __future__ import division, unicode_literals
import os
import json
import collections
import warnings
from pymatgen.core.periodic_table import get_el_sp
"""
This class implements definitions for various kinds of bonds. Typically used in
Molecule analysis.
"""
__author__ = "Shyue Ping Ong"
__c... | ail.com"
__date__ = "Jul 26, 2012"
def _load_bond_length_data():
"""Loads bond length data from json file"""
with open(os.path.join(os.path.dirname(__file__),
"bond_lengths.json")) as f:
data = collections.defaultdict(dict)
for row in json.load(f):
els = ... |
renfredxh/compilebot | compilebot/tests/__init__.py | Python | apache-2.0 | 34 | 0 | __ | all__ = ['unit', 'integration'] | |
kernel72/tastypie-mongoengine-resource | tastypieMongoengineResource.py | Python | bsd-3-clause | 4,975 | 0.002211 | __author__ = 'kernel-72'
from mongoengine import InvalidQueryError, NotUniqueError
from tastypie.authentication import MultiAuthentication, Authentication, SessionAuthentication
from tastypie.authorization import Authorization
from tastypie.bundle import Bundle
from tastypie.exceptions import BadRequest, NotFound
from... | if not applicable_filters:
return self.get_object_list(request).all() |
result = self.get_object_list(request).filter(**applicable_filters.dict())
return result
def apply_sorting(self, obj_list, options=None):
if options is None:
options = {}
if 'order_by' not in options:
return obj_list
if hasattr(options, 'getlist')... |
chrisdjscott/Atoman | atoman/filtering/atomStructure.py | Python | mit | 221 | 0 | from __future__ import unico | de_literals
# this must correspond to "atom_structures.h"
knownStructures = [
"disordered",
"FCC",
"HCP",
"BCC",
"ico | sahedral",
"sigma11_tilt1",
"sigma11_tilt2",
]
|
535521469/crawler_sth | dirbot/settings.py | Python | bsd-3-clause | 213 | 0 | # Scrapy settings | for dirbot project
SPIDER_MODULES = ['dirbot.spiders']
NEWSPIDER_MODULE = 'dirbot.spiders'
DEFAULT_ITEM_CLASS = 'dirbot.items.Website'
ITEM_PIPELINES = ['dirbot.pipelines.FilterWordsPipel | ine']
|
IronLanguages/ironpython3 | Tests/test_pep380_stdlib.py | Python | apache-2.0 | 4,035 | 0.009418 | # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
##
## Run selected tests from test_pep380 from StdLib
##
import unittest
import sys
from iptest import run_tes... | ing_exception_while_delegating_send'))
suite.addTest(test.test_pep380.TestPEP380Operation('test_next_and_return_with_value'))
suite.addTest(test.test_pep380.TestPEP380Operation('test_raising_exception_in_delegated_next_call'))
suite.addTest(test.test_pep380.TestPEP380Operation('test_raising_exce... | .test_pep380.TestPEP380Operation('test_send_and_return_with_value'))
suite.addTest(test.test_pep380.TestPEP380Operation('test_send_tuple_with_custom_generator'))
suite.addTest(test.test_pep380.TestPEP380Operation('test_throwing_GeneratorExit_into_subgen_that_raises'))
suite.addTest(test.test_pep... |
alphacsc/alphacsc | alphacsc/other/sporco/sporco/admm/cmod.py | Python | bsd-3-clause | 8,925 | 0.002017 | # -*- coding: utf-8 -*-
# Copyright (C) 2015-2017 by Brendt Wohlberg <brendt@ieee.org>
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""ADMM algorithm for the CMO... | lf.Y = self.Pcn(self.AX + self.U)
def eval_objfn(self):
"""Compute components of objective function as well as total
contribution to objective function.
"""
dfd = self.obfn_dfd()
cns = self.obfn_cns()
return (dfd, cns)
def obfn_dfd(self):
r"""Comput... | .S))**2
def obfn_cns(self):
r"""Compute constraint violation measure :math:`\| P(\mathbf{y}) -
\mathbf{y}\|_2`.
"""
return linalg.norm((self.Pcn(self.obfn_gvar()) - self.obfn_gvar()))
def rhochange(self):
"""Re-factorise matrix when rho changes"""
self.lu,... |
lucasgit/rl | TD/src/acrobot.py | Python | mit | 13,546 | 0.025543 | '''
Created on Jan 11, 2016
@author: Lucas Lehnert (lucas.lehnert@mail.mcgill.ca)
Control on the Acrobot domain.
'''
import numpy as np
import matplotlib.pyplot as plt
from mdp import MDPContinuousState
from basisfunction import getTiledStateActionBasisFunction
from policy import BoltzmannPolicy
from qlearning impo... | beta = 0.01
# traceLambda = 0.0
temp = 0.5
controlPolicy = BoltzmannPolicy( mdp.getActionSpace(), temperature= | temp )
# controlPolicy = GreedyPolicy( mdp.getActionSpace() )
initTheta = np.zeros( len( phi( mdp.getStateSpace()[0], mdp.getActionSpace()[0] ) ) )
# agent = SARSA( mdp.getGamma(), controlPolicy, traceLambda=traceLambda, basisFunction=phi, \
# initTheta=initTheta, alpha=alpha )
# agent = ... |
lanrat/SpiderWho | config.py | Python | gpl-2.0 | 2,331 | 0.001287 | '''Python module to contain all configuration settings for SpiderWho'''
'''Debug Mode'''
DEBUG = False
''' When printing display DPS or LPS '''
DPS = True
'''Enable checking result with EMAIL_REGEX'''
RESULT_VALIDCHECK = False
'''Regex used for whois validation when email check is enabled'''
EMAIL_REGEX = r'[\w.-]+... | DELAY'''
WHOIS_SERVER_SLEEP_DELAY = 5
'''Amount of seconds to give each whois query before failing'''
WHOIS_TIMEOUT_SECONDS = 10
'''Amount of seconds to wait before trying to reconnect to a failed proxy'''
PROXY_FAIL_RECONNECT_DELAY = 20
''' How many mi | nutes to wait before trimming whois history '''
WHOIS_HISTORY_TRIM_MINUTES = 15
''' Saves the tar.gz output format '''
SAVE_TAR = True
''' Numer of results to put in tar file befor rotating '''
SAVE_TAR_SIZE = 500000
''' Split Thick and Thin results '''
SPLIT_THICK = False
'''
list of servers who are known to be ... |
dasseclab/dasseclab | clones/routersploit/tests/creds/cameras/jvc/test_ftp_default_creds.py | Python | gpl-2.0 | 612 | 0 | from routersploit.modules.creds.cameras.jvc.ftp_default_creds import | Exploit
def test_check_success(generic_target):
""" Test scenario - testing against FTP server """
exploit = Exploit()
assert exploit.target == ""
assert exploit.port == 21
assert exploit.threads == 1
assert exploit.defaults == ["admin:jvc"]
assert exploit.stop_on_success is True
ass... | ne
assert exploit.run() is None
|
bmvdgeijn/WASP | mapping/get_as_counts.py | Python | apache-2.0 | 12,858 | 0.003733 | import sys
import argparse
import numpy as np
import pysam
import util
import snptable
import tables
import os
def write_results(out_f, chrom_name, snp_tab, ref_matches,
alt_matches, oth_matches, geno_sample):
haps = None
has_haps = False
if geno_sample:
# get index for t... | has_haps = True
sys.stderr.write("geno_hap_idx: %s\n" % repr(geno_hap_idx))
else:
sys.stderr.write("WARNING: sample %s is not present for "
"chromosome %s\n" % (geno_sample, chrom_name))
haps = None
has_haps = False
for i in... | geno_str = "NA"
out_f.write("%s %d %s %s %s %d %d %d\n" %
(chrom_name, snp_tab.snp_pos[i],
snp_tab.snp_allele1[i], snp_tab.snp_allele2[i],
geno_str, ref_matches[i], alt_matches[i],
oth_matches[i]))
def write_header(out... |
aadamski/presence-analyzer-aadamski | src/presence_analyzer/script.py | Python | mit | 3,701 | 0 | # -*- coding: utf-8 -*-
"""Startup utilities"""
import os
import sys
from functools import partial
import paste.script.command
import werkzeug.script
etc = partial(os.path.join, 'parts', 'etc')
DEPLOY_INI = etc('deploy.ini')
DEPLOY_CFG = etc('deploy.cfg')
DEBUG_INI = etc('debug.ini')
DEBUG_CFG = etc('debug.cfg')
_... | from werkzeug.debug import DebuggedApplication
app = make_app(global_conf, config=DEBUG_CFG, debug=True)
return DebuggedApplication(app, evalex=True)
# bin/flask-ctl shell
def make_shell():
"""Interactive Flask Shell"""
from flask import request
from presence_analyzer.main import init_db as initd... | uest_context
return locals()
def _init_db(debug=False, dry_run=False):
"""Initialize the database."""
from presence_analyzer.main import init_db
print 'init_db()'
if dry_run:
return
# Configure the application
if debug:
make_debug()
else:
make_app()
# Create... |
roadmapper/ansible | lib/ansible/modules/packaging/language/yarn.py | Python | gpl-3.0 | 11,924 | 0.001593 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017 David Gunter <david.gunter@tivix.com>
# Copyright (c) 2017 Chris Hoffman <christopher.hoffman@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
_... | cation
- name: Install "imagemin" node.js package on version 5.3.1
yarn:
name: imagemin
version: '5.3.1'
path: /app/location
- name: Install "imagemin" node.js package globally.
yarn:
name: imagemin
global: yes
- name: Remove the globally-installed package "imagemin".
yarn:
name: imagem... | tall "imagemin" node.js package from custom registry.
yarn:
name: imagemin
registry: 'http://registry.mysite.com'
- name: Install packages based on package.json.
yarn:
path: /app/location
- name: Update all packages in package.json to their latest version.
yarn:
path: /app/location
state: la... |
KT26/PythonCourse | 6. User Input and While Loops/8.py | Python | mit | 465 | 0.010753 | # Created by PyCharm Pro Edition
# User: Kaushik Talukdar
# Date: 01-04-17
# Time: 03:10 AM
# Using continue
# continue will send the loop back to its root |
nos = 0
while nos < 10:
nos += 1
if nos%2 == 0:
continue
print(nos)
# AVOID INFINITE LOOP
# if the loop has no condition that can end, the loop will run infinitely
# here if we | forgot to add "nos += 1, the loop will become infinite loop |
robot-republic/staticgenerator | setup.py | Python | mit | 329 | 0.006079 | from distutils.core import setup
vers | ion = '1.3.3'
setup(name='staticgenerator',
version=version,
description="StaticGenerator for Django",
author="Jared Kuolt",
author_email="me@superjared.com",
url="http://superjared.com/projects/static-ge | nerator/",
packages = ['staticgenerator']
)
|
kevinwang/moca | createcorpus_textretrieval.py | Python | mit | 3,070 | 0.042997 | import glob, os
import pysrt
from gensim import corpora, models, similarities
from collections import defaultdict
from pprint import pprint
import nltk.tokenize
from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
import csv
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
p_stemmer = Por... | ect])))
aggregate | [lect][m] = best_topic
lec_ids = {'1-1':11,'1-2':23,'2-1':25,'2-2':27,'2-3':29,'2-4':31,'2-5':19,'2-6':33,'2-7':35,'2-8':37,'2-9':39,
'3-1':41,'3-2':43,'3-3':45,'3-4':47,'3-5':49,'3-6':51,'3-7':59,'3-8':53,'3-9':55,
'4-1':61,'4-2':67,'4-3':65,'4-4':77,'4-5':79,'4-6':69,'4-7':117,'4-8':73,'4-9':75,'4-10':81,
'5-1':101,... |
ScottHull/Exoplanet-Pocketknife | old/hefesto_temp_fix.py | Python | cc0-1.0 | 1,250 | 0.0048 | import os
def replace_temp(inputfile_folder):
os.chdir(inputfile_folder)
home_dir = os.getcwd()
for i in os.listdir(os.getcwd()):
| if os.path.isdir(i):
os.chdir | (i)
print("In folder: {}".format(os.getcwd()))
for z in os.listdir(os.getcwd()):
if '.txt' in z:
with open(z, 'r') as infile:
with open("temp.txt", 'w') as outfile:
print("\nChanging string in file: {}".forma... |
estaban/pyload | module/plugins/captcha/captcha.py | Python | gpl-3.0 | 9,726 | 0.003701 | # -*- coding: utf-8 -*-
#
#Copyright (C) 2009 kingzero, RaNaN
#
#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 later version.
#
#This pro... | if count < allowed:
pixels[x, y] = 1
# second pass: this time set all 1's to 255 (white)
for x in xrange(w):
for y in xrange(h):
if pixels[x, y] == 1:
pi | xels[x, y] = 255
self.pixels = pixels
def derotate_by_average(self):
"""rotate by checking each angle and guess most suitable"""
w, h = self.image.size
pixels = self.pixels
for x in xrange(w):
for y in xrange(h):
if pixels[x, y] == 0:
... |
cantora/pyc | p0tests/grader_tests/reg_alloc_0.py | Python | gpl-3.0 | 86 | 0.011628 | z = 4
w = 0 |
z1 = 1
x = w + z1 # x = | 1
y = x + 1 # y = 2
w1 = y # w1 = 2
print w1
|
xdevelsistemas/taiga-back-community | taiga/stats/services.py | Python | agpl-3.0 | 6,986 | 0.003006 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Taiga Agile LLC <support@taiga.io>
# This program 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)... | = model.objects.all()
stats = OrderedDict()
today = timezone.now()
yesterday = today - timedelta(days=1)
seven_days_ago = yesterday - timedelta(days=7)
stats["total"] = queryset.count()
stats["today"] = queryset | .filter(created_date__year=today.year,
created_date__month=today.month,
created_date__day=today.day).count()
stats["average_last_seven_days"] = (queryset.filter(created_date__range=(seven_days_ago, yesterday))
... |
couchbase/perfrunner | unittests.py | Python | apache-2.0 | 28,115 | 0.000854 | import glob
import json
import pkg_resources
from collections import defaultdict, namedtuple
from multiprocessing import Value
from unittest import TestCase
import snappy
from perfrunner.settings import ClusterSpec, TestConfig
from perfrunner.workloads.bigfun.query_gen import new_queries
from perfrunner.workloads.tcm... | ccess=100, working_set_moving_docs=0,
key_fmtr='decimal')
keys = []
for worker in range(ws.workers):
generator = docgen.SequentialKey(worker, ws, prefix='test')
keys += [key.string for key in generator]
expected = [docgen.Key(number=i, pref... | mal').string
for i in range(ws.items)]
|
PseudoAj/MyInsightRepo | data/src/electricityTest.py | Python | mit | 963 | 0.012461 | #!/usr/bin/env python
#title :electricityTest.py
#description :Class to test the electricity logic
#author :Ajay Krishna Teja Kavuri
#date :01222017
#version :0.1
#==============================================================================
# Libraries
import unittest
from ele... | elf.thisElec = Electricity()
# Test for the list to csv
def testConvrtLstToCSV(self):
# Define a list
testList = ["a","b","c"]
# Pass the list
testCSV = self.thisElec.convrtLstToCSV(testList)
# check for the right execution
self.assertEqual(testCSV, "a,b,c")
... | # initite and run the unittest
unittest.main()
|
pombredanne/dxr | dxr/plugins/rust/menu.py | Python | mit | 6,324 | 0.003479 | import os
from functools import partial
from warnings import warn
from dxr.utils import browse_file_url, search_url
def quote(qualname):
""" Wrap qualname in quotes if it contains spaces """
if ' ' in qualname:
qualname = '"' + qualname + '"'
return qualname
def truncate_value(value, typ=""):
... | %s' % target_name,
'title': "Jump to %s in '%s'" % (target_name,
os.path.basename(path)),
'href': browse_file_url(tree_config.name, path, _anchor=int(row)),
'icon': 'jump'}
def jump_to_target_from_decl(menu_maker, tree, decl):
"""Ret... | rrant the creation of a menu,
return None.
"""
path = decl['file_name']
if path:
return menu_maker(tree, path, decl['file_line'])
else:
warn("Can't add jump to empty path.") # Can this happen?
jump_to_trait_method_menu_item = partial(jump_to_target_menu_item, target_name='trait m... |
koppa/gr-air-modes | python/__init__.py | Python | gpl-3.0 | 3,039 | 0.009872 | #
# Copyright 2008,2009 Free Software Foundation, Inc.
#
# This application 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, or (at your option)
# any later version.
#
# This application is ... | ImportError:
print "gr-air-modes warning: numpy+scipy not installed, FlightGear interface not supported"
pass
# --------- | -------------------------------------------------------
# Tail of workaround
if _RTLD_GLOBAL != 0:
sys.setdlopenflags(_dlopenflags) # Restore original flags
# ----------------------------------------------------------------
|
dsm054/pandas | pandas/tests/tools/test_to_datetime.py | Python | bsd-3-clause | 98,109 | 0.001244 | """ test to_datetime """
import calendar
from collections import deque
from datetime import (
datetime,
timedelta,
)
from decimal import Decimal
import locale
from dateutil.parser import parse
from dateutil.tz.tz import tzoffset
import numpy as np
import pytest
import pytz
from pandas._libs import tslib
from... | ["19801222", "20010112", "NaT"],
# Null values with Integers
[19801222, 20010112, None],
[19801222, 20010112, np.nan],
[19801222, 20010112, NaT],
[19801222, 20010112, "NaT"],
],
)
def test_to_datetime_format_YYYYMMDD_with_none(self, input_s):... | ith None
expected = Series([Timestamp("19801222"), Timestamp("20010112"), NaT])
result = Series(to_datetime(input_s, format="%Y%m%d"))
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"input_s, expected",
[
# NaN before strings with invalid date... |
openstack/vitrage | vitrage/api/controllers/rest.py | Python | apache-2.0 | 1,420 | 0 | # Copyright 2016 - Nokia
#
# 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, sof... | d under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import oslo_messaging
import pecan
from pecan import rest
class RootRestController(... | gs, request=None):
"""All requests go through here
We can check the backend status
"""
if not pecan.request.check_backend:
return super(RootRestController, self)._route(args, request)
try:
client = pecan.request.client.prepare(timeout=5)
bac... |
Laurawly/tvm-1 | tests/micro/arduino/conftest.py | Python | apache-2.0 | 2,694 | 0.001114 | # 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 u... | hoices=ARDUINO_BOARDS.keys(),
help="Arduino board for tests.",
| )
parser.addoption(
"--arduino-cli-cmd",
default="arduino-cli",
help="Path to `arduino-cli` command for flashing device.",
)
parser.addoption(
"--test-build-only",
action="store_true",
help="Only run tests that don't require physical hardware.",
)
pars... |
bengosney/rhgd3 | banner_messages/migrations/0004_auto_20200413_0736.py | Python | gpl-3.0 | 416 | 0 | # Generated by Django 3.0.5 on 2020-04-13 07:36
from django | .db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('banner_messages', '0003_m | essage_slug'),
]
operations = [
migrations.AlterField(
model_name='message',
name='message',
field=models.TextField(max_length=1280, verbose_name='Message'),
),
]
|
pexip/jostedal | jostedal/stun/client.py | Python | mit | 3,811 | 0.001574 | from twisted.internet import defer
from jostedal.stun.agent import StunUdpProtocol, Message
from jostedal.stun.authentication import CredentialMechanism
from jostedal import stun
from jostedal.stun import attributes
import logging
logger = logging.getLogger(__name__)
class StunUdpClient(StunUdpProtocol):
def __... | hentication processing (sec. 10)
# error code 300 -> 399; SHOULD fail unless ALTERNATE-SERVER (sec 11)
# error code 400 -> 499; transaction failed (420, UNKNOWN ATTRIBUTES contain info)
# error code 500 -> 599; MAY resend, but MUST limit number of retries
transaction.fail... | red.callback
def __init__(self, request, addr):
defer.Deferred.__init__(self)
self.transaction_id = request.transaction_id
self.request = request
self.addr = addr
def time_out(self):
if not self.called:
self.fail(TransactionError("Timed out"))
|
dajohnso/cfme_tests | utils/providers.py | Python | gpl-2.0 | 16,707 | 0.003112 | """ Helper functions related to the creation, listing, filtering and destruction of providers
The list_providers function in this module depend on a (by default global) dict of filters.
If you are writing tests or fixtures, you want to depend on this function as a de facto gateway.
The rest of the functions, such as ... | erFilter(object):
""" Filter used to obtain only providers matching given requirements
Args:
keys: List of acceptable provider keys, all if `None`
categories: List of acceptable prov | ider categories, all if `None`
types: List of acceptable provider types, all if `None`
required_fields: List of required fields, see :py:func:`providers_by_class`
restrict_version: Checks provider version in yamls if `True`
required_tags: List of tags that must be set in yamls
in... |
ahkab/ahkab | ahkab/symbolic.py | Python | gpl-2.0 | 24,396 | 0.001107 | # -*- coding: iso-8859-1 -*-
# symbolic.py
# Symbolic simulation module
# Copyright 2010-2013 Giuseppe Venturini
# This file is part of the ahkab simulator.
#
# Ahkab 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 Found... | =3):
"""Attempt a symbolic, small-signal solution of the circuit.
**Parameters:**
circ | : circuit instance
the circuit instance to be simulated.
source : string, optional
the ``part_id`` of the source to be used as input for the transfer
function. If ``None``, no transfer function is evaluated.
ac_enable : bool, optional
take frequency dependency into considera... |
josl/ASM_challenge | isolates/template.py | Python | apache-2.0 | 1,025 | 0 | metadata = {
"sample_name": "",
"group_name": "",
"file_names": "",
"sequencing_platform": "",
"sequencing_type": "",
"pre_assembled": "",
"sample_type": "",
"organism": "",
"strain": "",
"subtype": {},
"country": "",
"region": "",
"city": "",
"zip_code": "",
... | "isolation_source": "",
"source_note": "",
"pathogenic": "",
"pathogenicity_note": "",
"collection_date": "",
"collected_by": "",
"usage_restrictions": "",
"release_date": "",
"email_address": "",
"notes": "",
"batch": "true"
}
default = {
"mandatory": [
"sequenc... | unknown",
"isolation_source": "unknown",
"sample_type": "isolate",
"organism": "",
"pathogenic": "yes",
"usage_restrictions": "public"
}
}
|
jarv/cmdchallenge-site | lambda_src/runcmd/docker/types/containers.py | Python | mit | 20,507 | 0.000098 | import six
import warnings
from .. import errors
from ..utils.utils import (
convert_port_bindings, convert_tmpfs_mounts, convert_volume_binds,
format_environment, normalize_links, parse_bytes, parse_devices,
split_command, version_gte, version_lt,
)
from .base import DictType
from .healthcheck import Heal... | oft, int):
raise ValueError("Ulimit.soft must be | an integer")
if hard and not isinstance(hard, int):
raise ValueError("Ulimit.hard must be an integer")
super(Ulimit, self).__init__({
'Name': name,
'Soft': soft,
'Hard': hard
})
@property
def name(self):
return self['Name']
@n... |
mandeepdhami/neutron | neutron/agent/l3/dvr_local_router.py | Python | apache-2.0 | 20,535 | 0.000195 | # Copyright (c) 2015 Openstack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with th | e 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
# WARRANTIE | S OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import binascii
import netaddr
from oslo_log import log as logging
from oslo_utils import excutils
from neutron.agent.l3 import dvr_fip_ns
from neutron.... |
happyleavesaoc/aoc-mgz | mgz/header/unit_type.py | Python | mit | 6,598 | 0.000303 | """Unit Types."""
from construct import (
Struct, Float32l, Int16ul, Byte, Embedded, Switch, If,
Int32ul, Array, String, Padding, IfThenElse, this
)
from mgz.util import find_version, find_save_version, Version
attribute = "attribute"/Struct(
"type"/Int16ul,
"amount"/Float32l,
"flag"/Byte
)
damage... | "displayed_armour"/Int16ul,
"displayed_attack"/Int16ul,
| "displayed_range"/Float32l,
"displayed_reload_time"/Float32l
)
missile = "missile"/Struct(
base_combat,
"missile_type"/Byte,
"targeting_type"/Byte,
"missile_hit_info"/Byte,
"missile_die_info"/Byte,
"area_effect_specials"/Byte,
"ballistics_ratio"/Float32l
)
attribute_cost = "cost"/St... |
mwreuter/arcade | doc/source/examples/sprite_move_walls.py | Python | mit | 3,207 | 0 | """
Sprite Move With Walls
Simple program to show basic sprite usage.
Artwork from http://kenney.nl
"""
import random
import arcade
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
MOVEMENT_SPEED = 5
window = None
class MyApplication(arcade.Window):
""" Main application class. """
def setup(... | .LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
def animate(self, delta_time):
""" Movement and game logic """
# Call update on all sprites (The sprites don't do much in this
# example though.)
self.physics_engine.update()
window = MyApplication(SCRE... | run()
|
BlueBrain/NeuroM | neurom/core/neuron.py | Python | bsd-3-clause | 324 | 0.003086 | " | ""For backward compatibility only."""
# pylint: skip-file
from | neurom.core.morphology import * # pragma: no cover
from neurom.utils import deprecated_module # pragma: no cover
deprecated_module('Module `neurom.core.neuron` is deprecated. Use `neurom.core.morphology`'
' instead.') # pragma: no cover
|
cambridgehackers/connectal | scripts/preprocess_trace.py | Python | mit | 4,872 | 0.001026 | #! /usr/bin/env python
# Copyright (c) 2014 Quanta Research Cambridge, Inc
# Original author John Ankcorn
#
# 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 with... | pactual = []
for ch in param[1:]:
if informat:
if ch == '"':
if level == 0:
informat = Fa | lse
else:
formatstr = formatstr + ch
elif ch == ',':
if pitem != '':
pactual.append(pitem.strip())
pitem = ''
else:
pitem = pite... |
rsms/smisk | lib/smisk/serialization/xmlbase.py | Python | mit | 4,263 | 0.020174 | # encoding: utf-8
'''XML support.
'''
import logging
from smisk.serialization import serializers, data, Serializer, SerializationErro | r, UnserializationError
from smisk.core import Application
try: import xml.etree.cElementTree as ET
except ImportError:
try: import xml.etree.ElementTree as ET
except ImportError:
try: import cElementTree as ET
| except ImportError:
try: import elementtree.ElementTree as ET
except ImportError:
try: import lxml.etree as ET
except ImportError:
ET = None
log = logging.getLogger(__name__)
__all__ = ['ET', 'serializers', 'data',
'XMLSerializer', 'XMLSerializationError', 'XMLUnserializationE... |
ravibhure/ansible | lib/ansible/modules/web_infrastructure/ansible_tower/tower_inventory.py | Python | gpl-3.0 | 3,846 | 0.00234 | #!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... | er) for an overview.
options:
name:
description:
- The name to use for the inventory.
required: True
description:
description:
- The description to use for the inventory.
required: | False
default: null
organization:
description:
- Organization the inventory belongs to.
required: True
variables:
description:
- Inventory variables. Use '@' to get from file.
required: False
default: null
state:
description:
- Desired state ... |
ntuecon/server | pyenv/Scripts/pywin32_testall.py | Python | bsd-3-clause | 3,477 | 0.002876 | """A test runner for pywin32"""
import sys
import os
import distutils.sysconfig
import win32api
# locate the dirs based on where this script is - it may be either in the
# source tree, or in an installed Python 'Scripts' tree.
this_dir = os.path.dirname(__file__)
site_packages = distutils.sysconfig.get_python... | cript '%s' in one of %s"
% (script, possible_locations))
if __name__=='__main__':
# win32
maybes = [os.path.join(this_dir, "win32", | "test"),
os.path.join(site_packages, "win32", "test"),
]
find_and_run(maybes, 'testall.py')
# win32com
maybes = [os.path.join(this_dir, "com", "win32com", "test"),
os.path.join(site_packages, "win32com", "test"),
]
find_and_run(maybes, 'tes... |
rwl/PyCIM | CIM14/IEC61968/PaymentMetering/CashierShift.py | Python | mit | 5,075 | 0.001773 | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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... | self._Receipts = []
self.Receipts = [] if Receipts is None else Receipts
self._Transactions = []
self.Transactions = [] if Transactions is None else Transactions
self._Cashier = None
self.Cashier = Cashier
self._PointOfSale = None
self.PointOfSale = PointO... | defaults = {"cashFloat": 0.0}
_enums = {}
_refs = ["Receipts", "Transactions", "Cashier", "PointOfSale"]
_many_refs = ["Receipts", "Transactions"]
def getReceipts(self):
"""All Receipts recorded for this Shift.
"""
return self._Receipts
def setReceipts(self, value):
... |
femtotrader/ig-markets-stream-api-python-library | trading_ig/config.py | Python | bsd-3-clause | 1,350 | 0.001481 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import logging
ENV_VAR_ROOT = "IG_SERVICE"
CONFIG_FILE_NAME = "trading_ig_config.py"
logger = logging.getLogger(__name__)
class ConfigEnvVar(object):
def __init__(self, env_var_base):
| self.ENV_VAR_BASE = env_var_base
def _env_var(self, key):
return self.ENV_VAR_BASE + "_" + key.upper()
def get(self, key, default_value=None):
env_var = self._env_var(key)
return os.environ.get(env_var, default_value)
def __getattr__(self, key):
env_var = self._env | _var(key)
try:
return os.environ[env_var]
except KeyError:
raise Exception("Environment variable '%s' doesn't exist" % env_var)
try:
from trading_ig_config import config
logger.info("import config from %s" % CONFIG_FILE_NAME)
except Exception:
logger.warning("can't... |
r4mp/mete_python_cherrypy_jinja2 | mete/controllers/drinks.py | Python | agpl-3.0 | 1,135 | 0.01674 | from controllers.basehandler import BaseHandler
from mo | dels.drink import Drink
import json
import cherrypy
class Drinks(BaseHandler):
#@cherrypy.expose
def index(self):
drinks = Drink.list(cherrypy.request.db)
template = self.templateEnv.get_template('drinks/index.html')
return template.render(drinks=drinks)
#@cherrypy.expose(alias=... | JSON() for drink in Drink.list(cherrypy.request.db) ]
#@cherrypy.expose
def new(self, name = "", price = 0, bottle_size = 0, caffeine = 0, logo_url = ""):
if cherrypy.request.method == 'GET':
template = self.templateEnv.get_template('drinks/new.html')
return template.render(dri... |
mxamin/exflaskr-irpycon-2015 | app/main/forms.py | Python | mit | 361 | 0 | from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
class EntryForm(Form):
title = String | Field('Title', validators=[
DataRequired(),
Length(1, 64)
])
text = TextAr | eaField('Text', validators=[DataRequired()])
submit = SubmitField('Add')
|
apple/swift-lldb | packages/Python/lldbsuite/test/commands/frame/var/TestFrameVar.py | Python | apache-2.0 | 3,699 | 0.001081 | """
Make sure the frame variable -g, -a, and -l flags work.
"""
from __future__ import print_function
import lldb
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.lldbtest import *
class TestFrameVar(TestBase):
mydir = TestBase.compute_mydir(__file__)
# If your test case doesn't stress debu... | ", command_result)
self.assertEqual(result, lldb.eReturnStatusSucce | ssFinishResult, "frame var -a didn't succeed")
output = command_result.GetOutput()
self.assertTrue("argc" not in output, "Locals found argc")
self.assertTrue("argv" not in output, "Locals found argv")
self.assertTrue("test_var" in output, "Locals didn't find test_var")
self.asser... |
vicnet/weboob | modules/ing/web/accounts_list.py | Python | lgpl-3.0 | 19,513 | 0.003334 | # -*- coding: utf-8 -*-
# Copyright(C) 2009-2014 Florent Fourcot, Romain Bignon
#
# This file is part of a weboob module.
#
# This weboob module 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 ... | /' % month)
return super(INGDate, self).filter(txt)
|
class INGCategory(Filter):
catvalue = {u'virt': u"Virement", u'autre': u"Autre",
u'plvt': u'Prélèvement', u'cb_ret': u"Carte retrait",
u'cb_ach': u'Carte achat', u'chq': u'Chèque',
u'frais': u'Frais bancaire', u'sepaplvt': u'Prélèvement'}
def filter(self, txt):
... |
bbreslauer/PySciPlot | src/Pysciplot.py | Python | gpl-3.0 | 13,206 | 0.005755 | # Copyright (C) 2010-2011 Ben Breslauer
#
# 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 later version.
#
# This program is distribu... | self.setCurrentProject("")
self._storedSettings = {} # this is a dict with widgetName: list pairs
# where each list has [setting-name, setting-value] pairs
# setting-value is a dict with (property-name: Property) pairs
# Load ... | le")
self.preferences = Preferences("~/.pysciplotrc")
# Create application-wide models
self._models['appWaves'] = WavesListModel(self.waves().waveNames())
# Signals
self.waves().waveAdded.connect(self.model('appWaves').appendRow)
self.waves().allWavesRemoved.connect(sel... |
xiaohan2012/lst | add_fake_hashtags.py | Python | mit | 355 | 0.002817 | import argparse
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input')
parser.add_argument('-o', '--output')
args = parser.parse_args()
|
df = pd.read_json(args.input)
df['hashtags'] = pd.Series([['aaaa', 'bbbb']] * df.shape[0],
| index=df.index)
df.to_json(args.output, orient='records')
|
Ledoux/ShareYourSystem | Pythonlogy/build/lib/ShareYourSystem/Standards/Itemizers/Parenter/07_ExampleDoc.py | Python | mit | 959 | 0.052138 |
#ImportModules
import ShareYourSystem as SYS
#define and get two children
MyParenter=SYS.ParenterClass(
).array(
[
['-Layers'],
['|First','|Second'],
['-Neurons'],
['|E','|I']
]
).command(
'+-.values+|.values',
'#call:parent',
_AfterWalkRigidBool=True
).command(
'+-.values+|.values',
{
... | },
_AfterWalkRigidBool=True
)
#print
print('MyParenter.NeuronsDict.keys() is ')
SYS._print(MyParenter.NeuronsDict.keys())
#print
print('MyPar | enter.LayersDict.keys() is ')
SYS._print(MyParenter.LayersDict.keys())
|
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_managed_database_queries_operations.py | Python | mit | 12,909 | 0.003796 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ,
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
| "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api... |
lamenezes/django-ecom | ecom/carrinho/urls.py | Python | gpl-3.0 | 854 | 0.001171 | from django.conf.urls import url
from carrinho.views import (CarrinhoDetalhaView, CarrinhoProdutoInsereView,
CompraView, LoginView, LogoutView, ProdutoDetalhaView,
ProdutoListaView)
u | rlpatter | ns = [
url(r'^$',
ProdutoListaView.as_view(),
name='home'),
url(r'^carrinho/$',
CarrinhoDetalhaView.as_view(),
name='carrinho'),
url(r'^comprar/$',
CompraView.as_view(),
name='comprar'),
url(r'^login/$',
LoginView.as_view(),
name='login'),
... |
XTAv2/Enigma2 | lib/python/Plugins/Extensions/ExtrasPanel/QuickMenu.py | Python | gpl-2.0 | 35,097 | 0.028378 |
from enigma import eListboxPythonMultiContent, gFont, eEnv, getBoxType
from boxbranding import getMachineBrand, getMachineName
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.MenuList import MenuList
from Components.MultiContent import... | toMountManager
from Plugins.SystemPlugins.NetworkBrowser.NetworkBrowser import NetworkBrowser
from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
from Plugins.Extensions.ExtrasPanel.RestartNetwork import RestartNetwork
from Plugins.Extensions.ExtrasPanel.MountManager import HddMount
from Plugins... | sPanel.SoftcamPanel import *
from Plugins.Extensions.ExtrasPanel.SoftwarePanel import SoftwarePanel
from Plugins.SystemPlugins.SoftwareManager.Flash_online import FlashOnline
from Plugins.SystemPlugins.SoftwareManager.ImageBackup import ImageBackup
from Plugins.SystemPlugins.SoftwareManager.plugin import UpdatePlugin, ... |
imjonsnooow/vivisect | vtrace/archs/arm.py | Python | apache-2.0 | 339 | 0.00885 | import envi.archs.arm as e_arm
class ArmMixin(e_arm.ArmModule, e_arm.ArmRegisterContext):
def __init__(self):
e_arm.ArmModule.__init__(self)
e_arm.ArmRegisterContext.__init__(self)
def archGetStackTrace(self):
p | c = self.getProgramCounter()
sp = s | elf.getStackCounter()
return [ (pc,sp), ]
|
jamiefolsom/edx-platform | lms/djangoapps/mobile_api/users/serializers.py | Python | agpl-3.0 | 4,109 | 0.001217 | """
Serializer for user API
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.template import defaultfilters
from courseware.access import has_access
from student.models import CourseEnrollment, User
from certificates.models import certificate_status_for_student, Certif... | -list',
kwargs={'course_id': course_id},
request=request
)
course_handouts_url = reverse(
'course-handouts-list',
kwargs={'course_id': course_id},
request=request
)
else:
video_outline... | start_display = course_overview.advertised_start
elif course_overview.start != DEFAULT_START_DATE:
start_type = "timestamp"
start_display = defaultfilters.date(course_overview.start, "DATE_FORMAT")
else:
start_type = "empty"
start_display = Non... |
mitdbg/modeldb | client/verta/verta/_swagger/_public/uac/model/UacUpdateUserResponse.py | Python | mit | 575 | 0.012174 | # THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import Base | Type
class UacUpdateUserResponse(BaseType):
def __init__(self, info=None):
required = {
"info": False,
}
self.info = info
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format(k))
@staticmethod |
def from_json(d):
from .UacUserInfo import UacUserInfo
tmp = d.get('info', None)
if tmp is not None:
d['info'] = UacUserInfo.from_json(tmp)
return UacUpdateUserResponse(**d)
|
redhat-cip/dci-control-server | dci/decorators.py | Python | apache-2.0 | 2,908 | 0.001032 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 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 applicab... | )
flask.g.session.add(log)
flask.g.session.commit()
except Exception as e:
flask.g.session.rollback()
logger.error("cannot save audit log")
logger.error(str(e))
return f(*args, **kwargs)
return d | ecorated
|
twschiller/open-synthesis | openach/urls.py | Python | gpl-3.0 | 4,019 | 0.001493 | """Analysis of Competing Hypotheses Django Application URL Configuration.
See the Django documentation for more information:
* https://docs.djangoproject.com/en/2.1/ref/urls/
* https://docs.djangoproject.com/en/2.1/topics/http/urls/
"""
from django.urls import path
from . import views
# NOTE: Django's API doesn't fo... | ,
name="edit_hypot | hesis",
),
path(
"boards/<int:board_id>/hypotheses/add/",
views.hypotheses.add_hypothesis,
name="add_hypothesis",
),
path(
"boards/<int:board_id>/evidence/<int:evidence_id>/evaluate/",
views.boards.evaluate,
name="evaluate",
),
path(
"board... |
bparzella/secsgem | secsgem/secs/functions/s02f17.py | Python | lgpl-2.1 | 1,406 | 0 | #####################################################################
# s02f17.py
#
# (c) Copyright 2021, Benjamin Parzella. All rights reserved.
#
# 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 Fou... |
#
# This software 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.
###################################################################... | s for stream 02 function 17."""
from secsgem.secs.functions.base import SecsStreamFunction
class SecsS02F17(SecsStreamFunction):
"""
date and time - request.
**Structure**::
>>> import secsgem.secs
>>> secsgem.secs.functions.SecsS02F17
Header only
**Example**::
>>>... |
JohnLunzer/flexx | flexx/webruntime/browser.py | Python | bsd-2-clause | 2,780 | 0.003237 | """ Web runtime based on a common browser
Opens browser via webbrowser module.
"""
import webbrowser
from . import logger
from .common import BaseRuntime
BROWSER_MAP = {'chrome': ['google-chrome', 'chrome',
'chromium-browser', 'chromium'],
'chromium': ['chromium-browser', ... | n_subprocess([exe, url])
self._proc = None # Prevent closing
return
elif type in ('edge', ):
| self._spawn_subprocess(['start', 'microsoft-edge:'+url], shell=True)
self._proc = None # Prevent closing
return
if errors:
logger.warn('Given browser %r not valid/available;\n'
'Falling back to the default browser.' % type)
#... |
CybOXProject/cybox-to-oval | cybox_to_oval.py | Python | bsd-3-clause | 1,436 | 0.014624 | #CybOX -> OVAL Translator
#Generates valid OVAL 5.7 XML output from CybOX v2.1 XML
#Supports Windows files, registry keys, and processes
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox_to_oval_processor as cybox2oval
import sys
#Print the usage... | ame = args[i+1]
elif args[i] == '-v':
verbose_mode = True
processor = cybox2oval.cybox_to_oval_processor(infilename, outfilename, verbose_mode)
#Parse the input CybOX and generate the output OVAL
processor.generate_oval() |
if __name__ == "__main__":
main()
|
openturns/otsvm | python/test/t_example2.py | Python | lgpl-3.0 | 1,095 | 0 | # this example uses a csv file with the datas for the classification
# we retreive the sample from the file sample.csv
path = os.path.abspath(os.path.dirname(__file__))
dataInOut = Sample().ImportFromCSVFile(path + "/sample.csv")
# we create dataIn and dataOut
dataIn = Sample(861, 2)
dataOut = Sample(861, 1)
# we bui... | ction
gamma = [0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100]
# create the Classification Problem
Regression = LibSVMClassification(dataIn, dataOut)
Regression.setKernelType(LibSVM.N | ormalRbf)
Regression.setTradeoffFactor(cp)
Regression.setKernelParameter(gamma)
# compute the classification
Regression.run()
print "#######################"
print "Results with Samples I/O"
print "Accuracy(p.c.)=", Regression.getAccuracy()
|
amnona/heatsequer | ui/plotmetadata.py | Python | bsd-3-clause | 1,925 | 0.148571 | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
... | t>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QListWidget" name= | "lMetaData">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>256</width>
<height>192</height>
</rect>
</property>
</widget>
<widget class="QPushButton" name="bAdd">
<property name="geometry">
<rect>
<x>280</x>
<y>10</y>
<width>115</width>
<he... |
zapcoop/vertex | vertex_api/places/constants.py | Python | agpl-3.0 | 3,853 | 0.002855 | ADDRESS_COMPONENT_TYPES = (
'street_address', # indicates a precise street address.
'route', # indicates a named route (such as "US 101").
'intersection', # indicates a major intersection, usually of two major roads.
'political',
# indicates a political entity.
# Usually, this type indicates ... | tural_feature', # indicates a prominent natural feature.
'airport', # indicates an airport.
'park', # indicates a named park.
'point_of_interest',
# indicates a named point of interest.
# Typically, these "POI"s are prominent local entities that don't easily fit in
# another category, such as... | ndicates the floor of a building address.
'establishment', # typically indicates a place that has not yet been categorized.
'parking', # indicates a parking lot or parking structure.
'post_box', # indicates a specific postal box.
'postal_town',
# indicates a grouping of geographic areas, such as ... |
jakesyl/BitTornado | BitTornado/Application/makemetafile.py | Python | mit | 4,006 | 0.00025 | #pylint: disable=W0102,C0103
import os
import threading
from traceback import print_exc
from BitTornado.Meta.BTTree import BTTree
from BitTornado.Meta.Info import MetaInfo
defaults = [
('announce_list', '',
'a list of announce URLs - explained below'),
('httpseeds', '',
'a list of http seed URL... | subparams['target'] = os.path.join(params['target'],
base + ext)
make_meta_file(fname, u | rl, subparams, flag,
progress=subprog, progress_percent=False)
except ValueError:
print_exc()
|
pnwairfire/bluesky | bluesky/filtermerge/__init__.py | Python | gpl-3.0 | 1,578 | 0.004436 | """bluesky.filtermerge"""
__author__ = "Joel Dubowy"
import abc
import logging
from bluesky.config import Config
class FiresActionBase(object, metaclass=abc.ABCMeta):
"""Base class for merging or filtering fires
"""
def __init__(self, fires_manager, fire_class):
"""Constructor
args:
... | fire, sub_msg):
msg = "Failed to {} fire {} ({}): {}".format(
self.ACTION, fire.id, fire._private_id, sub_msg)
raise self._error_class(msg)
def _fail_or_skip(self, msg):
if self._skip_failures:
logging.warning(msg)
| return
else:
raise self._error_class(msg)
|
kernelci/kernelci-backend | app/models/tests/test_report_model.py | Python | lgpl-2.1 | 3,903 | 0 | # Copyright (C) Linaro Limited 2015,2017
# Author: Milo Casagrande <milo.casagrande@linaro.org>
#
# This program 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... | "kernel": "kernel",
"name": "name", |
"type": "build",
"version": "1.1"
}
report_doc = mreport.ReportDocument.from_json(json_obj)
self.assertIsInstance(report_doc, mbase.BaseDocument)
self.assertIsInstance(report_doc, mreport.ReportDocument)
self.assertEqual("1.1", report_doc.version)
... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/express_route_circuit_authorization.py | Python | mit | 2,504 | 0.001597 | # 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 ... | generated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class ExpressRouteCircuitAuthorization(SubResource):
"""Authorization | in an ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:param authorization_key: The authorization key.
:type authorization_key: str
:param authorization_use_status: AuthorizationUse... |
morphis/home-assistant | homeassistant/components/sensor/cpuspeed.py | Python | apache-2.0 | 2,269 | 0 | """
Support for displaying the current CPU speed.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpusp | eed/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['py-cpuinfo==0.2.6']
_LOGGER = logging.getLogger... | tional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
# pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the CPU speed sensor."""
name = config.get(CONF_NAME)
add_devices([CpuSpeedSensor(name)])
class CpuSpeedSensor(Entity):
"""Representa... |
SDavey149/BFHRCONPython | BFHServer.py | Python | gpl-3.0 | 7,989 | 0.002754 | __author__ = 'Scott Davey'
"""
Base for connecting and querying BFH/BFP4F/BF2 servers using RCON.
Copyright (C) 2013 Scott Davey, www.sd149.co.uk
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, eit... | ns: A list of tuples.
"""
allChat = []
| chat = self.query('bf2cc clientchatbuffer', True)
chat = chat.split("\\r\\r")
chat.pop(-1) #empty element created at end of list, remove it
for each in chat:
chatList = tuple(each.split("\\t"))
allChat.append(chatList)
return allChat
def getServerChatBuff... |
simvisage/oricreate | apps/examples/exX02_opt_crit_node_distance.py | Python | gpl-3.0 | 684 | 0 | if __name__ == '__main__':
from oricreate.api import \
CreasePattern, Cust | omCPFactory, MapToSurface
from oricreate.fu import \
FuNodeDist |
import numpy as np
cp = CreasePattern(X=[[0, 0, 0],
[0.5, 0, 0],
[10.0, 0, 0]],
L=[[0, 1], [1, 2], [2, 0]])
cpf = CustomCPFactory(formed_object=cp)
init = MapToSurface(previous_task=cpf)
oc = FuNodeDist(forming_task=init,
... |
ufjfeng/leetcode-jf-soln | python/260_single_number_iii.py | Python | mit | 1,582 | 0.002528 | """
Given an array of numbers num | s, in which exactly two elements appear only once
and all the other elements appear exactly twice. Find the two elements that
appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is
also correct.
| Your algorithm should run in linear runtime complexity. Could you implement
it using only constant space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating
all test cases.
"""
class Solution(object):
def singleNumber(self, nums):
"""
:t... |
pywikibot/core-migration-example | pywikibot/families/fon_family.py | Python | mit | 455 | 0.002198 | # -*- coding | : utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The official Beta Wiki.
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = 'fon'
self.langs = {
'en': None,
}
def hostname(self, code):
return 'wiki.f... | riptpath(self, code):
return '/mediawiki'
def version(self, code):
return "1.15.1"
|
mxamin/youtube-dl | youtube_dl/extractor/nfb.py | Python | unlicense | 4,486 | 0.000892 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
clean_html,
determine_ext,
int_or_none,
qualities,
urlencode_postdata,
xpath_text,
)
class NFBIE(InfoExtractor):
IE_NAME = 'nfb'
IE_DESC = 'National Film Board of Canada'
_VALID_URL = r... | de in asset:
| streamer = xpath_text(node, 'streamerURI', default=None)
if not streamer:
continue
play_path = xpath_text(node, 'url', default=None)
if not play_path:
continue
f... |
CiscoSystems/nova | nova/tests/test_notifications.py | Python | apache-2.0 | 13,358 | 0.001647 | # Copyright (c) 2012 OpenStack Foundation
# 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 ... | f.flags(notify_api_faults=True)
exception = None
try:
# Get a real exception with a call stack.
raise test.TestingExceptio | n("junk")
except test.TestingException as e:
exception = e
notifications.send_api_fault("http://example.com/foo", 500, exception)
self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))
n = fake_notifier.NOTIFICATIONS[0]
self.assertEqual(n.priority, 'ERROR')
s... |
bdestombe/flopymetascript | flopymetascript/metafunctions.py | Python | mit | 9,791 | 0.001532 | # coding=utf-8
import glob
import hashlib
import io
import os
import zipfile
from pathlib import Path
from tempfile import TemporaryDirectory
import nbconvert
import nbformat
from .model import Model
def run(bytes_in):
myzipfile = zipfile.ZipFile(bytes_in)
with TemporaryDirectory() as temp_dir:
"""... | os.path.join(temp_dir_sane_input, '*' +
path_sane_odj.suffix))[0]
path_sane = path_sane_alt
hash_sane = hashlib.md5(
open(path_sane, 'rb').read()).hexdigest()
if hash_sane != hash_out:
... | ad().splitlines()
text2_split = open(path_sane, 'r').read().splitlines()
for i, (l1,
l2) in enumerate(zip(text1_split, text2_split)):
if l1 == l2:
continue
elif l1[0] == '#' ... |
kapadia/geoblend | setup.py | Python | mit | 2,841 | 0.00176 |
import os
import shutil
from codecs import open as codecs_open
import numpy as np
from setuptools import setup, find_packages
from distutils.core import Distribution, Extension
from distutils.command.build_ext import build_ext
from distutils import errors
from Cython.Build import cythonize
from Cython.Compiler.Errors ... | author=u"Amit Kapadia",
author_email='amit@planet.com',
url='https://github.com/kapadia/geoblend',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
ext_modules=cythonize(extensions),
zip_safe=False,
install_requi... | ,
'scikit-image'
],
extras_require={
'test': ['pytest'],
'development': [
'cython>=0.23.0',
'benchmark'
]
},
entry_points="""
[console_scripts]
geoblend=geoblend.scripts.cli:geoblend
"""
) |
aitoralmeida/eu-elections | analyzer/remote_database.py | Python | apache-2.0 | 9,695 | 0.008252 | __author__ = 'juan'
import json
from termcolor import colored
| import mysql.connector
import time
config = {
'user': 'elec',
'password': 'elec',
'host': 'thor.deusto.es',
'database': 'eu_test2',
}
class database:
def __init__(self):
self.con = mysql.connector.connect(**config)
def insert(self,tweet):
try:
self.con = mysql.con... | f.insert_mention(tweet)
#self.insert_language_group(tweet)
#self.insert_language_candidate(tweet)
#self.insert_hash_country(tweet)
#self.insert_hash_group(tweet)
#self.insert_hash_candidate(tweet)
self.con.commit()
self.con.close()
... |
Heufneutje/txircd | txircd/modules/rfc/cmd_away.py | Python | bsd-3-clause | 2,756 | 0.029753 | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import trimStringToByteLength
from zope.interface import implementer
from typing import Any, Callabl... | nfig(self, config: Dict[str, Any]) -> None:
if "away_length" in config:
if not isinstance(config["away_length"], int) or config | ["away_length"] < 0:
raise ConfigValidationError("away_length", "invalid number")
elif config["away_length"] > 200:
config["away_length"] = 200
self.ircd.logConfigValidationWarning("away_length", "value is too large", 200)
def notifyAway(self, user: "IRCUser", data: Dict[Any, Any]) -> None:
if "targ... |
youngmp/park_and_ermentrout_2016 | specgram_mod.py | Python | bsd-2-clause | 3,335 | 0.002999 | """
This script was found on stack overflow
http://stackoverflow.com/questions/19468923/cutting-of-unused-frequencies-in-specgram-matplotlib
"""
from pylab import *
from matplotlib import *
# modified specgram()
def my_specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanni... | 56, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
cmap=None, xextent=None, pad_to=None, sides='default',
scale_by_freq=None, minfreq = None, maxfreq = None, **kwargs)
Compute a spectrogram of data in *x*. Data are split into
*NFFT... | to each
segment, and the amount of overlap of each segment is
specified with *noverlap*.
%(PSD)s
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the y extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered... |
openstack/ceilometer | ceilometer/tests/unit/publisher/test_gnocchi.py | Python | apache-2.0 | 33,790 | 0 | #
# Copyright 2014 eNovance
#
# 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, ... | 43029547f1a61c1996d1a531a2'),
models.Trait('service', 1, u'compute'),
models.Trait('availability_zone', 1, u'zone1'),
models.Trait('disk_gb', | 2, 0),
models.Trait('instance_type', 1, u'm1.tiny'),
models.Trait('tenant_id', 1, u'7c150a59fe714e6f9263774af9688f0e'),
models.Trait('root_gb', 2, 0),
models.Trait('ephemeral_gb', 2, 0),
models.Trait('instance_type_id', 2, u'2'),
models.Trait('vcp... |
tassolom/twq-app | api/users/migrations/0001_initial.py | Python | mit | 1,356 | 0.002212 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-15 23:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... | options={
'abstract': False,
| },
),
migrations.CreateModel(
name='Employee',
fields=[
('user_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='users.User')),
],
... |
emesene/emesene | emesene/e3/xmpp/SleekXMPP/sleekxmpp/thirdparty/statemachine.py | Python | gpl-3.0 | 11,722 | 0.006995 | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import threading
import time
import logging
log = logging.getLogger(__name__)
class StateMachine(object):
def __init__(self, states=[]):... | If `func` returns a True value, the transition will occur. If `func` returns a non-
True value or if an exception is thrown, the transition will not occur. Any thrown
exception is not caught by the state machine and is the caller's responsibility | to handle.
If `func` completes normally, this method will return the value returned by `func.` If
values for `args` and `kwargs` are provided, they are expanded and passed like so:
`func( *args, **kwargs )`.
'''
return self.transition_any((from_state,), to_state, wait=wait,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.