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 |
|---|---|---|---|---|---|---|---|---|
ctuning/ck-env | soft/env.msys2/customize.py | Python | bsd-3-clause | 1,741 | 0.029868 | #
# Collective Knowledge (individual environment - setup)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
import os
extra_dirs=['C:\\msys64', 'C:\\tools\\msys2', 'D:\\msys64', 'D:\\tools\\msys2']
... | break
return {'return':0, 'version':ver}
##############################################################################
# setup environment
def setup(i):
s=''
cus=i['customize']
env=i['env']
fp=cus.get('full_path | ','')
ep=cus['env_prefix']
if fp=='':
return {'return':1, 'error':'full path required by the soft customization script is empty'}
p1=os.path.dirname(fp)
p2=os.path.dirname(p1)
p3=os.path.dirname(p2)
env[ep]=p3
env[ep+'_BIN']=p1
env[ep+'_BASH']=fp
return {'return':0, 'bat... |
aowen87/PhyloViewer | src/condense.py | Python | gpl-3.0 | 3,122 | 0.012812 | #! /usr/bin/python
'''
@author: Alister Maguire
Given a counts file and a taxa file, condense
repeated genus' and their counts, and output
a file that maps genus names to their counts
for each experiment.
'''
import argparse
def is_number(s):
try:
float(s)
return True
except ValueError:
... | e, "r")
counts_f = open(args.counts_file, "r")
condensed_counts = []
genus_dct = {}
genus_lst = []
count_lst = []
count_dct = | {}
taxa = taxa_f.readlines()
counts = counts_f.readlines()
for c in counts:
count_lst.append(c.split())
#create a dictionary that associates
#experiment IDs with lists for counts
c_size = len(counts)
for i in range(1, c_size):
count_dct[count_lst[i][0]] = []
... |
gungorbudak/sslsa | sslsa.py | Python | mit | 4,211 | 0.00095 | #!C:\Python27
# sslsa.py
# Structural Superimposition of Local Sequence Alignment
# A program which finds out whether a local sequence
# alignment of two protein sequences also implies structural
# similarity of the aligned parts
import os
import sys
import glob
from Bio.PDB import *
from Bio import pairwise2
from Bio.... | mpty string for mapping the atom object | s
pdb_atms_mapped = [[], []]
# i is the index for the two alignments, j is for the first
# atom object list and k is for the other atom object list
i, j, k = 0, 0, 0
while i < len(aln_first[:end]):
# Check if there is no gap in either part of
# the alignment because there will be no atom
# for ones with -
... |
diogo149/Lasagne | lasagne/tests/layers/test_input.py | Python | mit | 1,255 | 0.001594 | import numpy
import pytest
import theano
clas | s TestInputLayer:
@pytest.fixture
def layer(se | lf):
from lasagne.layers.input import InputLayer
return InputLayer((3, 2))
def test_input_var(self, layer):
assert layer.input_var.ndim == 2
def test_get_output_shape(self, layer):
assert layer.get_output_shape() == (3, 2)
def test_get_output_without_arguments(self, layer)... |
4shadoww/usploit | lib/dns/rdtypes/ANY/HINFO.py | Python | mit | 2,266 | 0.000883 | # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and ... | import dns.exception
import dns.immutable
import dns.rdata
import dns.tokenizer
@dns.immutable.immutable
class HINFO(dns.rdata.Rdata):
"""HINFO record"""
# see: RFC 1035
__slots__ = ['cpu', 'os']
def __init__(self, rdclass, rdtype, cpu, os):
super().__init__(rdclass, rdtype)
self.c... | self._as_bytes(cpu, True, 255)
self.os = self._as_bytes(os, True, 255)
def to_text(self, origin=None, relativize=True, **kw):
return '"{}" "{}"'.format(dns.rdata._escapify(self.cpu),
dns.rdata._escapify(self.os))
@classmethod
def from_text(cls, rdclass, r... |
jlorieau/mollib | mollib/core/topology.py | Python | gpl-3.0 | 14,201 | 0.000282 |
# Bonding Topology of heavy atoms. This is a dict of a dict of sets
topology = {'PRO': {'N': {'C-1 | ', 'CA', 'CD'},
'CA': {'N', 'C', 'CB', 'HA'},
'HA': {'CA'},
'CB': {'CA', 'CG', 'HB2', 'HB3'},
'HB2': {'CB'},
'HB3': {' | CB'},
'CG': {'CB', 'CD', 'HG2', 'HG3'},
'HG2': {'CG'},
'HG3': {'CG'},
'CD': {'CG', 'N', 'HD2', 'HD3'},
'HD2': {'CD'},
'HD3': {'CD'},
'C': {'CA', 'O', 'N+1'},
... |
vsserafim/aula_sockets_echo | client_01.py | Python | gpl-2.0 | 1,291 | 0 | # -*- coding: utf-8 -*-
import socket
from string import strip
__author__ = 'Vinícius da Silveira Serafim <vinicius@serafim.eti.br>'
# endereço e porta do servidor para conexão
server_addr = ("127.0.0.1", 9000)
def main():
"""
Função principal.
"""
# (1) Criar socket cliente
client_socket = sock... | resp = client_socke | t.recv(128)
# se o servidor não enviou nada, a conexão foi encerrada
if not len(resp):
break
print "[<] Recebido: '%s' (%s bytes) do servidor %s:%s" %\
(resp, len(resp), server_addr[0], server_addr[1])
# (5) Desconectar
client_socket.close()
print "Conexã... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.1/Lib/test/test_long.py | Python | mit | 8,805 | 0.003748 | from test_support import verify, verbose, TestFailed
from string import join
from random import random, randint
# SHIFT should match the value in longintrepr.h for best testing.
SHIFT = 15
BASE = 2 ** SHIFT
MASK = BASE - 1
# Max number of base BASE digits to use in test cases. Doubling
# this will at least quadruple... | es something
# under -O.
def check(ok, *args):
if not ok:
raise TestFailed, join(map(str, args), " ")
# Get quasi-random long consisting of ndigits digits (in base BASE).
# quasi == the most-significant digit will not be 0, and the number
# is constructed to contain long strings of 0 and 1 bits. These ar... | ore likely than random bits to provoke digit-boundary errors.
# The sign of the number is also random.
def getran(ndigits):
verify(ndigits > 0)
nbits_hi = ndigits * SHIFT
nbits_lo = nbits_hi - SHIFT + 1
answer = 0L
nbits = 0
r = int(random() * (SHIFT * 2)) | 1 # force 1 bits to start
while... |
huyilin/TopicLda | src/onlineuser.py | Python | gpl-3.0 | 1,278 | 0.021127 | import cPickle, string, numpy, getopt, sys, random, time, re, pprint
import sys
import onlineldauser
import citydoc
import os
import subprocess
import MySQLdb
def main():
db=MySQLdb.Connect(host="localhost",
| user="team06",
passwd="aiM7chah,d",
db="randomtrip")
cur=db.cursor()
batchsize = 1
D = 3.3e6
K = 100 # number of topics
documentstoanalyze=1; # number of batches
user_id='2 | '
cur.execute("select tags from UserProfile where id=%s",user_id)
user_tags=cur.fetchone()
user_tags=[user_tags[0]]
print user_tags
vocab = file('./vocaball.txt').readlines()
W = len(vocab)
olda=onlineldauser.OnlineLDA(vocab)
(gamma, bound) = olda.update_lambda(user_tags)
(wordids, w... |
emCOMP/twitter-mysql | bin/simple_import.py | Python | bsd-3-clause | 6,719 | 0.01786 | import MySQLdb
import csv
import cStringIO
import codecs
import pprint
from datetime import datetime
from decimal import *
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getre... | ser.add_argument('-o', | '--output', help="outfile")
parser.add_argument('-f', '--filename', help="input file")
parser.add_argument('-e', '--encoding', default="utf-8", help="json file encoding (default is utf-8)")
parser.add_argument('--db_encoding', default="utf8mb4", help="database encoding")
#parser.add_argument('-b', '--batchsize', d... |
huangsam/chowist | places/migrations/0008_category.py | Python | mit | 852 | 0.001174 | # Generated by Django 3.0.8 on 2020-07-11 03:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("places", "0007_auto_20200711_0104"),
]
operations = [
migrations.CreateModel(
name="Category",
fields=[
... | dels.AutoField(
auto_created=True,
primary_key=True,
seriali | ze=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
("places", models.ManyToManyField(to="places.Restaurant")),
],
options={"verbose_name_plural": "categories", "db_table": "cat... |
omarkhan/opencraft | instance/tests/test_openstack.py | Python | agpl-3.0 | 3,877 | 0.00129 | # -*- coding: utf-8 -*-
#
# OpenCraft -- tools to aid developing and hosting free software projects
# Copyright (C) 2015 OpenCraft <xavier@opencraft.com>
#
# 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 Soft... | call.servers.list(),
call.servers.delete(server_class(name='server-a', pk=1)),
call.servers.delete(server_class(name='server-a', pk=2)),
])
def test_get_server_public_address_none(self):
"""
No public IP when none has been assigned yet
"""
serve... | lic_address(server), None)
@patch('requests.packages.urllib3.util.retry.Retry.sleep')
@patch('http.client.HTTPConnection.getresponse')
@patch('http.client.HTTPConnection.request')
def test_nova_client_connection_error(self, mock_request, mock_getresponse, mock_retry_sleep):
"""
Connecti... |
mathiasertl/django-ca | ca/django_ca/tests/tests_extensions.py | Python | gpl-3.0 | 71,893 | 0.002406 | # This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public Licen | se as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# django-ca 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
#... | see <http://www.gnu.org/licenses/>.
"""Test cases for :py:mod:`django_ca.extensions`."""
import doctest
import os
import sys
import typing
from unittest import TestLoader
from unittest import TestSuite
from cryptography import x509
from cryptography.x509 import TLSFeatureType
from cryptography.x509.oid import Author... |
jbaayen/sympy | sympy/integrals/risch.py | Python | bsd-3-clause | 11,561 | 0.002681 |
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.function import Function
from sympy.core.symbol import Symbol, Wild
from sympy.core.basic import S, C, Atom, sympify
from sympy.core.numbers import Integer, Rational
from sympy.functions import exp, sin , co... | pendent(x)
else:
indep = S.One
if not f.has(x):
return indep * f * x
rewritables = {
(sin, cos, cot) : tan,
(sinh, cosh, coth) : tanh,
}
rewrite = kwargs.pop('rewrite', False)
if rewrite:
for candidates, rule in rew | ritables.iteritems():
f = f.rewrite(candidates, rule)
else:
for candidates in rewritables.iterkeys():
if f.has(*candidates):
break
else:
rewrite = True
terms = components(f, x)
hints = kwargs.get('hints', None)
if hints is not None:
... |
google/personfinder | tests/views/test_admin_global_index.py | Python | apache-2.0 | 6,931 | 0.000289 | # Copyright 2019 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,... | 'captcha_secret_key': 'captcha-secret-key',
})
self.assertEqual(
resp.context.get('ganalytics_config'), {
'analytics_id': 'analytics-id',
'amp_gtm_id': 'amp-gtm-id',
})
self.assertEqual(
resp.context.get('gmaps_c... | p.context.get('gtranslate_config'), {
'translate_api_key': 'translate-api-key',
})
self.assertEqual(
resp.context.get('notification_config'), {
'notification_email': 'notifications@example.com',
'unreviewed_notes_threshold': '12',
... |
thisch/python-falafel | examples/project2/mypackage/modb/bar.py | Python | bsd-2-clause | 246 | 0 | from .. import TestCase
# NOTE: this test is not run by the tester because the name of this file
# does not match the testpattern regex in TestLoader.discover
cl | ass TestBar(TestCase):
def test_print(self):
se | lf.assertTrue(3+4 > 2)
|
socialplanning/SupervisorErrorMiddleware | supervisorerrormiddleware/tests/test.py | Python | gpl-2.0 | 2,244 | 0.008021 | from supervisorerrormiddleware import SupervisorErrorMiddleware
import os
import sys
import paste.fixture
class DummyOutput:
def __init__(self):
self._buffer = []
def write(self, data):
self._buffer.append(data)
def flush(self):
self._buffer = []
def bad_app(environ, start_respon... | nt-type', 'text/html')])
return ["Good Kitty"]
def test_without_supervisor():
old_stdout = sys.stdout
try:
sys.stdout = DummyOutput()
app = bad_app
app = SupervisorErrorMiddleware(app)
app = paste.fixture.TestApp(app)
failed = False
try:
app.... | |
arannasousa/pagseguro_xml | pagseguro_xml/tests/test_classes_consultas/__init__.py | Python | gpl-2.0 | 490 | 0.002049 | # coding=utf-8
# ---------------------------------------------------------------
# Desenvolvedor: | Arannã Sousa Santos
# Mês: 12
# Ano: 2015
# Projeto: pagseguro_xml
# e-mail: asousas@live.com
# ---------------------------------------------------------------
from .test_detalhes_v3 import ClasseTransacaoDetalhesTest
from .test_historico_v2 import ClasseTransacaoHistoric... | t |
bkuczenski/lca-tools | antelope_background/background/flat_background.py | Python | gpl-2.0 | 18,042 | 0.001718 | """
class for storing static results of a tarjan ordering
"""
from scipy.sparse.csc import csc_matrix
from scipy.sparse.csr import csr_matrix
from scipy.sparse.linalg import inv, factorized, spsolve
from scipy.sparse import eye
from scipy.io import savemat, loadmat
import os
from collections import namedtuple
from .... | as TermRef params
:param exterior: iterable of Exterior flows as TermRef params
:param af: sparse, flattened Af
:param ad: sparse, flattened Ad
:param bf: sparse, flattened Bf
:param lci_db: [None] optional (A, B) 2-tuple
:param quiet: [True] does nothing for now
... | in exterior])
self._af = af
self._ad = ad
self._bf = bf
if lci_db is None:
self._A = None
self._B = None
else:
self._A = lci_db[0].tocsr()
self._B = lci_db[1].tocsr()
self._lu = None # store LU decomposition
se... |
runt18/osquery | tools/codegen/gentable.py | Python | bsd-3-clause | 11,592 | 0.001725 | #!/usr/bin/env python
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from... | )))
exit(1)
# Check for reserved column names
for column in self.columns():
if column.name in RESERVED:
print (lightred(("Cannot use column name: %s in ta | ble: %s "
"(the column name is reserved)" % (
column.name, self.table_name))))
exit(1)
path_bits = path.split("/")
for i in range(1, len(path_bits)):
dir_path = ""
for j in range(i):
... |
texastribune/tt_streams | example/manage.py | Python | apache-2.0 | 320 | 0 | #!/usr/bin/env python |
import os
import sys
if __name__ == "__main__":
os.en | viron.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
GreenLunar/Bookie | bookie/lib/readable.py | Python | agpl-3.0 | 6,558 | 0 | """Handle processing and setting web content into Readability/cleaned
"""
import httplib
import logging
import lxml
import socket
import urllib2
from BaseHTTPServer import BaseHTTPRequestHandler as HTTPH
from breadability.readable import Article
from urlparse import urlparse
LOG = logging.getLogger(__name__)
class... | al parsed
'200': 200,
'404': 404,
'403': 403,
'429': 429, # wtf, 429 doesn't exist...
# errors like 9's
'900': 900, # used for unparseable
'901': 901, # url is not parseable/usable
'902': 902, # socket.error during download
'903': 903, # httplib.IncompleteRead error
'9... | r about document is empty
'905': 905, # httplib.BadStatusLine
})
IMAGE_TYPES = DictObj({
'png': 'image/png',
'jpeg': 'image/jpeg',
'jpg': 'image/jpg',
'gif': 'image/gif',
})
class Readable(object):
"""Understand the base concept of making readable"""
is_error = False
content = None
... |
rearmlkp/Smart_Flash | API/migrations/0003_auto_20170201_0842.py | Python | gpl-3.0 | 917 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-01 08:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('API', '0002_auto_20170201_0840'),
]
operations = [
migrations.AddField(
... | ack',
field=models.CharField(default='', max_length=1000),
),
migrations.AddField(
model_name='card',
name='front',
field=models.CharField(default='', max_length=1000),
),
migrations.AddField(
model_name='card',
name... | ddField(
model_name='card',
name='type',
field=models.IntegerField(default=0),
),
]
|
skyoo/jumpserver | apps/terminal/migrations/0018_auto_20191202_1010.py | Python | gpl-2.0 | 2,294 | 0 | # Generated by Django 2.2.7 on 2019-12-02 02:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('terminal', '0017_auto_20191125_0931'),
]
operations = [
migrations.RemoveField(
model_name='session',
name='date_las... | odel_name='session',
name='user_id',
| field=models.CharField(blank=True, db_index=True, default='',
max_length=36),
),
migrations.AlterField(
model_name='session',
name='asset',
field=models.CharField(db_index=True, max_length=128,
... |
gialloporpora/yellowpy | lastfm.py | Python | gpl-2.0 | 4,732 | 0.042054 | # download images from last.fm
# PyQuery is a very powerful module to parse HTML pages, but it is not by default distributed with Python
# if you want install it you need first install lxml module
# Same features of this script works only with pyquery, but the most important ones (download images of cover and arti... | s and album's images from Last.fm.")
group = parser.add_mutually_exclusive_group()
parser.add_argument('artist',
help="Artist name")
parser.add_argument("-a","--album", dest="album", default = None,
help="Album title")
group.add_argument("-d", "--download", action="store_true",
help="Download the detected... | args.album)
print img["url"]
if args.download:
args.file ="%s.%s" %(img["name"], img["url"].split('.')[-1])
args.file=args.file.decode(sys.getfilesystemencoding())
if args.file:
wget(img["url"], args.file)
print "Image as been downloaded successfully as %s" %args.file |
gofed/gofed-ng | testsuite/helpers/utils.py | Python | gpl-3.0 | 1,073 | 0.001864 | #!/bin/python
# gofed-ng - Golang system
# Copyright (C) 2016 Fridolin Pokorny, fpokorny@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at y... | RCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.... | service_path):
basename = os.path.basename(service_path)
return basename[:-len('.py')]
if __name__ == "__main__":
sys.exit(1)
|
FEniCS/dolfin | site-packages/dolfin_utils/meshconvert/meshconvert.py | Python | lgpl-3.0 | 50,178 | 0.004604 | # -*- coding: utf-8 -*-
""" Module for converting various mesh formats."""
# Copyright (C) 2006 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN 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, e... | rted for conversion
supported_gmsh_element_types = [1, 2, 4, 15]
# Open files
ifile = open(ifilename, "r")
# Scan file for cell type
cell_type = None
highest_dim = 0
line = ifile.readline()
while line:
# Remove newline
line = line.rstrip("\n\r")
# Read dimensi... | = ifile.readline()
num_elements = i |
stevearc/dynamo3 | tests/__init__.py | Python | mit | 22,100 | 0.000271 | """ Tests for Dynamo3 """
import sys
import unittest
from decimal import Decimal
from pickle import dumps, loads
from urllib.parse import urlparse
from botocore.exceptions import ClientError
from mock import ANY, MagicMock, patch
from dynamo3 import (
Binary,
Dynamizer,
DynamoDBConnection,
DynamoDBEr... | ssert_called_with(
"scan",
TableName="foobar",
ReturnConsumedCapacity="INDEXES",
ConsistentRead=False,
| )
def test_list_tables_page(self):
"""Call to ListTables should page results"""
hash_key = DynamoKey("id")
for i in range(120):
self.dynamo.create_table("table%d" % i, hash_key=hash_key)
tables = list(self.dynamo.list_tables(110))
self.assertEqual(len(tab... |
bloer/bgexplorer | bgexplorer/modelviewer/evaldata.py | Python | bsd-2-clause | 20,163 | 0.000446 | from itertools import chain
import gzip
import multiprocessing
import time
import numpy as np
from enum import Enum
from uncertainties import unumpy
from io import BytesIO
from flask import abort
import pymongo
try:
import matplotlib
import matplotlib.figure
import matplotlib.pyplot
except ImportError:
... | val = val.to(unit).m
except AttributeError: # not a Quantity...
pass
except units.errors.DimensionalityError as e:
if val != 0:
log.warning(e)
val = getattr(val, 'm', 0)
# convert to string
val = "{:.3g}".format... | :
unit = self.simsdbview.spectra_units.get(specname, None)
if unit is not None:
try:
spec.hist.ito(unit)
except AttributeError: # not a quantity
pass
return spec
def _evalmatch(self, match, dovals=True, dogroups=True, dospectra=Fals... |
liwanggui/bssh | bssh/network.py | Python | lgpl-2.1 | 1,271 | 0 | # -*- coding: utf-8 -*-
import socket
from paramiko import SSHClient, AutoAddPolicy, AuthenticationException
from bssh.utils import env
from bssh.auth import get_pkey
from bssh.logger import logger
def connect(
hostname=None,
port=22,
username=None,
password=None,
pkey=None,... | timeout=timeout)
logger.login.debug('%s connect successfully.' % hostname)
return client
except AuthenticationException:
logger.login.error('%s Validation faile | d.' % hostname)
except socket.error:
logger.login.error('%s Network Error' % hostname)
except Exception as e:
logger.login.error('%s %s' % (hostname, str(e)))
|
ulif/pulp | server/pulp/server/managers/consumer/history.py | Python | gpl-2.0 | 7,603 | 0.002104 | """
Contains manager class and exceptions for operations for recording and retrieving
consumer history events.
"""
import datetime
import isodate
import pymongo
from pulp.common import dateutils
from pulp.server import config
from pulp.server.db.model.consumer import Consumer, ConsumerHistoryEvent
from pulp.server.ex... | date_range = {}
if start_date:
date_range['$gte'] = start_date
if end_date:
date_range['$lte'] = end_date
if len(date_range) > 0:
search_params['timestamp'] = date_range
# Determine the correct mongo cursor to retrieve
if len(search_param... | by most recent entry first
cursor.sort('timestamp', direction=SORT_DIRECTION[sort])
# If a limit was specified, add it to the cursor
if limit:
cursor.limit(limit)
# Finally convert to a list before returning
return list(cursor)
def event_types(self):
re... |
wrigri/libcloud | libcloud/common/openstack_identity.py | Python | apache-2.0 | 48,080 | 0.000021 | # 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 ... | e token is still valid.
# The time is subtracted to account for the HTTP request latency and prevent
# user from | getting "InvalidCredsError" if token is about to expire.
AUTH_TOKEN_EXPIRES_GRACE_SECONDS = 5
__all__ = [
'OpenStackIdentityVersion',
'OpenStackIdentityDomain',
'OpenStackIdentityProject',
'OpenStackIdentityUser',
'OpenStackIdentityRole',
'OpenStackServiceCatalog',
'OpenStackServiceCatal... |
leighpauls/k2cro4 | third_party/python_26/Lib/site-packages/win32/lib/win32traceutil.py | Python | bsd-3-clause | 1,423 | 0.021082 | # This is a helper for the win32trace module
# If imported from a normal Python program, it sets up sys.stdout and sys.stderr
# so output goes to the collector.
# If run from the command line, it creates a collector loop.
# Eg:
# C:>start win32traceutil.py (or python.exe win32traceutil.py)
# will start a process wit... | l appear in the first collector process.
# Note - the client or the collector can be started first.
# There is a 64k buffer. If this gets full, it is reset, and new
# output appended from the start.
import win32trace
def RunAsCollector():
import sys
try:
import win32api
win32api.SetConsoleTitle("Python Trace ... | e.blockingread()
sys.stdout.write(win32trace.blockingread())
def SetupForPrint():
win32trace.InitWrite()
try: # Under certain servers, sys.stdout may be invalid.
print "Redirecting output to win32trace remote collector"
except:
pass
win32trace.setprint() # this works in an rexec environment.
if __name__=='... |
RobertoPrevato/flask-three-template | dalmongo/__init__.py | Python | mit | 267 | 0.003745 | from pymong | o import MongoClient
from dalmongo import configuration
# get the instance of MongoDB client
client = MongoClient(configuration.MONGODB_HOST, configuration.MONGODB_PORT)
| # get the main application database
db = getattr(client, configuration.MONGODB_NAME) |
MichaelCurrin/twitterverse | app/utils/insert/lookup_and_store_tweets.py | Python | mit | 1,724 | 0.00174 | #!/usr/bin/env python
"""
Lookup and Store Tweets utility.
Lookup tweets on Twitter by the GUID and then stores the profile and tweet
data in the local db.
TODO: Use the system category and campaign as set in app.conf file.
"""
import argparse
import os
imp | ort sys
# A | llow imports to be done when executing this file directly.
sys.path.insert(
0,
os.path.abspath(
os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)
),
)
from lib import tweets
from lib.twitter_api import authentication
def main():
"""
Command-line interface for Lookup a... |
shortbloke/home_assistant_config | custom_components/nodered/switch.py | Python | mit | 7,962 | 0.001005 | """Sensor platform for nodered."""
import json
import logging
import voluptuous as vol
from homeassistant.components.websocket_api import event_message
from homeassistant.const import (
CONF_ENTITY_ID,
CONF_ICON,
CONF_ID,
CONF_STATE,
CONF_TYPE,
EVENT_STATE_CHANGED,
)
from homeassistant.core im... | self._unsubscribe_device_trigger = None
@callback
async def handle_discovery_update(self, msg, connection):
"""Update entity config."""
if CONF_REMOVE not in msg and self._trigger_config != msg[CONF_DEVICE_TRIGGER]:
self.remove_device_trigger()
| self._trigger_config = msg[CONF_DEVICE_TRIGGER]
await self.add_device_trigger()
super().handle_discovery_update(msg, connection)
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
await super().async_added_to_hass()
await self.add_dev... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSpearpointtranslationsHomeBlog.py | Python | bsd-3-clause | 692 | 0.027457 | def extractSpearpointtranslationsHomeBlog(item):
'''
Parser for 'spearpointtranslations.home.blog'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Record of the Missing Sect Master', 'Reco... | aster', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname | in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
NodeTrie/NodeTrie_Py | setup.py | Python | lgpl-2.1 | 2,127 | 0.004701 | """Setup script for NodeTrie"""
from setuptools import setup, find_packages, Extension
import versioneer
try:
from Cython.Build import cythonize
except ImportError:
USING_CYTHON = False
else:
USING_CYTHON = True
ext = 'pyx' if USING_CYTHON else 'c'
extensions = [Extension("nodetrie.nodetrie",
... | formation Analysis',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
| 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)',
],
ext_modules=extensions,
)
|
Orav/kbengine | kbe/src/lib/python/Lib/test/test_importlib/abc.py | Python | lgpl-3.0 | 2,382 | 0 | import abc
import unittest
class FinderTests(metaclass=abc.ABCMeta):
"""Basic tests for a finder to pass."""
@abc.abstractmethod
def test_module(self):
# Test importing a top-level module.
pass
@abc.abstractmethod
def test_package(self):
# Test importing a... | es.
pass
@abc.abstractmethod
def test_failure(self):
# Test trying to find a module that cannot be handled.
pass
class LoaderTests(metaclass=abc.ABCMeta):
@abc.abstractmethod
def test_module(self):
"""A module should load with | out issue.
After the loader returns the module should be in sys.modules.
Attributes to verify:
* __file__
* __loader__
* __name__
* No __path__
"""
pass
@abc.abstractmethod
def test_package(self):
"""Loa... |
proyan/sot-torque-control | unitTesting/unit_test_inverse_dynamics_balance_controller.py | Python | gpl-3.0 | 6,246 | 0.018092 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 31 16:04:18 2017
@author: adelpret
"""
import pinocchio as se3
import numpy as np
from pinocchio import RobotWrapper
from conversion_utils import config_sot_to_urdf, joints_sot_to_urdf, velocity_sot_to_urdf
from dynamic_graph.sot.torque_control.inverse_dynamics_balance_c... | 100
dt = 0.001;
NJ = initRobotData.nbJoints
# robot configuration
q_sot = np.array([-0.0027421149619457344, -0.0013842807952574399, 0.6421082804660067,
-0.0005693871512031474, -0.0013094048521806974, 0.0028568508070167,
-0.0006369040657361668, 0.002710094953239396, -0.482419... | 36, 0.9224570746372157, -0.43872624301275104, -0.0021586727954009096,
-0.0023395862060549863, 0.0031045906573987617, -0.48278188636903313, 0.9218508861779927, -0.4380058166724791, -0.0025558837738616047,
-0.012985322450541008, 0.04430420221275542, 0.37027327677517635, 1.479506416... |
michaelBenin/sqlalchemy | test/orm/inheritance/test_relationship.py | Python | mit | 53,676 | 0.007564 | from sqlalchemy.orm import create_session, relationship, mapper, \
contains_eager, joinedload, subqueryload, subqueryload_all,\
Session, aliased, with_polymorphic
from sqlalchemy import Integer, String, ForeignKey
from sqlalchemy.engine import default
from sqlalchemy.testing import AssertsCompiledSQL, fixture... | ', reports_to=p1)
sess = create_session()
sess.add(p1)
sess.add(e1)
sess.flush()
sess.expunge_all()
eq_(sess.query(Engineer)
.filter(Engineer.reports_to.has(Person.name == 'dogbert'))
.first(),
Engineer(name='dilbert'))
def... | = Engineer(name='wally', primary_language='c++', reports_to=e1)
sess = create_session()
sess.add_all([e1, e2])
sess.flush()
eq_(sess.query(Engineer)
.filter(Engineer.reports_to
.of_type(Engineer)
.has(Engineer.name == 'dilbert'))
... |
danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Tools/Scripts/webkitpy/tool/commands/queues_unittest.py | Python | gpl-3.0 | 22,259 | 0.002965 | # Copyright (C) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | ests.layout_package import test_failures
from webkitp | y.thirdparty.mock import Mock
from webkitpy.tool.commands.commandtest import CommandsTest
from webkitpy.tool.commands.queues import *
from webkitpy.tool.commands.queuestest import QueuesTest
from webkitpy.tool.commands.stepsequence import StepSequence
from webkitpy.tool.mocktool import MockTool, MockSCM, MockStatusServ... |
adrienpacifico/openfisca-core | openfisca_core/tests/test_cycles.py | Python | agpl-3.0 | 5,495 | 0.008735 | # -*- coding: utf-8 -*-
from nose.tools import raises
from openfisca_core import periods
from openfisca_core.columns import IntCol
from openfisca_core.formulas import CycleError, SimpleFormulaColumn
from openfisca_core.tests import dummy_country
from openfisca_core.tests.dummy_country import Individus, reference_for... | :
column = IntCol
entity_class = Individus
def function(self, simulation, period):
return period, simulation.calculate('variable3', period)
# 5 -f-> 6 with a | period offset, with cycle flagged but not allowed
# <---
@reference_formula
class variable5(SimpleFormulaColumn):
column = IntCol
entity_class = Individus
def function(self, simulation, period):
variable6 = simulation.calculate('variable6', period.last_year, max_nb_cycles = 0)
return peri... |
mozilla-services/autopush | autopush/tests/conftest.py | Python | mpl-2.0 | 235 | 0 | from autopush.tests import | setUp, tearDown
def pytest_configure(config):
"""Called before testing begins"""
setUp()
def pytest_unconfigure(config):
"""Called after all tests run and warnings displayed"""
tearDown()
| |
bobcyw/django | django/core/urlresolvers.py | Python | bsd-3-clause | 26,463 | 0.001474 | """
This module converts requested URLs to callback view functions.
RegexURLResolver is the main class here. Its resolve() method takes a URL (as
a string) and returns a ResolverMatch object which provides access to all
attributes of the resolved URL match.
"""
from __future__ import unicode_literals
import functools... | module %s does not exist." %
(lookup_view, mod_name))
else:
raise
else:
try:
view_func = getattr(mod, func_name)
except AttributeError:
if can_fail:
return lookup_vi | ew
else:
raise ViewDoesNotExist(
"Could not import '%s'. View does not exist in module %s." %
(lookup_view, mod_name))
else:
if not callable(view_func):
# For backwards compatibility this is raised regardless of can_... |
zynga/jasy | jasy/js/tokenize/Lang.py | Python | mit | 458 | 0 | #
# Jasy - Web | Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#
"""JavaScript 1.7 keywords"""
keywords = set([
"break",
"case", "catch", "const", "continue",
"debugger", "default", "delete", "do",
"else",
"false", "finally", "for", "function | ",
"if", "in", "instanceof",
"let",
"new", "null",
"return",
"switch",
"this", "throw", "true", "try", "typeof",
"var", "void",
"yield",
"while", "with"
])
|
Gateswong/GatesMusicPet | music_pet/utils.py | Python | mit | 4,849 | 0.000825 | # -*- coding: utf-8 -*-
import os
from codecs import encode, decode
import re
LINUX_ROOT = u"/"
def trim_quote(text):
if len(text) > 2 and text[0] == '"' and text[-1] == '"':
text = text[1:-1]
return text
def to_unicode(text, encoding="utf8"):
if type(text) == unicode:
return text
... | se ValueError("Invalid pattern! (lack of `>`)")
return buffer
def cli_escape(text):
for ch in u'''`''':
text = text.replace(ch, u'''\\%s''' % ch)
return text
def parent_folder(path):
parts = path.split(u"/")
if path == LINUX_ROOT:
raise ValueError(u"Can't get parent fol | der from linux dir /")
if parts[-1] == u"":
del parts[-1]
if parts[-1] == u".":
parts[-1] = u".."
elif parts[-1] == u"..":
parts.append(u"..")
elif len(parts) == 1:
return u"./"
else:
del parts[-1]
parts.append(u"")
return u"/".join(parts)
def ens... |
inkenbrandt/Earth_Tides | Micrograv/util/tilt_sens.py | Python | gpl-2.0 | 593 | 0.006745 | #!/usr/bin/ | python
# compute new sensitivity from formulae in manual
import math
print "Tilt Sensitivity Calculator"
print "X1 refers to the tilt measurement, in arc sec"
print "R0/R1 refer to the gravimeter readings, in mGal"
print "Get the current tilt sensitivity from data files or the Setup menu"
oldSens = float(raw_input("Cu... | raw_input("R1 [mGal] : "))
x1 = float(raw_input("X1 [arc sec]: "))
K = math.sqrt( 1 + (87000 * (r0-r1)/(x1*x1)) )
newSens = K * oldSens
print "New tilt Sensitivity: %f"%newSens
|
jacobajit/ion | intranet/apps/eighth/views/admin/blocks.py | Python | gpl-2.0 | 5,960 | 0.002349 | # -*- coding: utf-8 -*-
import logging
import pickle
import re
from cacheops import invalidate_model
from django import http
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect, render
from ..attendance import ge... | ters.append({"name": blk.block_letter, " | exists": True})
context = {"admin_page_title": "Add or Remove Blocks{}".format(title_suffix),
"date": date,
"letters": letters,
"show_letters": show_letters,
"add_block_form": QuickBlockForm}
return render(request, "eighth/admin/add_block.html", cont... |
luizcieslak/AlGDock | AlGDock/IO.py | Python | mit | 14,740 | 0.021574 | import os
import numpy as np
import MMTK
class Grid:
"""
Class to read and write alchemical grids.
Data is a dictionary with
spacing - the grid spacing, in Angstroms.
counts - the number of points in each dimension.
vals - the values.
All are numpy arrays.
"""
def __init__(self):
pass
def r... | ultiplier affects the origin and spacing.
"""
if mul | tiplier is not None:
data_n = {'origin':multiplier*data['origin'],
'counts':data['counts'],
'spacing':multiplier*data['spacing'],
'vals':data['vals']}
else:
data_n = data
if FN.endswith('.nc'):
self._write_nc(FN, data_n)
elif FN.endswith('.dx... |
LuisSuall/Sleight_of_hand | Finger_run/utils/gesture.py | Python | gpl-2.0 | 2,182 | 0.024748 | import extendedHand
from extendedHand import *
import math
from math import *
'''
Function that calculates the @percent % of @whole
'''
def percentage(whole, percent):
return (whole * percent) / 100.0
'''
Function that detects the run gesture.
@hand: the hand that we're analysing.
@tolerance: the percentage of toler... | ps position of the two fingers.
thumb_tip_pos = thumb.bone(3).next_joint
index_tip_pos = index.bone(3).next_joint
#We calculate the distance between the tips.
distanceBtwTips = sqrt(pow(thumb_tip_pos[0]-index_tip_pos[0],2) + pow(thumb_tip_pos[1]-index_tip_pos[1],2) + pow(thumb_tip_pos[2]-index_tip_pos[2],2))
#We... | stanceBtwTips < (30 + percentage(30, tolerance)) and palmOrientation(hand) == 'down':
return True
else:
return False
|
minesh1291/Learning-Python | solutions/parse-xml.py | Python | apache-2.0 | 508 | 0.033465 | # Import Functions
i | mport urllib2
import xml.etree.ElementTree as ET
# Get online XML file
url="https://cghub.ucsc.edu/cghub/metadata/analysisDetail/a8f16339-4802-440c-81b6-d7a6635e604b"
request=urllib2.Request(url, headers={"Accept" : "application/xml"})
u=urllib2.urlopen(request)
tree=ET.parse(u)
root=tree.getroot()
dict={}
for i in... | : v.upper()):
print key+":"+dict[key]
|
tkelman/utf8rewind | tools/gyp/pylib/gyp/mac_tool.py | Python | mit | 26,881 | 0.007366 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions to perform Xcode-style build steps.
These functions are executed via gyp-mac-tool when using the Makefile generator.
""... | ateFromXMLData(): Old-style plist parser: missing
# semicolon in dictionary.
# on invalid files. Do the same kind of validation.
import CoreFoundation
s = open(source, 'rb').read() |
d = CoreFoundation.CFDataCreate(None, s, len(s))
_, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
if error:
return
fp = open(dest, 'wb')
fp.write(s.decode(input_code).encode('UTF-16'))
fp.close()
def _DetectInputEncoding(self, file_name):
"""Reads the fi... |
WmHHooper/aima-python | submissions/Thompson/myBayes.py | Python | mit | 907 | 0.003308 | ## Burglary example [Figure 14.2]
from probability import BayesNet
T, F = True, False
gym = BayesNet([
#WorkOuts
('LegDay', '', .33),
('ArmsDay', '', 0.33),
('Cardio', '', 0.33),
('Tired', 'LegDay ArmDay', 'Cardio',
{(T, T, T): 0.1,
(T, T, F): 0 | .1,
(T, F, T): 0.7,
(T, F, F): 0.8,
(F, T, T): 0.7,
(F, T, F): 0.9,
(F, F, T): 0.9,
(F, F, F): 0.5}),
('Quit', 'Tired', {T: 0.70, F: 0.01}),
('Push', 'Tired', {T: 0.90, F: 0.10})
])
gym.label = 'Gym Day'
examples = {
gym: [
{'variable': 'Legday',
'eviden... | {'variable': 'Armday',
'evidence': {'Quit': T, 'Push': T}
},
{'variable': 'Cardio',
'evidence': {'Quit': F, 'Push': T}
}
]
}
# |
LordAmit/epub-highlighter | epub_highlighter.py | Python | mit | 7,285 | 0.000686 | '''
Oh, an attractive module description here.
'''
import os
import shutil
import zipfile
from gi.repository import Gtk
from xml.dom import minidom
from xml.etree import ElementTree as ET
import re
import distutils.archive_util
EPUB_PATH = "/home/amit/git/epub-highlighter/epub/test.epub"
# print(os.path.spli(EPUB_PATH... | nings=None):
global current_progress_in_percent
xml_file_count = len(xmls_with_path)
files_processed = 0
for xml in xmls_with_path:
# content = open(xml).read()
# p | rint("Processing: " + xml)
xml_file_contents = read_contents(xml)
# print(xml_file_contents)
for i in range(0, len(words)):
word = words[i]
# print(word)
if meanings:
meaning = meanings[i]
xml_file_contents = highlight_content(
... |
outworldrunner/nightbay | movies/views.py | Python | gpl-3.0 | 1,200 | 0.004167 | from django.shortcuts import render, get_object_or_404, redirect
from .models import Movie, Trailer
from favorites.models import Favourite
def recent_movies(request):
movie_list = Movie.objects.all().order_by('-id')
# favs = Favourite.objects.all()
# for fav in favs:
# if fav.user == request.user... | user.username)
fav.save | ()
fav.favourites.add(movie)
return redirect("activity:detail", id=id) |
igorcoding/asynctnt-queue | tests/test_queue.py | Python | apache-2.0 | 925 | 0 | from asynctnt_queue import Queue, Tube
from tests import BaseTarantoolTestCase
class QueueTestCase(BaseTarantoolTestCase):
async def test__queue_create(self):
q = Queue(self.conn)
self.assertEqual(q.conn, self.conn, 'conn valid')
def test__queue_get_tube(self):
q = Queue(self.conn)
| tube = q.tube('test_tube')
self.assertEqual(tube.name, 'test_tube', 'name valid')
self.assertIsInstance(tube, Tube, 'tube valid type')
self.assertEqual(tube.conn, self.conn, 'conn valid')
def | test__queue_get_tube_multiple(self):
q = Queue(self.conn)
tube1 = q.tube('test_tube')
tube2 = q.tube('test_tube')
self.assertIs(tube1, tube2, 'the same object')
async def test__queue_statistics(self):
q = Queue(self.conn)
res = await q.statistics()
self.ass... |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/docutils/parsers/rst/languages/zh_tw.py | Python | gpl-2.0 | 5,172 | 0.001354 | # -*- coding: utf-8 -*-
# $Id: zh_tw.py 7119 2011-09-02 13:00:23Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two f... | on required)': 'acronym',
u'code (translation required)': 'code',
'index (translation required)': 'index',
'i (translation required)': 'index',
'subscript (translation required)': 'subscript',
'sub (translation required)': 'subscript',
'superscript (translation required)': 'superscript',
'su... | n required)': 'superscript',
'title-reference (translation required)': 'title-reference',
'title (translation required)': 'title-reference',
't (translation required)': 'title-reference',
'pep-reference (translation required)': 'pep-reference',
'pep (translation required)': 'pep-reference',
'rfc... |
hryamzik/ansible | lib/ansible/modules/network/aci/aci_tenant_span_dst_group.py | Python | gpl-3.0 | 6,414 | 0.001559 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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',
'status': ['preview'],
... | pec()
argument_spec.update(
dst_group=dict(type='str', required=False, aliases=['name']), # Not required for querying all objects
tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects
description=dict(type='str' | , aliases=['descr']),
state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['dst_group', 'tenant']],
['state',... |
demonchild2112/travis-test | grr/server/grr_response_server/server_stubs.py | Python | apache-2.0 | 12,170 | 0.012572 | #!/usr/bin/env python
"""Stubs of client actions.
Client actions shouldn't be used on the server, stubs should be used instead.
This way we prevent loading effectively the whole client code into ours
server parts.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode... | name of the client."""
out_rdfvalues = [rdf_protod | ict.DataBlob]
class GetPlatformInfo(ClientActionStub):
"""Retrieves platform information."""
out_rdfvalues = [rdf_client.Uname]
class Kill(ClientActionStub):
"""A client action for terminating (ClientActionStub) the client."""
out_rdfvalues = [rdf_flows.GrrMessage]
class Hang(ClientActionStub):
"""A c... |
akretion/laposte_api | laposte_api/data/colissimo_9V_nhas22.py | Python | agpl-3.0 | 2,753 | 0.009081 | # -*- coding: utf-8 -*-
delivery={'weight': '10.0', 'pec_bar': u'9V169001>59647441000000023', 'suivi_bar': u'9V0>50000000024', 'cab_prise_en_charge': u'9V1 69001 964744 1000 000023', 'date': '12/05/2014', 'cab_suivi': u'9V 00000 00002 4', 'ref_client': u'OUT/00007', 'Instructions': ''}
sender={'city': u'city', 'accou... | PCH:^FS
^ | FO0,1136^XGE:POSTE,1,1^FS
^FO720,1130^XGE:CAMERA,1,1^FS
^XZ
"""
|
SonienTaegi/CELLAR | CELLAR/settings.py | Python | gpl-2.0 | 2,762 | 0.000724 | """
Django settings for CELLAR project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths i... | '
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
... | },
},
]
WSGI_APPLICATION = 'CELLAR.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'CELLAR.sqlite3'),
}
}
# Internationalization
# http... |
mvo5/python-apt | tests/test_hashes.py | Python | gpl-2.0 | 9,619 | 0 | #!/usr/bin/python
#
# Copyright (C) 2009 Julian Andres Klode <jak@debian.org>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
"""Unit tests for verifying the correctness of hashsums in a... | .simplefilter("always")
self.assertEqu | al(self.hashes.md5, self.fhashes.md5)
self.assertEqual(self.hashes.sha1, self.fhashes.sha1)
self.assertEqual(self.hashes.sha256, self.fhashes.sha256)
self.assertEqual(len(caught_warnings), 6)
self.assertTrue(issubclass(caught_warnings[0].category,
... |
pyconjp/pyconjp-website | pycon/pycon_api/migrations/0001_initial.py | Python | bsd-3-clause | 12,615 | 0.007372 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'APIAuth'
db.create_table(u'pycon_api_apiauth', (
(u'id', self.gf('django.db.mode... | u'pycon_api_irclogline', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('timestamp', self.gf('django.db.models.fields.DateTimeField')()),
('proposal', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['proposals.ProposalBase'])),
('... | db.send_create_signal(u'pycon_api', ['IRCLogLine'])
def backwards(self, orm):
# Deleting model 'APIAuth'
db.delete_table(u'pycon_api_apiauth')
# Deleting model 'ProposalData'
db.delete_table(u'pycon_api_proposaldata')
# Deleting model 'IRCLogLine'
db.delete_tab... |
rtancman/filmes | movies/core/migrations/0003_auto_20150914_2157.py | Python | mit | 408 | 0 | # -*- coding: utf-8 -*-
from __future__ import | unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20150914_2147'),
]
operations = [
migrations.AlterField(
model_name='movie',
name='slug',
field=models.SlugField(null... | alse),
),
]
|
mjamesruggiero/tripp | tests/test_logistic_regression.py | Python | bsd-3-clause | 6,511 | 0.000154 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from .context import tripp
from tripp import logistic_regression
from tripp import munge
from tripp import gradient
from tripp import ml
from tripp import algebra
import random
import logging
logging.basicConfig(level=logging.ERROR, format="%(lineno)d\t%(... | true_negatives += 1
message = "true_pos={0}; false_neg={1}, false_pos={2}; true_neg={3}"
logging.debug(message.format(true_positives,
false_negatives,
false_positives,
true_negatives))
... |
self.assertEqual(0.93, round(precision, 2))
self.assertEqual(0.82, round(recall, 2))
|
LeoTestard/qt-ubuntu-components | tests/autopilot/tavastia/tests/textfield/test_textfield.py | Python | lgpl-3.0 | 923 | 0.005417 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# Copyright 2012 Canonical
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
"""Tests for the TextInput Qml... | autopilot.matchers import Eventually
from textwrap import dedent
from testtools.matchers import Is, Not, Equals
from testtools import skip
import os
fro | m tavastia.tests import TavastiaTestCase
class TextFieldTests(TavastiaTestCase):
"""Tests for TextField component."""
test_qml_file = "%s/%s.qml" % (os.path.dirname(os.path.realpath(__file__)),"TextFieldTests")
def test_can_select_textfield(self):
"""Must be able to select the Qml TextField compo... |
aequitas/home-assistant | homeassistant/components/deconz/__init__.py | Python | apache-2.0 | 6,477 | 0 | """Support for deCONZ devices."""
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_API_KEY, CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP)
from homeassistant.helpers import config_validation as cv
# Loading the config flow file will register the flow
from .... | data[SERVICE_DATA]
gateway = get_ma | ster_gateway(hass)
if CONF_BRIDGEID in call.data:
gateway = hass.data[DOMAIN][call.data[CONF_BRIDGEID]]
if entity_id:
try:
field = gateway.deconz_ids[entity_id] + field
except KeyError:
_LOGGER.error('Could not find the entity %s', ent... |
SasView/sasmodels | sasmodels/core.py | Python | bsd-3-clause | 21,256 | 0.001553 | """
Core model handling routines.
"""
from __future__ import print_function
__all__ = [
"list_models", "load_model", "load_model_info",
"build_model", "precompile_dlls", "reparameterize",
]
import os
from os.path import basename, join as joinpath
from glob import glob
import re
import copy
import numpy a... | ate value, or it can be a parameter from
the base model that will be replace by the expression. The expression
*expr* can be any C99 expression, including C-style if-expressions
*condition ? value1 : value2*. Expressions can use any new or existing
parameter that is not being replaced including interm... | del or included in *source* (see below).
*filename* is the filename for the replacement model. This is usually
*__file__*, giving the path to the model file, but it could also be a
nominal filename for translations defined on-the-fly.
*title* is the mode |
sigmunau/nav | python/nav/auditlog/utils.py | Python | gpl-2.0 | 794 | 0.001259 | from __future__ import unicode_literals
from django.utils.encoding import force_text
from django.db.models import Q
from . import find_modelname
from models import LogEntry
LATEST_N_AUDITLOG_ENTRIES = 15
def get_auditlog_entries(iterable, limit=LATEST_N_AUDITLOG_ENTRIES):
modelname = find_modelname(list(iterab... | ) for i in iterable]
object_query = Q(object_pk__in=pks, object_model=modelname)
target_query = Q(target_pk__in=pks, object_model=modelname)
actor_query = Q(actor_pk__in=pks, object_model=modelname)
filter_query = object_query | target_query | actor_query
entries = (LogEntry.objects
.... | .distinct()
.order_by('-timestamp')[:limit]
)
return entries
|
pbanaszkiewicz/amy | amy/autoemails/templatetags/type_extras.py | Python | mit | 555 | 0 | from collections.abc import Iterable
from django import template
from django.db.models import Model
register = template.Library()
@register.filter
def get_type(value):
# inspired by: https://stackoverflow.com/a/12028864
return type(value)
@register.filter
def is_model( | value):
return isinstance(value, Model)
@register.filter
def is_iterable(value):
return isinstance(value, Iterable)
@register.filter
def is_str(value):
return isinstance(value, str)
@register.filter
def is_bool(value):
return isinstance(value, bo | ol)
|
leahrnh/ticktock_text_api | Backend.py | Python | gpl-2.0 | 4,516 | 0.010407 | #!/usr/bin/env python
###########################################################################
## ##
## Language Technologies Institute ##
## Carnegie Mellon University ... | nearly the entirety of the code, ret | aining structure of ##
## methods previously used for debugging ##
## and resource structure/initialization ##
## ##
###############################################################... |
aperigault/ansible | lib/ansible/modules/cloud/hcloud/hcloud_server.py | Python | gpl-3.0 | 14,437 | 0.001939 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# 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 = {
"met... | }
def _get_server(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_server = self.client.servers.get_by_id(
self.module.params.get("id")
| )
else:
self.hcloud_server = self.client.servers.get_by_name(
self.module.params.get("name")
)
except APIException as e:
self.module.fail_json(msg=e.message)
def _create_server(self):
self.module.fail_on_missing_... |
RasaHQ/rasa_nlu | tests/engine/training/test_hooks.py | Python | apache-2.0 | 3,903 | 0.001025 | from rasa.engine.caching import TrainingCache
from rasa.engine.graph import ExecutionContext, GraphNode, GraphSchema, SchemaNode
from rasa.engine.storage.storage import ModelStorage
from rasa.engine.training import fingerprinting
from rasa.engine.training.components import PrecomputedValueProvider
from rasa.engine.trai... | ,
model_storage=default_model_storage,
resource=None,
execution_context=execution_context,
hooks=[
TrainingHook(
cache=temp_cache,
model_storage=default_model_storage,
| pruned_schema=execution_context.graph_schema,
)
],
)
node(("input_node", "Joe"))
# This is the same key that the hook will generate
fingerprint_key = fingerprinting.calculate_fingerprint_key(
graph_component_class=CacheableComponent,
config={"prefix": "Hell... |
listyque/TACTIC-Handler | thlib/ui_classes/ui_maya_dock.py | Python | epl-1.0 | 6,812 | 0.001468 | # module General Ui
# file ui_maya_dock.py
# Main Dock Window interface
from thlib.side.Qt import QtWidgets as QtGui
#from thlib.side.Qt import QtCore
from thlib.environment import env_inst, env_mode, env_read_config, env_write_config
import thlib.maya_functions as mf
import thlib.tactic_classes as tc
import thlib.glo... | ain_tab.raise_()
main_tab.raise_window()
except:
# def server_ping_agent():
# return tc.server_ping()
#
# ping_worker, thr | ead_pool = gf.get_thread_worker(
# server_ping_agent,
# finished_func=lambda: create_ui(None),
# error_func=create_ui
# )
#
# thread_pool.start(ping_worker)
env_inst.start_pools()
worker = env_inst.server_pool.add_task(tc.server_ping)
... |
Ibuprofen/gizehmoviepy | node_positions_image.py | Python | mit | 1,603 | 0.008734 | import json
from PIL import Image, ImageFont, ImageDraw
with open('./config/nodes.json') as data_file:
data = json.load(data_file)
gray = (200, 200, 200)
black = (0,0,0)
lightblue = (225, 255, 255)
darkblue = (185, 255, 255)
img = Image.new("RGBA", (400,400), 128)
usr_font = ImageFont.truetype("./fonts/Arial.t... | ay, width | =1)
draw.line([(1, img.size[1]/2), (img.size[0]-1, img.size[1]/2)], fill=gray, width=1)
# top tier circle approximation
draw.ellipse([
(130, 130),
(270, 270)
], fill=None, outline=black)
# roof tier approximation
draw.ellipse([
(60, 60),
(340, 340)
], fill=None, outline=black)
# bottom tier (walls) appr... |
gstiebler/odemis | src/odemis/util/test/util_test.py | Python | gpl-2.0 | 8,569 | 0.001984 | #-*- coding: utf-8 -*-
"""
@author: Rinze de Laat
Copyright © 2013 Rinze de Laat, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Foundation.
Odemis is distributed in ... | ic License along with
Odemis. If not, see http://www.gnu.org/licenses/.
"""
from __future__ import division
from functools import partial
import gc
import logging
from odemis import util
from odemis.util import limit_invocation, TimeoutError
from odemis.util import timeout
import time
import unittest
import weakref
... | ogger().setLevel(logging.DEBUG)
class TestLimitInvocation(unittest.TestCase):
def test_not_too_often(self):
self.count = 0
now = time.time()
end = now + 1.1 # a bit more than 1 s
while time.time() < end:
self.count_max_1s()
time.sleep(0.01)
self.ass... |
mugurrus/superdesk-core | superdesk/io/feed_parsers/__init__.py | Python | agpl-3.0 | 14,119 | 0.002408 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from abc imp... | if setting_param_name is not None:
settings_mapping = getattr(superdesk.config, setting_param_name)
if settings_mapping is None:
logging.info("No mapping found in settings for NITF parser, u | sing default one")
settings_mapping = {}
else:
settings_mapping = {}
mapping = self.metadata_mapping = OrderedDict()
for source_mapping in (self.default_mapping, class_mapping, settings_mapping):
for key, value in source_mapping.items():
... |
DjenieLabs/django-multisites-utils | multisitesutils/__init__.py | Python | bsd-3-clause | 276 | 0.003623 | __version__ = '0.2.0'
c | lass Preferences(object):
"""
Placeholder class to which preferences properties are added
dynamically through a signal.
See behaviours.Preferences an | d behaviours.preferences_class_prepared
"""
pass
preferences = Preferences()
|
Captain-Coder/tribler | Tribler/Core/Modules/restapi/debug_endpoint.py | Python | lgpl-3.0 | 18,160 | 0.002203 | from __future__ import absolute_import
import logging
import os
import sys
import datetime
import psutil
from six import StringIO
from twisted.web import http, resource
from Tribler.Core.Utilities.instrumentation import WatchDog
import Tribler.Core.Utilities.json_util as json
HAS_MELIAE = True
try:
from meliae ... | n_file in my_process.open_files()]})
class DebugOpenSocketsEndpoint(resource.Resource):
"""
This class handles request for information about open sockets.
"""
def __init__(self, session):
resource.Resource._ | _init__(self)
self.session = session
def render_GET(self, request):
"""
.. http:get:: /debug/open_sockets
A GET request to this endpoint returns information about open sockets.
**Example request**:
.. sourcecode:: none
curl -X GET http://l... |
pbrod/scipy | scipy/interpolate/tests/test_polyint.py | Python | bsd-3-clause | 24,329 | 0.005754 | from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.testing import (
assert_almost_equal, assert_array_equal, assert_array_almost_equal,
TestCase, run_module_suite, assert_allclose, assert_equal, assert_,
assert_raises)
from scipy.interpolate im... | .xs,self. | ys)
assert_array_equal(P([]), [])
def test_shapes_scalarvalue(self):
P = KroghInterpolator(self.xs,self.ys)
assert_array_equal(np.shape(P(0)), ())
assert_array_equal(np.shape(P(np.array(0))), ())
assert_array_equal(np.shape(P([0])), (1,))
assert_array_equal(np.shape(... |
t-stark/ec2cli | scripts/pretest_setup.py | Python | gpl-2.0 | 6,293 | 0.001112 | """
Test Setup Module -- THIS SHOULD BE REPURPOSED, TRIGGERED BY make-test.sh script
"""
import os
import sys
import time
import json
import inspect
from configparser import ConfigParser
import logging
# aws imports
import boto3
import moto
import pytest
from botocore.exceptions import ClientError, ProfileNotFound
# ... | ers:
keys = iam_client.create_access_key(UserName=user)
access_key = | keys['AccessKey']['AccessKeyId']
secret_key = keys['AccessKey']['SecretAccessKey']
config[profile]
# write new keys
def assess_setup(self, *args):
for arg in args:
if arg is False:
return False
return True
if ___name__ == '__main__':
... |
huhuchen/asyncqueue | asyncqueue/_redis.py | Python | mit | 720 | 0.002778 | #!/usr/bin/en | v python
# -*- coding: utf-8 -*-
import redis
import json
class Redis(object):
def __init__(self, host="localhost", port=6379):
self._host = host
self._port = port
self._redis_cursor = None
d | ef conn(self):
if self._redis_cursor is None:
pool = redis.ConnectionPool(host=self._host, port=self._port, db=0)
self._redis_cursor = redis.Redis(connection_pool=pool)
def enqueue(self, qname, data):
self.conn()
self._redis_cursor.rpush(qname, json.dumps(data))
... |
Phaiax/ArcticTypescript | lib/display/views/Outline.py | Python | mit | 3,505 | 0.003994 | # coding=utf8
import sublime
from .Base import Base
from ...utils import Debug
from ...utils.uiutils import get_prefix
class Outline(Base):
regions = {}
ts_view = None
def __init__(self, t3sviews):
super(Outline, self).__init__('Typescript : Outline View', t3sviews)
# SET TEXT
def set_... | sing_ts_view:
Debug | ('focus', 'Outline.on_click: is just focusing other view > ignore')
return
if line in self.regions:
draw = sublime.DRAW_NO_FILL
self.ts_view.add_regions('typescript-definition', [self.regions[line]], 'comment', 'dot', draw)
self._focus_member_in_view(self.regions[... |
Rouslan/NTracer | scripts/polytope.py | Python | mit | 24,145 | 0.014206 | #!python
import math
import fractions
import pygame
import argparse
import os.path
import sys
import subprocess
import time
from itertools import combinations,islice
from ntracer import NTracer,Material,ImageFormat,Channel,BlockingRenderer,CUBE
from ntracer.pygame_render import PygameRenderer
ROT_SENSITIVITY = 0.005... | material) for tri in
self.tesselate(position,orientation))
return tris
def circumradius(self):
return self._circumradius
def circumradius_square(self):
return self._circumradius*self._circumradius
def line_apothem_square(self):
return 1
class Plane:
def _... | t.dot
def distance(self,point):
return self._dot(point,self.normal) + self.d
class Line:
def __init__(self,nt,p0,v,planes,outer=False):
self.p0 = p0
self.v = v
self.planes = set(planes)
self.outer = outer
self._dot = nt.dot
def point_at(self,t):
ret... |
xkmato/tracpro | tracpro/contacts/urls.py | Python | bsd-3-clause | 137 | 0 | from __future__ import absolute_import, unicode_literals
from . | views import ContactCRUDL
|
urlpatterns = ContactCRUDL().as_urlpatterns()
|
reinoud/factuursturen | factuursturen/__init__.py | Python | bsd-2-clause | 19,420 | 0.003862 | #!/usr/bin/env python
"""
a class to access the REST API of the website www.factuursturen.nl
"""
import collections
import ConfigParser
from datetime import datetime, date
import re
import requests
from os.path import expanduser
import copy
import urllib
__author__ = 'Reinoud van Leeuwen'
__copyright__ = "Copyright 2... | rc', expanduser('~/.factuursturen_rc')])
if (not apikey) and (not username):
try:
self._apikey = config.get(configsection, 'apikey')
self._username = config.get(configsection, 'username')
except ConfigParser.NoSectionError:
r | aise FactuursturenNoAuth ('key and username not given, nor found in .factuursturen_rc or ~/.factuursturen_rc')
except ConfigParser.NoOptionError:
raise FactuursturenNoAuth ('no complete auth found')
elif username and (not apikey):
self._username = username
for... |
TheDavidGithub/mysite | car/migrations/0001_initial.py | Python | gpl-2.0 | 1,116 | 0.000896 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration): |
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
| ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('city', models.CharField(max_length=50)),
('brand', models.CharField(max_length=50)),
('types', models.CharField(max_length=50)),
('car_time', mo... |
richo/groundstation | test/support/crypto_fixture.py | Python | mit | 10,569 | 0.001608 | #{{{ valid_key
valid_key = """-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAyGE8JpvCpp/0aLm6s0C56V5JtVr/fWra/pdFviA8YSabUlur
kcVPwoZLPbYmZtqmjfLSp5k1aCQbSqQDuB3nduFvWS6TzB8ACRDfw4KHE2D76pNE
lPbPejzIF8AyNKLrqi/Tba17cmqw1FFICg3B5ftu7mBzhJCPS/mt1i89CuoKVWRo
VB1CCKqJ0XIUO5/GC8nH2TwAzhnQpCx5B0bUJZkPxB5qbjXPpewY0IpSMNLrAGB... | E KEY-----
MIIEogIBAAKCAQEA8kRD19JjebNWHmGPnTcToYhFR2PE8XjiPJJ4qdd72AjHwGcJ
UZVGAuiFrtEX1QiG619ccUnm/wGPhTS19o4vImBLCz07soOb9qfkkl5b0tjYB9oq
oBbCs1sgPSnO1Ju05/FuVANDQH53jRpHi9t7Jta8A0fZ3t2j1nITwj/aJL4zC3lI
VIQXcR8DteKoY656eavLevKDXNueOpdJIa5kVR3cSLlJzNQGY1AJi4CXpr/+2Krh
mXr+SdHPDtgL0DpJsXVkDYkRkOxGJ49XlRq/SGH+mUhEVM6yX... | qSijo6lRRoO1p7wIDAQABAoIBAFVu21nVeHznUBxA
nUt8q7CQBJZLSZ052tYvdNu4AJVLa12fODsL3/eQlevzEmtuqV2BcHEG9a3BmCIK
V4zN0TNXL7+T5WRrYumVhVZUbh8plu0V82gm/pwPK4xGHQj+q8oLarO3vtSUhIY+
2TIpwQEOQpkJknw0Pt2VtwAOUlgYBuz9joirz8qgU63lRjrt1dok/tXUulaIXwIq
u7UNR+KltpM+OG8Dkw3dRGi0vd+0pE/udN08mIdbnpF0WxoRYDax5CPKTNVZnNA4
PyjPriXLQNbguRITZh... |
weijia/djangoautoconf | djangoautoconf/auto_detection/routing_auto_detection.py | Python | bsd-3-clause | 1,242 | 0.00161 | from importlib import import_module
from djangoautoconf.auto_conf_urls import enum_app_names
from djangoautoconf.auto_conf_utils import is_at_least_one_sub_filesystem_item_exists, get_module_path
from ufs_tools.short_decorator.ignore_exception import ignore_exc_with_result
def autodiscover():
from django.conf im... | n enum_app_names():
if app == "channels":
continue
mod = import_module(app)
if is_at_least_one_sub_filesystem_item_exists(get_module_path(mod), ["routing.py"]):
routing_module_name = "%s.routing" % app
routing_settings = get_routing_settings(routing_module_na... | ue)
def get_routing_settings(routing_module_name):
routing_module = import_module(routing_module_name)
routing_settings = routing_module.channel_routing
return routing_settings
|
modelblocks/modelblocks-release | resource-gcg/scripts/induciblediscgraph.py | Python | gpl-3.0 | 35,189 | 0.036204 | ###############################################################################
## ##
## This file is part of ModelBlocks. Copyright 2009, ModelBlocks developers. ##
## ##
... | ##
################################################################ | ###############
import sys, os, collections, sets
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import discgraph
VERBOSE = False
for a in sys.argv:
if a=='-d':
VERBOSE = True
################################################################################
def... |
amanzi/ats-dev | tools/visit_ats/visit_ats/visit_ats.py | Python | bsd-3-clause | 21,342 | 0.005716 | import sys, os
import visit_rcParams as vrc
import visit_colormaps as vc
import visit_time as vt
import visit as v
rcParams = dict( surface_linewidth=3,
snow_linewidth=4
)
class Operator:
def __init__(self, oname, otype, oatts):
self.oname = oname
self.otype = o... | h', "Mesh")
ma = v.MeshAttributes()
ma.legendFlag = 0
ma.meshColor = _colors[color]
ma.meshColorSource = ma.MeshCustom
if (opacity < 1.):
ma.opaqueMode = ma.On
ma.opacity = opacity
v.SetPlotOptions(ma)
pname = v.GetPlotL | ist().GetPlots(v.GetNumPlots()-1).plotName
if silo:
plot = Plot(pname, 'mesh', ma)
else:
plot = Plot(pname, 'Mesh', ma)
self.nonplots.append(plot)
return plot
def createPseudocolor(self, varname, display_name=None, cmap=None,
... |
hanmy75/voice-recognizer | src/aiy/audio.py | Python | apache-2.0 | 3,887 | 0.000772 | # 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, ... | wave file.
The wave file has to be mono and small enough to be loaded in memory.
"""
player = get_player()
player.play_wav(wave_file)
def play_audio(audio_data) | :
"""Plays the given audio data."""
player = get_player()
player.play_bytes(audio_data, sample_width=AUDIO_SAMPLE_SIZE, sample_rate=AUDIO_SAMPLE_RATE_HZ)
def say(words, lang=None):
"""Says the given words in the given language with Google TTS engine.
If lang is specified, e.g. "en-US', it will be... |
ivanlyon/exercises | kattis/k_statistics.py | Python | mit | 970 | 0.004124 | '''
Produce minimum, maximum and the difference of number list
Status: Accepted
'''
###############################################################################
def read_line_of_integers():
"""Read one line of numbers or detect EOF"""
try:
text = input()
return [int(i) for i in text.split... | , maxi, maxi - mini))
else:
break
###############################################################################
if __name__ == '__ma | in__':
main()
|
yuzheng/python-ex | checkDigit.py | Python | mit | 301 | 0.017668 | #-*-coding:UTF-8 -*-
#
# 判斷輸入是否為整數(int)
input_ | string = input('Please input n:')
#while input_string.isdigit() == False:
while not input_string.isdigit():
print("Error, %s is not digit | !" % input_string)
input_string = input('Please input n:')
print("%s is digit!" % input_string)
|
dalejung/trtools | trtools/io/tests/test_filecache.py | Python | mit | 1,754 | 0.008552 | from unittest import TestCase
from io import StringIO
from trtools.util.tempdir import TemporaryDirectory
import trtools.io.filecache as fc
class TestFileCache(TestCase):
def __init__(self, *args, **kwargs):
TestCase.__init__(self, *args, **kwargs)
def runTest(self):
pass
def setUp(self... | till works
assert mfc[key1].string == 'daledata2'
# this one should load keys from index file
mfc2 = fc.MetaFileCache(td)
for a,b in zip( list(mfc2.keys()), list(mfc.keys())):
assert a.key == b.key
if __name__ == '__main__': ... | v=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],exit=False)
|
nakul02/incubator-systemml | src/main/python/systemml/mlcontext.py | Python | apache-2.0 | 25,332 | 0.004934 | #-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distribut | ed 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 this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... | istributed 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.
#
#-------------------------------------------------------------
# Method... |
google/or-tools | examples/tests/issue46.py | Python | apache-2.0 | 3,057 | 0 | #!/usr/bin/env python3
# Copyright 2010-2021 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 ... | als
def Next(self, solver):
| for interval in self.__intervals:
interval.SetStartMax(interval.StartMin())
return None
def DebugString(self):
return 'CustomDecisionBuilder'
def NoSequence():
print('NoSequence')
solver = pywrapcp.Solver('Ordo')
tasks = []
[
tasks.append(
solver.... |
uclouvain/osis | attribution/tests/factories/attribution_charge_new.py | Python | agpl-3.0 | 2,021 | 0.001485 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers | ion.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License -... |
martastain/nxtools | setup.py | Python | mit | 989 | 0.0182 | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
| name = "nxtools",
version = "0.8.4",
author = "Martin Wacker",
author_email = "martas@imm.cz",
description = "Set of common utilities and little helpers.",
license = "MIT",
keywords = "utilities log logging ffmpeg watchfolder media mam time",
url = "https://github.com/immstudios/nxtools",
... | "Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Topic :: Multimedia :: Video :: Conversion",
"Topic :: U... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.