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 |
|---|---|---|---|---|---|---|---|---|
dominicgs/GreatFET-experimental | host/greatfet/interfaces/pattern_generator.py | Python | bsd-3-clause | 2,137 | 0.006083 | #
# This file is part of GreatFET
#
from ..interface import GreatFETInterface
class PatternGenerator(GreatFETInterface):
"""
Class that supports using the GreatFET as a simple pattern generator.
"""
def __init__(self, board, sample_rate=1e6, bus_width=8):
""" Set up a GreatFET pattern ge... | ate, self.bus_width, len(samples), repeat)
def stop(self):
""" Stops the board from scanning out any further samples. """
self.api.stop()
def dump_sgpio_config(self, include_unused=False):
""" Debug function; returns the board's dumped SGPIO configuration. """
self.api.dump_... | |
ewandor/home-assistant | homeassistant/components/neato.py | Python | apache-2.0 | 3,962 | 0 | """
Support for Neato botvac connected vacuum cleaners.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/neato/
"""
import logging
from datetime import timedelta
from urllib.error import HTTPError
import voluptuous as vol
import homeassistant.helpers.co... |
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
})
}, extra=vol.ALLOW_EXTRA)
STATES = {
1: 'Idle',
2: 'Busy',
3: 'Pause',
4: 'Error'
}
MODE = {
1: 'Eco',
2: 'Turbo'
}
ACTION = {
0: ... | ,
1: 'House cleaning',
2: 'Spot cleaning',
3: 'Manual cleaning',
4: 'Docking',
5: 'User menu active',
6: 'Cleaning cancelled',
7: 'Updating...',
8: 'Copying logs...',
9: 'Calculating position...',
10: 'IEC test'
}
ERRORS = {
'ui_error_brush_stuck': 'Brush stuck',
'ui_err... |
ikoula/cloudstack | test/integration/component/test_vpc_network_pfrules.py | Python | gpl-2.0 | 43,341 | 0.004961 | # 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... | per(TestVPCNetworkPFRules, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
... |
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
... |
GrampusTeam/Grampus | core/directorio.py | Python | bsd-3-clause | 750 | 0.005333 | import os
import tempfile
import shutil
def listar(director | io):
"""Regresa uns lista con los archivos contenidos
en unca carpeta"""
archivos = os.listdir(directorio)
buff = []
for archivo in archivos:
ruta = os.path.join(directorio, archivo)
if os.path.isfile(ruta):
buff.append(ruta)
return buff
def crear(prefijo="Gram... | ruta
la variable prefijo define el prefijo que se usara para la
carpeta, por defecto se usara Gram"""
temp = tempfile.mkdtemp(prefix=prefijo)
return temp
def eliminar(ruta):
"""Elimina un directorio, toma como parametro la ruta del directorio
a eliminar"""
shutil.rmtree(ruta) |
apache/libcloud | docs/examples/compute/azure/instantiate.py | Python | apache-2.0 | 212 | 0.004717 | from libcloud.compute. | types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE)
driver = cls(subscription_id="subscription-id", key_fil | e="/path/to/azure_cert.pem")
|
WillianPaiva/1flow | oneflow/settings/snippets/api_keys.py | Python | agpl-3.0 | 1,941 | 0 | # -*- coding: utf-8 -*-
#
# Django API keys, all loaded from the environment,
# conforming to http://www.12factor.net/config :-D
#
u"""
Copyright 2013 Olivier Cortès <oc@1flow.io>.
This file is part of the 1flow project.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affer... | UTH2_SECRET',
'SOCIAL_AUTH_GITHUB | _KEY',
'SOCIAL_AUTH_GITHUB_SECRET',
'SOCIAL_AUTH_FACEBOOK_KEY',
'SOCIAL_AUTH_FACEBOOK_SECRET',
# 'SOCIAL_AUTH_GOOGLE_PLUS_KEY',
# 'SOCIAL_AUTH_GOOGLE_PLUS_SECRET',
'SOCIAL_AUTH_LINKEDIN_KEY',
'SOCIAL_AUTH_LINKEDIN_SECRET',
# •••••••••••••••••••••••••••••••••••••••••••••••••••••••••• ... |
opadron/girder | plugins/user_quota/server/quota.py | Python | apache-2.0 | 18,128 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2015 Kitware 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 cop... | 'collection', collection)
getCollectionQuota.description = (
Description('Get quota and assetstore policies for the collection.')
.param('id', 'The collection ID', paramType='path')
.errorResponse('ID was invalid.')
.errorResponse('Read permission denied on the collection.', 403))
... | ta(self, collection, params):
return self._setResourceQuota('collection', collection, params)
setCollectionQuota.description = (
Description('Set quota and assetstore policies for the collection.')
.param('id', 'The collection ID', paramType='path')
. |
mozilla/betafarm | apps/projects/tests.py | Python | bsd-3-clause | 17,989 | 0.000111 | import os
from django.conf import settings
from django.contrib.auth.models import User
import requests
from test_utils import TestCase, SkipTest
from commons.urlresolvers import reverse
from projects import cron
from projects.models import DEFAULT_INACTIVE_MESSAGE, Link, Project
from topics.models import Topic
from ... | ath.dirname(__file__)),
'test_data',
'abide.jpg')
with open | (fname) as f:
# TODO: make localized URL handling suck less
self.client.post('/en-US' + self.project.get_edit_url(), {
'name': self.project.name,
'slug': self.project.slug,
'description': self.project.description,
'long_description'... |
dywisor/kernelconfig | kernelconfig/kconfig/abc/solcache.py | Python | gpl-2.0 | 696 | 0 | # kernelconfig -- abstract description of Kconfig-related classes
# -*- coding: utf-8 -*-
import abc
__all__ = ["AbstractSymbo | lExprSolutionCache"]
class AbstractSymbolExprSolutionCache(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def push_symbol(self, sym, values):
raise NotImplementedError()
@abc.abstractmethod
def get_solutions(self):
raise NotImplementedError()
@abc.abstractmethod
def mer... |
@abc.abstractmethod
def copy(self):
raise NotImplementedError()
|
corona10/grumpy | grumpy-tools-src/grumpy_tools/compiler/stmt_test.py | Python | apache-2.0 | 16,929 | 0.004726 | # coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | foo = 8
foo **= 2
print foo""")))
def testClassDef(self):
self.assertEqual((0, "<type 'type'>\n"), _GrumpRun(textwrap.dedent("""\
class Foo(object):
pass
print type(Foo)""")))
def testClassDefWithVar(self):
self.assertEqual((0, 'abc\n'), _GrumpRun(textwrap.dede... | , 'False\n'), _GrumpRun(textwrap.dedent("""\
class Foo(object):
bar = 42
del Foo.bar
print hasattr(Foo, 'bar')""")))
def testDeleteClassLocal(self):
self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\
class Foo(object):
bar = 'baz'
del bar... |
sn6uv/gmpy_cffi | tests/test_special_functions.py | Python | bsd-3-clause | 9,191 | 0.002176 | import sys
import pytest
from gmpy_cffi import (
log, log2, log10, exp, exp2, exp10, cos, sin, tan, sin_cos, sec, csc, cot,
acos, asin, atan, atan2, cosh, sinh, tanh, sinh_cosh, sech, csch, coth,
acosh, asinh, atanh, factorial, log1p, expm1, eint, li2, gamma, lngamma,
lgamma, digamma, zeta, erf, erfc,... | est.raises(TypeError):
log([])
def test_log(self):
assert log(0.5) == mpfr('-0.69314718055994529')
assert log(0.5+0.7j) == mpc('-0.15055254639196086+0.95054684081207508j')
def test_log2(self):
assert log2(0.5) == mpfr('-1.0')
def test_log10(self):
assert log10(... | -0.065384140134511923+0.41281724775525297j')
def test_exp(self):
assert exp(0.5) == mpfr('1.6487212707001282')
assert exp(0.5+0.7j) == mpc('1.2610115829047472+1.0621354039100237j')
def test_exp2(self):
assert exp2(0.5) == mpfr('1.4142135623730951')
def test_exp10(self):
as... |
zeromq/pyre | tests/test_zbeacon.py | Python | lgpl-3.0 | 2,243 | 0.002675 | import unittest
import zmq
import struct
import uuid
import socket
from pyre.zactor import ZActor
from pyre.zbeacon import ZBeacon
class ZBeaconTest(unittest.TestCase):
def setUp(self, *args, **kwargs):
ctx = zmq.Context()
ctx = zmq.Context()
# two beacon frames
self.transmit1 ... | oy()
# end tearDown
def test_node1(self):
self.node1.send_unicode("PUBLISH", zmq.SNDMORE)
self.node1.send(self.transmit1)
def test_node2(self):
self.node2.send_unicode("PUBLISH", zmq.SNDMORE)
self.node2.send(self.transmit2)
def test_recv_beacon1(self):
self.nod... | req = self.node1.recv_multipart()
self.assertEqual(self.transmit2, req[1])
def test_recv_beacon2(self):
self.node1.send_unicode("PUBLISH", zmq.SNDMORE)
self.node1.send(self.transmit1)
self.node2.send_unicode("PUBLISH", zmq.SNDMORE)
self.node2.send(self.transmit2)
re... |
nino-c/plerp.org | src/portfolio/migrations/0012_canvasappportfolioitem_appname.py | Python | mit | 431 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class | Migration(migrations.Migration):
dependencies = [
('portfolio', '0011_auto_20160115_0105'),
]
operations = [
migrations.AddField(
model_name='canvasappportfolioitem',
name='appname',
field=models.CharField(max_length=100, | null=True),
),
]
|
aphelps/HMTL | python/Bootstrap.py | Python | mit | 3,352 | 0.002685 | #!/usr/bin/python
#
# Bootstrap script for a new device. This uploads a configuration and installs
# the Bringup sketch.
#
import sys
import os
import argparse
import subprocess
import hmtl.portscan as portscan
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", dest=... | lp="Arduino USB device")
parser.add_argument("-i", "--deviceid", dest="deviceid",
required=True,
help="Device ID to configure")
parser.add_argument("-a", "--address", dest="address",
help="Address to configure (defaults to device ID)")
... | help="Device type for platformio scripts (nano, mini, uno, moteinomega, etc) [%(default)s)]")
parser.add_argument("-s", "--stages", dest="stages",
default="1,2,3",
help="Stages to execute [%(default)s]")
parser.add_argument("--module", dest="m... |
laosiaudi/tensorflow | tensorflow/contrib/distributions/python/ops/distribution.py | Python | apache-2.0 | 33,964 | 0.005565 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | % (base.__name__, attr))
class_attr_value.__doc__ = _update_docstring(
class_attr_value.__doc__,
("Additional documentation from `%s`:\n\n%s"
% (classname, class_special_attr_docstring)))
attrs[attr] = class_attr_value
return abc | .ABCMeta.__new__(mcs, classname, baseclasses, attrs)
@six.add_metaclass(_DistributionMeta)
class Distribution(_BaseDistribution):
"""A generic probability distribution base class.
`Distribution` is a base class for constructing and organizing properties
(e.g., mean, variance) of random variables (e.g, Bernoull... |
jgmize/tulsawebdevs.org | talks/migrations/0003_auto_20150816_2148.py | Python | gpl-3.0 | 722 | 0.00277 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('talks', '0002_auto_20150808_2108'),
]
operations = [
migrations.AlterField(
m... | migrations.AlterField(
model_name='talk',
name='speaker',
field=models.ForeignKey( | null=True, blank=True, related_name='talks', to='talks.Speaker'),
),
]
|
GooseDad/Test | riding_forecast.py | Python | apache-2.0 | 8,045 | 0.00087 | import csv
import datetime
from scipy.stats import norm
from regional_poll_interpolator import RegionalPollInterpolator
import riding_poll_model
party_long_names = {
'cpc': 'Conservative/Conservateur',
'lpc': 'Liberal/Lib',
'ndp': 'NDP-New Democratic Party/NPD-Nouveau Parti d',
'gpc': 'Green Party/Pa... | r feeder_number, weight in r['feeders'].items():
| feeder = old_ridings[feeder_number]
normalized = NormalizeDictVector(feeder['projections'])
for party, support in normalized.items():
if party not in projections:
projections[party] = 0
projections[party] += support * weight
... |
xloc/SwimmingPool | Questions Submit/Q1/Q1_xiong.py | Python | unlicense | 189 | 0.031746 | workhour=input('enter work hour:')
workra | te=input('enter work rate:')
if workhour>40:
pay=40*workrate+(workhour-40)*workrate*1.5
else:
pay=workhour*workrate
print 'pay:', | pay
|
rbtcollins/lmirror | l_mirror/tests/logging_resource.py | Python | gpl-3.0 | 2,057 | 0.004861 | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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
# versio... | licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""A test resource to provide isolation for the logging module (sigh, globals)."""
__all__ = ['LoggingResourceManager']
import logging
from testresources import TestResourceManager
from l_mirror... | keypatch
class OldState:
def __init__(self, restore_functions):
self.restore_functions = restore_functions
def tearDown(self):
for fn in self.restore_functions:
fn()
class LoggingResourceManager(TestResourceManager):
"""A resource for testing logging module using code.
... |
JshWright/home-assistant | homeassistant/components/cover/opengarage.py | Python | apache-2.0 | 6,089 | 0 | """
Platform for the opengarage.io cover component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/cover.opengarage/
"""
import logging
import voluptuous as vol
import requests
from homeassistant.components.cover import (
CoverDevice, PLATFORM_SCHEMA... | imeout=10)
return ret.json()
def _push_butt | on(self):
"""Send commands to API."""
url = '{}/cc?dkey={}&click=1'.format(
self.opengarage_url, self._devicekey)
try:
response = requests.get(url, timeout=10).json()
if response["result"] == 2:
_LOGGER.error("Unable to control %s: device_key i... |
atheendra/access_keys | keystone/tests/test_wsgi.py | Python | apache-2.0 | 12,889 | 0 | # Copyright 2012 OpenStack Foundation
#
# 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... | def test_middleware_response(self):
class FakeMiddleware(wsgi. | Middleware):
def process_response(self, request, response):
response.environ = {}
response.environ['fake_response'] = True
return response
req = self._make_request()
resp = FakeMiddleware(self.app)(req)
self.assertIn('fake_response', re... |
atvcaptain/enigma2 | lib/python/Components/Converter/EventTime.py | Python | gpl-2.0 | 7,587 | 0.027547 | from __future__ import absolute_import
from Components.Converter.Converter import Converter
from Components.Converter.Poll import Poll
from time import time
from Components.Element import cached, ElementError
from Components.config import config
from enigma import eEPGCache
class EventTime(Poll, Converter, object):
S... | pe == "ThirdEndTime":
self.type = self.THIRD_END_TIME
elif type == "ThirdDuration":
self.type = self.THIRD_DURATION
elif type == "Times":
self.type = self.TIMES |
elif type == "NextTimes":
self.type = self.NEXT_TIMES
elif type == "ThirdTimes":
self.type = self.THIRD_TIMES
else:
raise ElementError("'%s' is not <StartTime|EndTime|Remaining|Elapsed|Duration|Progress|VFDRemaining|VFDElapsed|NextStartTime|NextEndTime|NextDuration|ThirdStartTime|ThirdEndTime|ThirdDurat... |
ml9951/ghc | libraries/pastm/examples/damp-comparing-linked-lists/bench.py | Python | bsd-3-clause | 1,511 | 0.017869 | #!/usr/bin/env python
import argparse, subprocess, pdb, re
parser = argparse.ArgumentParser()
parser.add_argument("-iters", type=int, help="Number of iterations for each STM implementation", default=3)
parser | .add_argument("-opt", type=str, help="Optimization level", default="")
parser.add_argument("-cores", type=int, help= | "Number of cores to go up to", default=4)
parser.add_argument("-stm", type=str, help="Which STM to use", default="partial")
args = parser.parse_args()
makeCmds = [('mvar', 'mvar') , ('partial straight', 'straightForwardParital'), ('partial dissected', 'dissectedPartial'), ('cas', 'cas')]
filename = 'Times.txt'
l = ... |
adazey/Muzez | libs/nltk/metrics/association.py | Python | gpl-3.0 | 15,878 | 0.0017 | # Natural Language Toolkit: Ngram Association Measures
#
# Copyright (C) 2001-2016 NLTK Project
# Author: Joel Nothman <jnothman@student.usyd.edu.au>
# URL: <http://nltk.org>
# For license information, see LICENSE.TXT
"""
Provides scoring functions for a number of association measures through a
generic, abstr... | in a corpus. The letter i in the
suffix refers to the appearance of the word in question, while x indicates
the appearance of any word. Thus, for example:
n_ii counts (w1, w2), i.e. the bigram being scored
n_ | ix counts (w1, *)
n_xi counts (*, w2)
n_xx counts (*, *), i.e. any bigram
This may be shown with respect to a contingency table::
w1 ~w1
------ ------
w2 | n_ii | n_oi | = n_xi
------ ------
~w2 | n_io | n_oo |
-... |
andresailer/DIRAC | Core/DISET/TransferClient.py | Python | gpl-3.0 | 6,920 | 0.034682 | """ This is for transfers what RPCClient is for RPC calls
"""
__RCSID__ = "$Id$"
import os
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities import File
from DIRAC.Core.DISET.private.BaseClient import BaseClient
from DIRAC.Core.DISET.private.FileHelper import FileHelper
class TransferClient( BaseClient ):
... | kId = "%s.tar" % bulkId
retVal = self._sendTransferHeader( "BulkFromClient", ( bulkId, token, bulkSize ) )
if not retVal[ 'OK' ]:
return retVal
trid, transport = retVal[ 'Value' ]
try:
fileHelper = FileHelper( transport )
retVal = fileHelper.bulkToNetwork( fileList, compr | ess, onthefly )
if not retVal[ 'OK' ]:
return retVal
retVal = transport.receiveData()
return retVal
finally:
self._disconnect( trid )
def receiveBulk( self, destDir, bulkId, token = "", compress = True ):
"""
Receive a bulk of files from server
:type destDir : list of... |
adafruit/Adafruit_Python_GPIO | Adafruit_GPIO/I2C.py | Python | mit | 9,083 | 0.002752 | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Based on Adafruit_I2C.py created by Kevin Townsend.
#
# 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, inc... | self._logger.debug("Read 0x%02X from register 0x%02X",
result, register)
return result
def readS8(self | , register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
if result > 127:
result -= 256
return result
def readU16(self, register, little_endian=True):
"""Read an unsigned 16-bit value from the specified register, with the
... |
Raekkeri/django-formsettesthelpers | src/formsettesthelpers/tests.py | Python | mit | 4,321 | 0.000463 | from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.forms.models import modelformset_factory
from django.forms.formsets import formset_factory
from formsettesthelpers import *
from formsettesthelpers.test_app.forms import (
UserF... | mSet)
| data = formset_helper.generate([
{'username': 'admin', 'email': 'admin@example.com'},
{'username': 'user1', 'email': 'userer@example.com'},
], total_forms=2)
# `data` now contains the formset data, something like
# """{u'form-INITIAL_FORMS': 0, u'form-MAX_NUM_FORM... |
hockeybuggy/bigcommerce-api-python | bigcommerce/resources/banners.py | Python | mit | 218 | 0 | from .base import *
class Banners(ListableApiResource, CreateableApiResour | ce,
UpdateableApiResource, DeleteableApiRes | ource,
CollectionDeleteableApiResource):
resource_name = 'banners'
|
zhusz/ICCV17-fashionGAN | language/test_te.py | Python | bsd-3-clause | 2,918 | 0.002056 | import numpy as np
import sys
from random import randint
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from scipy.io import loadmat
from scipy.io import savemat
mat = loadmat('../data_release/benchmark/language_original.mat')
for k, v in mat.iteritems():
exec(k +... | gender = Variable(torch.LongTensor(bsz).zero_().cuda())
cuda_label_sleeve = Variable(torch.LongTensor(bsz).zero_().cuda())
model.eval()
test_hn2 = np.zeros((m, dim_h))
test_cate_new = np.zeros((m, dim_cate_new))
test_color = np.zeros((m, dim_color))
test_gender = np.zeros((m, dim_gender))
test_sleeve = np.zeros((m, d... | if sample_id % 1000 == 1:
print(sample_id)
c = codeJ[sample_id][0]
l = len(c)
cuda_c_onehot = torch.zeros(l, bsz, dim_voc).cuda()
for i in range(l):
cuda_c_onehot[i][0][int(c[i][0]-1)] = 1
cuda_c_onehot = Variable(cuda_c_onehot)
hn2, y_cate_new, y_color, y_gender, y_sleeve = mod... |
gaolichuang/py-essential | essential/db/sqlalchemy/migration.py | Python | apache-2.0 | 10,186 | 0.000393 | # coding: utf-8
#
# Copyright (c) 2013 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
#
# Unle... | e
unique constraint and a migration adding another one
you will end up with a table that has only the
latter unique constraint, and the former will be lost
- dropping of unique constraints | is not supported at all
The proper way to fix this is to provide a pull-request to
sqlalchemy-migrate, but the project seems to be dead. So we
can go on with monkey-patching of the lib at least for now.
"""
# this patch is needed to ensure that recreate_table() doesn't drop
# existing unique... |
iitml/AL | front_end/gui/plot_vals.py | Python | gpl-2.0 | 10 | 0 | val | s = {} | |
pioneers/topgear | python/forseti2/xbox_joystick_state.py | Python | apache-2.0 | 2,436 | 0.007389 | """LCM type definitions
This file automatically generated by lcm.
DO NOT MODIFY BY HAND!!!!
"""
import cStringIO as StringIO
import struct
import header
class xbox_joystick_state(object):
__slots__ = ["header", "axes", "buttons"]
A = 0
B = 1
X = 2
Y = 3
LB = 4
RB = 5
BACK = 6
STA... | 322355bddf3cb+ header.header._get_hash_recursive(newparents)) & 0xffffffffffffffff
tmphash = (((tmphash<<1)&0xffffffffffffffff) + (tmphash>>63)) & 0xffffffffffffffff
return tmphash
_get_hash_recursive = staticmethod(_get_hash_recursive)
_packed_fingerprint = None
| def _get_packed_fingerprint():
if xbox_joystick_state._packed_fingerprint is None:
xbox_joystick_state._packed_fingerprint = struct.pack(">Q", xbox_joystick_state._get_hash_recursive([]))
return xbox_joystick_state._packed_fingerprint
_get_packed_fingerprint = staticmethod(_get_packed_f... |
avanzosc/event-wip | sale_order_create_event_hour/wizard/wiz_event_append_assistant.py | Python | agpl-3.0 | 3,966 | 0 | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import fields, models, api
from openerp.addons.event_track_assistant._common import\
_convert_to_utc_date, _convert_to_local_date, _convert_time_to_float
date2string = fi... | (_co | nvert_to_utc_date(
self.max_to_date, tz=tz), tz=tz)
def _update_registration_start_date(self, registration):
super(WizEventAppendAssistant, self)._update_registration_start_date(
registration)
reg_date_start = str2datetime(registration.date_start)
if self.start_time:... |
harvard-lil/nuremberg | nuremberg/transcripts/migrations/0002_transcriptpage_updated_at.py | Python | mit | 619 | 0.001616 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-16 22:52
from __future__ import unicode_literals
import datetime
from d | jango.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dep | endencies = [
('transcripts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='transcriptpage',
name='updated_at',
field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 6, 16, 22, 52, 58, 616986, tzinfo=utc)),
... |
UWNetworksLab/metasync | metasync/metasyncAPI.py | Python | mit | 48,287 | 0.003769 | import os
import io
import sys
import time
import threading
import struct
import pickle
import tempfile
import shutil
import types
from threading import Thread
from Queue import Queue
from multiprocessing import cpu_count
from mapping import DetMap2
import dbg
import util
import services
import translators
from blob... | lt is not None:
return str(default)
# dirty user's input
print "input the number of replicas (default=2)"
while True:
replicas = raw_input("> ").strip()
if replicas == "":
replicas = "2"
if replicas.isdigit():
| if int(replicas) > nservices:
dbg.err("the number of replicas should not be larger than the number of services")
else:
return replicas
else:
print "input the number"
def _get_conf_encryptkey(default):
assert type(default) in [types.NoneType,... |
ericmjl/bokeh | examples/integration/widgets/tabs_with_multiselect.py | Python | bsd-3-clause | 195 | 0 | from bokeh.io import | save
from bokeh.models import MultiSelect, Tabs
select = MultiSelect(options=["First option", "Second option"])
tabs = Tabs(tabs=[("A tab", select)], widt | h=300)
save(tabs)
|
les69/calvin-base | calvin/tests/test_actor.py | Python | apache-2.0 | 7,248 | 0.000552 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | l", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_sig | nature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.compone... |
fabsx00/joern-tools | joerntools/mlutils/pythonEmbedder/PythonEmbedder.py | Python | gpl-3.0 | 2,124 | 0.01177 | import os
from FeatureArray import FeatureArray
from FeatureArrayToMatrix import FeatureArrayToMatrix
class Embedder:
def embed(self, directory, tfidf = True):
"""
For a given directory containing a TOC and a data/
directory as, for example, created by joern-demux,
create an e... |
outFile.close()
if __name__ == '__main__':
import sys
embeder = Em | bedder()
embeder.embed(sys.argv[1])
|
team-phoenix/Phoenix | frontend/python/updaters/sqlTableUpdater.py | Python | gpl-2.0 | 50,004 | 0.00792 | import os
from collections import OrderedDict
from .sqldatabase import SqlDatabase
from .retrieve_core_info import retrieveCoreInfo
# Root class that all SQL table updaters derive from
class SqlTableUpdater():
def __init__(self, tableName, tableColumns=[], coreInfo={}):
self.tableName = tableName
... | ms.append(tup[1] | )
# There are some cores that do not have "database" defined
elif "systemname" in v:
systems.append(v["systemname"])
systems = list(set(systems))
systems.sort()
return systems
# This map defines all Libretro-based systems that Phoenix supports. If i... |
kawamon/hue | desktop/core/ext-py/eventlet-0.24.1/tests/subprocess_test.py | Python | apache-2.0 | 3,313 | 0.000302 | import sys
import time
import eventlet
from eventlet.green import subprocess
import eventlet.patcher
import tests
original_subprocess = eventlet.patcher.original('subprocess')
def test_subprocess_wait():
# https://bitbucket.org/eventlet/eventlet/issue/89
# In Python 3.3 subprocess.Popen.wait() method acquire... | assert e.timeout == 0.1
ok = True
tdiff = time.time() - t1
assert ok, 'did not raise subprocess.TimeoutExpired'
assert 0.1 <= tdiff <= 0.2, 'did not stop within allowed time'
def test_communicate_with_poll():
# This test was being skipped since git 25812fca8, I don't there's
# a need to... | /eventlet/eventlet/pull/24
# `eventlet.green.subprocess.Popen.communicate()` was broken
# in Python 2.7 because the usage of the `select` module was moved from
# `_communicate` into two other methods `_communicate_with_select`
# and `_communicate_with_poll`. Link to 2.7's implementation:
# http://hg... |
SThomasP/ECSSystemsBot | TestProcedures/GetWebPage.py | Python | gpl-3.0 | 1,077 | 0.011142 | from urllib.request import urlopen
for line in urlopen('https://secure.ecs.soton.ac.uk/status/'):
line = line.decode('utf-8') # Decoding the binary data to text.
if 'Core Priority Devices' in line: #look for 'Core Priority Devices' To find the line of text with the list of issues
linesIWant = line.spl... | x' in f:
if 'machine' in f:
machineName=f.split('<b>')[1].split('</b>')[0]
if 'state_2' in f:
service=f.split('<td>')[2].split('</td>')[0]
problem=f.split('<td>')[3].split('</td>')[0]
issues.append(service+','+machineName+','+problem+'\n')
... | [1].split('</td>')[0]
problem=f.split('<td>')[2].split('</td>')[0]
issues.append(service+','+machineName+','+problem+'\n')
logfile=open('newlog.txt','w')
logfile.writelines(issues)
logfile.close()
|
tomviner/exploring-unittesting-talk | code-examples/test_unittest_suite.py | Python | apache-2.0 | 610 | 0.008197 | import unittest
def add(a, b):
return | a + b
class TestKnownGood(unittest.TestCase):
def __init__(self, input, output) | :
super(TestKnownGood, self).__init__()
self.input = input
self.output = output
def runTest(self):
self.assertEqual(add(*self.input), self.output)
def suite():
suite = unittest.TestSuite()
known_values = [
((1, 2), (3)),
((2, 3), (5)),
]
suite.addTes... |
need12648430/OmegaPy | Chatbot.py | Python | mit | 980 | 0.040816 | """
demo: simple chatbot
connects with a stranger greeting them with "hi, i'm a chatbot"
then proceeds to echo all messag | es sent to it
"""
from Omegle import *
import time
class SimpleChatbot(OmegleHandler):
def on_connect(self):
print "stranger connected"
greeting = "hi, i'm a chatbot"
self.omegle.send(greeting)
print "y > " + greeting
def on_typing_start(self):
print "stranger | is typing..."
def on_typing_stop(self):
print "stranger stopped typing."
def on_message(self, message):
print "s > " + message
# pretend to type for 1 second to look real
self.omegle.start_typing()
time.sleep(1)
# send message
self.omegle.send(message)
# tell omegle we're done "typing"
self.... |
vsajip/django | tests/regressiontests/introspection/tests.py | Python | bsd-3-clause | 6,655 | 0.003606 | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods... | mes(only_existin | g=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_... |
arokem/pyAFQ | examples/plot_afq_reco80.py | Python | bsd-2-clause | 2,044 | 0.002446 | """
==========================
RecoBundles80 using AFQ API
==========================
An example using the AFQ API to run recobundles with the
`80 bundle atlas <https://figshare.com/articles/Advanced_Atlas_of_80_Bundles_in_MNI_space/7375883>`_.
"""
import os.path as op
import plotly
from AFQ.api.group import GroupA... | e,
rng_seed=42)
##########################################################################
# Initialize an AFQ object:
# -------------------------
#
# We specify seg_algo as reco80 in segmentation_params. This tells the AFQ
# object to perform RecoBundles using the 80 bundles atlas in the
# segm... | 'stanford_hardi'),
preproc_pipeline='vistasoft',
segmentation_params={"seg_algo": "reco80"},
tracking_params=tracking_params)
##########################################################################
# Visualizing bundles and tract profiles:
# ----------------------... |
kaija/tw-stock | stock.py | Python | mit | 11,215 | 0.009362 | import datetime
i | mport httplib
import urllib
import os.path
import csv
import time
from datetime import timedelta
import pandas as pd
import numpy as np
def isfloat(value):
try:
float(value)
return | True
except ValueError:
return False
def totimestamp(dt, epoch=datetime.date(1970,1,1)):
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
class stockImport(object):
def __init__(self
):
print ('... |
humdings/zipline | zipline/utils/cache.py | Python | apache-2.0 | 10,994 | 0 | """
Caching utilities for zipline
"""
from collections import MutableMapping
import errno
import os
import pickle
from distutils import dir_util
from shutil import rmtree, move
from tempfile import mkdtemp, NamedTemporaryFile
import pandas as pd
from .context_tricks import nop_context
from .paths import ensure_direct... | ization.split(':', 1)
if s[0] != 'pickle':
| raise ValueError(
"'serialization' must be either 'msgpack' or 'pickle[:n]'",
)
self._protocol = int(s[1]) if len(s) == 2 else None
self.serialize = self._serialize_pickle
self.deserialize = pickle.load
ensure_directory(sel... |
snazy/cassandra-dtest | snapshot_test.py | Python | apache-2.0 | 23,150 | 0.003024 | import distutils.dir_util
import glob
import os
import shutil
import subprocess
import time
from cassandra.concurrent import execute_concurrent_with_args
from dtest import (Tester, cleanup_cluster, create_ccm_cluster, create_ks,
debug, get_test_path)
from tools.assertions import assert_one
from too... | def restore_snapshot(self, snapshot_dir, node, ks, cf):
debug("Restoring snapshot....")
for x in xra | nge(0, self.cluster.data_dir_count):
snap_dir = os.path.join(snapshot_dir, str(x), ks, cf)
if os.path.exists(snap_dir):
ip = node.address()
args = [node.get_tool('sstableloader'), '-d', ip, snap_dir]
p = subprocess.Popen(args, stdout=subprocess.PI... |
SublimeText/Modelines | tests/sublime_plugin.py | Python | mit | 206 | 0.024272 | class Plugin(object):
pass
class ApplicationCommand(Plugin):
pass
class WindowComma | nd(Plugin):
pass
class TextCommand(Plugin):
pass
class Even | tListener(Plugin):
pass |
boriel/zxbasic | src/arch/z80/optimizer/labelinfo.py | Python | gpl-3.0 | 704 | 0.00142 | # -*- coding: utf-8 -*-
from | src.api.identityset import IdentitySet
from . import common
from . import errors
class LabelInfo(object):
"""Class describing label information"""
def __init__(self, label, addr, basic_block=None, position=0):
"""Stores the label name, the address counter into memory (rather useless)
and whic... | # Position within the block
self.used_by = IdentitySet() # Which BB uses this label, if any
if label in common.LABELS:
raise errors.DuplicatedLabelError(label)
|
vied12/superdesk | server/publicapi/tests/prepopulate_init_app_test.py | Python | agpl-3.0 | 2,453 | 0.000815 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors.
#
# For the full copyright and license informa | tion, please see the
# AUTHORS and LICENSE file | s distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from publicapi.tests import ApiTestCase
from unittest import mock
from unittest.mock import MagicMock
_fake_prepopulate_resource = MagicMock()
_fake_prepopulate_service = MagicMock()
_fake_backend = MagicMock(name='superdesk... |
sergpolly/Thermal_adapt_scripts | perform_indexing.py | Python | mit | 731 | 0.012312 | import sys
from Bio import SeqIO
# see corresponding description in the project's wiki
inventory = sys.argv[1]
db_file = sys.argv[2]
seq_format = sys.argv[3]
# sanity check is ommited for such a short and simple script
# get the files names to be indexed
with open(inventory,'r') as fp:
fnames = [line.strip() f... | "f | asta":
get_index = lambda name: name.split('|')[3]
res = SeqIO.index_db(db_file,filenames=fnames,format=seq_format,key_function=get_index)
else:
print "Only genbank and fasta formats are accepted!"
sys.exit(1)
|
zennobjects/kivy | kivy/storage/__init__.py | Python | mit | 11,191 | 0.001072 | '''
Storage
=======
.. versionadded:: 1.7.0
.. warning::
This module is still experimental, and the API is subject to change in a
future version.
Usage
-----
The idea behind the Storage module is to be able to load/store keys-value pairs.
The default model is abstract so you cannot use it directly. We prov... | dicate True if the storage has been updated, or False if
nothing has been done (no changes). None if any error.
'''
self._schedule(self.store_delete_async, key=key,
callback=callback)
def find(self, **filters):
'''Return all the entries matching the filters. ... | print('entry:', key, '->', value)
Because it's a generator, you cannot directly use it as a list. You can
do::
# get all the (key, entry) availables
entries = list(store.find(name='Mathieu'))
# get only the entry from (key, entry)
entries... |
jonfoster/pyxb1 | tests/drivers/test-particle.py | Python | apache-2.0 | 4,830 | 0.007453 | import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
schema_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../schemas/particle.xsd'))
code = pyxb.binding.generate.GeneratePython(schema_location=schema_path)
rv = compile(code, 'test', '... | >'
dom = pyxb.utils.domutils.StringToDOM(xml)
# Creating with wrong element
self.assertRaises(pyxb.StructuralBadDocumentError, h01b.createFromDOM, dom.documentElement)
def test_h01_empty (self):
xml = '<ns1:h01 xmlns:ns1="URN:test"/>'
dom = pyxb.utils.domutils.StringToDOM(xm... | instance.elt is None)
self.assertEqual(ToDOM(instance).toxml("utf-8"), xml)
def test_h01_elt (self):
xml = '<ns1:h01 xmlns:ns1="URN:test"><elt/></ns1:h01>'
dom = pyxb.utils.domutils.StringToDOM(xml)
instance = h01.createFromDOM(dom.documentElement)
self.assert_(instance.elt ... |
AlgoLab/PIntron-scripts | Postprocessing/pintron-output-2-json.py | Python | agpl-3.0 | 9,511 | 0.001787 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import contextlib
import gzip
import json
import logging
import re
import sys
@contextlib.contextmanager
def smart_open_out(filename=None):
if filename and filename != '-':
fn = filename
fo = open(filename, 'w')
... | turn {'genome': genomic_block,
'introns': introns,
'alignments': alignments}
def main():
parser = argparse.ArgumentParser(
description="Convert PIntron results to a more convenient JSON format",
formatter_class=argparse.Ar | gumentDefaultsHelpFormatter
)
parser.add_argument(
'-g', '--pintron-genomic-file',
help="File containing the genomic sequence given as input to PIntron",
metavar="FILE",
type=argparse.FileType(mode='r'),
default='genomic.txt')
parser.add_argument(
'-a', '--pin... |
InScience/DAMIS-old | src/damis/migrations/0025_auto__del_field_task_sequence__del_field_task_stderr__del_field_task_s.py | Python | agpl-3.0 | 11,099 | 0.007208 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Task.sequence'
db.delete_column(u'damis_task', 'sequenc... | 'executable_file': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_le | ngth': '100'}),
'icon': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null'... |
SalesforceFoundation/mrbelvedereci | metaci/plan/migrations/0017_merge_20180911_1915.py | Python | bsd-3-clause | 329 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-09-11 19:15
from __ | future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencie | s = [
("plan", "0016_plan_test_dashboard"),
("plan", "0016_auto_20180904_1457"),
]
operations = []
|
iglpdc/dmrg_helpers | setup.py | Python | mit | 912 | 0.048246 | #!/usr/bin/env python
from distutils.core import setup
from version import __version__
setup(name='dmrg_helpers',
version=__version__,
description='Python helpers from our main DMRG code',
long_description=open('README.md').read(),
author='Ivan Gonzalez',
author_email='iglpdc@gmail.com',
url='https:... | ience/Research',
'License :: OSI Approved :: MIT license',
'Natural language :: English',
'Programming Language:: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Physics',
],
# list all subdirectories in next lis | t
packages = ['dmrg_helpers', 'NAME.core',
'dmrg_helpers.utils'],
py_modules = ['version'],
requires = [],
)
|
HalCanary/skia-hc | infra/bots/infra_tests.py | Python | bsd-3-clause | 1,839 | 0.014138 | #!/usr/bin/env python
#
# Copyright 2016 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run all infrastructure-related tests."""
import os
import subprocess
import sys
INFRA_BOTS_DIR = os.pa | th.dirname(os.path.realpath(__file__))
SKIA_DIR = os.path.abspath(os.path.join(INFRA_BOTS_DIR, os.pardir, os.pardir))
def test(cmd, cwd):
try:
subprocess.check_output(cmd, cwd=cwd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
return e.output
def python_unit_tests(train):
if tra... | None
return test(
['python', '-m', 'unittest', 'discover', '-s', '.', '-p', '*_test.py'],
INFRA_BOTS_DIR)
def recipe_test(train):
cmd = [
'python', os.path.join(INFRA_BOTS_DIR, 'recipes.py'), 'test']
if train:
cmd.append('train')
else:
cmd.append('run')
return test(cmd, SKIA_DIR)
... |
victorgama/todo | todo/itemlist.py | Python | mit | 1,776 | 0.007883 | import collections
import sys
from .parser import Parser
from .item import Item
class ItemList(object):
items = []
def __init__(self, path=None):
if path:
self.path = path
self.items = Parser.parse(path)
def append(self, *args):
for item in args:
if i... | te(self, item):
if isinstance(item, collections.Iterab | le):
item = item[1]
self.items.remove(item)
def get(self, index, default=None):
return self.dict.get(index, default)
def get_or_die(self, index):
item = self.get(index)
if not item:
print('[Ops! There is no todo #{}]'.format(index))
sys.exi... |
byakatat/selenium-training | test_login.py | Python | apache-2.0 | 586 | 0.006826 | import pyte | st
from selenium import webdriver
@pytest.fixture
def driver(request):
wd = webdriver.Firefox(capabilities={"marionette": True})
#(desired_capabilities={"chromeOptions": {"args": ["--start-fullscreen"]}})
request.addfinalizer(wd.quit)
return wd
def test_exampl | e(driver):
driver.get("http://localhost/litecart/admin/")
driver.find_element_by_xpath("//input[@name='username']").send_keys("admin")
driver.find_element_by_xpath("//input[@name='password']").send_keys("admin")
driver.find_element_by_xpath("//button[@name='login']").click()
|
trmznt/msaf | msaf/lib/tools/allele.py | Python | lgpl-3.0 | 7,523 | 0.026718 |
from collections import defaultdict
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
from msaf.models import Marker
def summarize_alleles2( analytical_sets, temp_dir = None ):
""" return a tuple of (report, plot)
"""
allele_plots = {}
allele_repor... | se:
delta_status.append( True )
for i in range(1, len(alleles) - 1):
if ( alleles[i][0] - alleles[i-1][0] <= threshold or
| alleles[i+1][0] - alleles[i][0] <= threshold ):
delta_status.append( False )
else:
delta_status.append( True )
if alleles[-2][0] - alleles[-1][0] == 1:
delta_status.append( False )
else:
delta_status.append( True )
return delta_status
def make_allele_plo... |
trabucayre/gnuradio | gr-digital/python/digital/qa_ofdm_chanest_vcvc.py | Python | gpl-3.0 | 13,180 | 0.004325 | #!/usr/bin/env python
# Copyright 2012-2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import sys
import numpy
import random
import numpy
from gnuradio import gr, gr_unittest, blocks, analog, digital
import pmt
def shift_tuple(vec, N):
... | Difference to previous test is, it only uses one synchronisation symbol. """
fft_len = 16
carr_offset = -2
# This will not correct for +2 because it thinks carrier 14 is used
# (because of interpolation)
sync_symbol = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0)
... | et) + \
shift_tuple(data_symbol, carr_offset)
src = blocks.vector_source_c(tx_data, False, fft_len)
# 17 is out of bounds!
chanest = digital.ofdm_chanest_vcvc(sync_symbol, (), 1, 0, 17)
sink = blocks.vector_sink_c(fft_len)
self.tb.connect(src, chanest, sink)
... |
helixyte/tractor | tractor/ticket.py | Python | mit | 15,619 | 0.002945 | """
This file is part of the tractor library.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on Jan 06, 2012.
"""
__docformat__ = 'reStructuredText en'
__all__ = ['create_wrapper_for_ticket_creation',
'create_wrapper_for_ticket_update',
'TicketWrapper'
... | :
"""
Constructor for ticket wrappers. All arguments are optional.
However, if you are going to create a new trac ticket for the trac, you
must at least pass t | he following arguments:
* summary
* description
If you are going to update an existing trac ticket, you have to pass
at least the ticket ID.
:param attribute_names_lookup and attribute_options_lookup:
These lookup serve the association of attribute names wi... |
LRGH/amoco | tests/test_system_structs.py | Python | gpl-2.0 | 3,557 | 0.016025 | import pytest
from amoco.system.structs import *
def test_rawfield():
f = RawField('I',fcount=2,fname='v')
assert f.format()=='2I'
assert f.size()==8
assert f.unpack(b'\0\x01\x02\x03AAAA') == (0x03020100,0x41414141)
def test_varfield():
f = VarField('s',fname='string')
assert f.format()=='#s'
... | dzdfoihzdofh') == b'abcdef\x00'
assert f.size()==7
assert f.format()=='7s'
def test_cntfield():
f = CntField('s','~b',fname='bstr')
assert f.format()=='#s'
assert f.size()==float('Infinity')
assert f.unpack(b'\x04abcdefgh') == b'abcd'
assert f.size()==5
assert f.format()=='b4s'
def tes... | True
assert S.packed == False
assert b.packed == False
assert a.packed == True
a.unpack(b'\x01')
b.unpack(b'\x02')
assert a.v == 1
assert b.v == 2
def test_UnionDefine():
pass
def test_TypeDefine():
@StructDefine("myinteger*1 : z")
class S1(StructFormatter): pass
TypeDefine... |
tylerbutler/engineer | setup.py | Python | mit | 5,374 | 0.002419 | # coding=utf-8
# Bootstrap installation of setuptools
from ez_setup import use_setuptools
use_setuptools()
import os
import sys
from fnmatch import fnmatchcase
from distutils.util import convert_path
from propane_distribution import cmdclassdict
from setuptools import setup, find_packages
from engineer import version... | can append to these | instead
# of replicating them:
standard_exclude = ('*.py', '*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build',
'./dist', 'EGG-INFO', '*.egg-info')
def find_package_data(
where='.', package='',
exclude=standard_exclu... |
googleads/googleads-python-lib | examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py | Python | apache-2.0 | 1,986 | 0.006042 | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. 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 ma | y obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr | iting, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a line item creative association for a creativ... |
yannrouillard/weboob | modules/regionsjob/job.py | Python | agpl-3.0 | 1,035 | 0.001932 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file | is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will... | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses... |
jakobzhao/ashcrawler | core/geo.py | Python | lgpl-3.0 | 5,940 | 0.002416 | # !/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on Oct 16, 2015
# @author: Bo Zhao
# @email: bo_zhao@hks.harvard.edu
# @website: http://yenching.org
# @organization: Harvard Kennedy School
import urllib2
import json
import sys
from settings import BAIDU_AK
from log import *
reload(sys)
sys.s... | if verified_info == u'前' or u'www' in verified_info or u'律师' in verified_info or u'学者' in verified_info or u'作家' in verified_info or u'媒体人' in verified_info or u'诗人' in verified_info:
verified_info = ''
locational_inf | o = verified_info
if locational_info == '':
locational_info = username
if verified_info != '':
latlng = geocode(verified_info)
else:
continue
log(NOTICE, '#%d geocode the user by its semantic info %s. %d posts remain. latlng: %s ' % (i, verified_info.... |
Vagab0nd/SiCKRAGE | lib3/twilio/rest/sync/v1/service/sync_stream/stream_message.py | Python | gpl-3.0 | 5,237 | 0.003246 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page im... | def get_instance(self, payload):
"""
Build an instance of StreamMessageInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance
:rtype: twilio.rest.sync.v1.service.sync_stream.stream_m... | d,
service_sid=self._solution['service_sid'],
stream_sid=self._solution['stream_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Sync.V1.Strea... |
andrewSC/checkthat | checkthat/views.py | Python | mit | 5,807 | 0.000689 | from .models import BuildFailure
# TODO: Make this class and its methods better in general.
class View:
def __init__(self):
self.char_padding_len = 30
def get_build_header(self):
return "{0} Build Results {0}".format('-' * self.char_padding_len)
def get_build_footer(self):
return... | print(footer)
print(self.get_failure_footer())
if has_pkgbuild_analysis:
print(self.get_namcap_pkgbuild_header())
| for build in builds:
msgs = build.namcap_pkgbuild_analysis.msgs
# NOTE: We need to check the list to make sure it has actual
# content and not just the empty string
if any([item for item in msgs if item != '']):
for msg in msgs:
... |
shadowmint/nwidget | lib/cocos2d-0.5.5/cocos/actions/interval_actions.py | Python | apache-2.0 | 22,046 | 0.009027 | # ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2012 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided t... | y
import math
from base_actions im | port *
from cocos.euclid import *
__all__ = [ 'Lerp', # interpolation
'MoveTo','MoveBy', # movement actions
'Jump', 'JumpTo', 'JumpBy',
'Bezier', # complex movement actions
'Rotate',"RotateTo", "Rotat... |
arekfu/project_euler | p0012/p0012.py | Python | mit | 839 | 0.008343 | #!/usr/bin/env python3
import math
from collections import Counter
import operator
import functools
DICT_FACTORS = dict()
def factorize(n) | :
if n in DICT_FACTORS:
return DICT_FACTORS[n]
cnt = Counter()
sqrtn = int(math.sqrt(n)) + 1
for i in range(2, sqrtn + 1):
if n % i == 0:
cnt[i] += 1
cnt += factorize(n // i)
break
else:
cnt[n] += 1
DICT_FACTORS[n] = cnt
return cnt... | ce(operator.mul, (val+1 for val in factors.values()), 1)
return n_div
def triangular_number(n):
return n*(n+1)//2
i=100
while True:
n = triangular_number(i)
n_div = n_divisors(n)
if n_div>500:
print(n)
break
print('{}, {}: {}'.format(n, i, n_div))
i = i + 1
|
devenbansod/SWD-Query | splinter/driver/zopetestbrowser.py | Python | gpl-2.0 | 12,097 | 0.001736 | # -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import re
from lxml.cssselect import CSSSelector
from zope.testbrowser.browser import Browser
from splinter.element_list import Element... |
def _find_links_by_xpath(self, xpath):
html = self.htmltree
links = html.xpath(xpath)
return ElementList([ZopeTestBrowserLinkElement(link, self) for link in links], find_by="xpath", query=xpath)
def select(self, name, value):
self.find_by_name(name).first._control.val | ue = [value]
def is_text_present(self, text, wait_time=None):
wait_time = wait_time or self.wait_time
end_time = time.time() + wait_time
while time.time() < end_time:
if self._is_text_present(text):
return True
return False
def _is_text_present(self... |
google/sample-sql-translator | rfmt/blocks.py | Python | apache-2.0 | 13,911 | 0.006398 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | )
class ChoiceBlock(CompositeLayoutBlock):
"""A block which contains alternate layouts of the same content."""
# Note: All elements of a ChoiceBlock are breaking, if any are.
def __init__(self, elements):
super(ChoiceBlock, self).__init__(elements)
def DoOptLayout(self, rest_of_line):
# The optimum ... | Layout(rest_of_line)
for e in self.elements])
class MultBreakBlock(CompositeLayoutBlock):
"""The abstract superclass of blocks that locally modify line break cost."""
def __init__(self, elements, break_mult=1):
super(MultBreakBlock, self).__init__(elements)
self.break_mult... |
visionegg/visionegg | demo/grating.py | Python | lgpl-2.1 | 1,456 | 0.023352 | #!/usr/bin/env python
"""Sinusoidal grating calculated in realtime."""
############################
# Import various modules #
############################
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation
fr... | port - intermediary between stimuli and screen #
###############################################################
viewport = Viewport( screen=screen, stimuli=[stimulus] )
########################################
# Create presentation | object and go! #
########################################
p = Presentation(go_duration=(5.0,'seconds'),viewports=[viewport])
p.go()
|
Elico-Corp/openerp-7.0 | mrp_mo_nopicking/mrp.py | Python | agpl-3.0 | 4,435 | 0.008345 | # -*- coding: utf-8 -*-
# © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
import time
from datetime import datetime
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATETIME_FOR... | bom_id)
routing_id = bom_point.routing_id.id or False
self.write(cr, uid, [production.id], {'bom_id': b | om_id, 'routing_id': routing_id})
if not bom_id:
continue
# get components and workcenter_lines from BoM structure
factor = uom_obj._compute_qty(cr, uid, production.product_uom.id, production.product_qty, bom_point.product_uom.id)
res = bom_obj._bom_explode(... |
cisco-openstack/tempest | tempest/api/object_storage/test_crossdomain.py | Python | apache-2.0 | 2,264 | 0 | # Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
| # a copy of the License at
#
# http://www.apache.org/licenses/LICENS | E-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the Licen... |
tommy-u/chaco | chaco/tools/tests/better_zoom_test_case.py | Python | bsd-3-clause | 1,537 | 0 | # Copyright (c) 2014, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.ent... | icenses/BSD.txt
# Thanks for using Enthought open source!
#
# Author: Enthought, Inc.
""" Tests for the BetterZoom Chaco tool """
import unittest
import numpy
from chaco.api import create_line_plot
from chaco.tools.api import BetterZoom
from enable.testing import EnableTestAssistant
class TestBetterZoomTool(Enabl... | stant, unittest.TestCase):
""" Tests for the BetterZoom Chaco tool """
def setUp(self):
values = numpy.arange(10)
self.plot = create_line_plot((values, values))
self.plot.bounds = [100, 100]
self.plot._window = self.create_mock_window()
self.tool = BetterZoom(component=s... |
felipeZ/nonAdiabaticCoupling | scripts/hamiltonians/plot_couplings.py | Python | mit | 2,000 | 0 | #! /usr/bin/env python
"""
This programs plots the electronic coupling between two states.
It reads all Ham_*_im files and cache them in a tensor saved on disk.
Usage:
plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0
p = path to the hamiltonian files
s1 = state 1 index
s2 = state 2 index
dt = time step in fs
"""
i... | eading afterwards
np.save('couplings', couplings)
else:
couplings = np.load | ('couplings.npy')
ts = np.arange(couplings.shape[0]) * dt
plt.plot(ts, couplings[:, s1, s2] * r2meV)
plt.xlabel('Time (fs)')
plt.ylabel('Energy (meV)')
plt.show()
def read_cmd_line(parser):
"""
Parse Command line options.
"""
args = parser.parse_args()
attr... |
seanballais/botos | tests/test_admin.py | Python | gpl-3.0 | 95,577 | 0.00135 | # This test is partly based from:
# https://www.argpar.se/posts/programming/testing-django-admin/
from urllib.parse import urljoin
import json
from bs4 import BeautifulSoup
from django import forms
from django.contrib.admin import ACTION_CHECKBOX_NAME
from django.contrib.admin.sites import AdminSite
from django.c... | .login(username='admin', password='root')
# We have to refresh _ba | tch0 since it gets modified in many tests.
# Modifications to an object created inside setUpTestData() in a test
# method will persist across test methods. Fortunately, the changes
# are only present in memory. So, we can just refresh the original
# content of the object from the databas... |
hrautila/go.opt | tests/py/testsdp.py | Python | lgpl-3.0 | 1,573 | 0.019072 | #
# This is copied from CVXOPT examples and modified to be used as test reference
# for corresponding Go program.
#
import sys
from cvxopt import matrix, solvers
import helpers
import localcones
def testsdp(opts):
c = matrix([1.,-1.,1.])
G = [ matrix([[-7., -11., -11., 3.],
[ 7., -18., -... | 16., -10., 3.],
[ -5., 2., -17., 2., -6., 8., -17., -7., 6.]]) ]
h = [ matrix([[33., -9.], [-9., 26.]]) ]
h += [ matrix([[14., 9., 40.], [9., 91., 10.], [40., 10., 15.]]) ]
solvers.options.update(opts)
sol = solvers.sdp(c, Gs=G, hs=h)
#localcones.options.update(... | , Gs=G, hs=h)
print "x = \n", helpers.str2(sol['x'], "%.9f")
print "zs[0] = \n", helpers.str2(sol['zs'][0], "%.9f")
print "zs[1] = \n", helpers.str2(sol['zs'][1], "%.9f")
print "\n *** running GO test ***"
rungo(sol)
def rungo(sol):
helpers.run_go_test("../testsdp", {'x': sol['x'],
... |
szecsi/Gears | GearsPy/Project/Components/Forward/Flyby.py | Python | gpl-2.0 | 2,803 | 0.0264 | import Gears as gears
from .. import *
try:
from OpenGL.GL import *
from OpenGL.GLU import *
except:
print ('ERROR: PyOpenGL not installed properly.')
import random
def box() :
glBegin(GL_QUADS)
glColor3f(0.0,1.0,0.0)
glVertex3f(1.0, 1.0,-1.0)
glVertex3f(-1.0, 1.0,-1.0)
glVertex3f(-1.0, 1.... | .uniform( a = -20, b = 20),
random.uniform( a = -20, b = | 20),
)
box()
glPopMatrix()
glEndList()
def finish( self, event ):
glDeleteLists(self.glist, 1)
def render(self, iFrame):
glEnable(GL_DEPTH_TEST)
glDepthMask(GL_TRUE);
glClearColor(0.0, 0.0, 0.0, 1.0 )
glClear(GL_COLOR_BUF... |
dhuang/incubator-airflow | airflow/executors/dask_executor.py | Python | apache-2.0 | 4,430 | 0.000903 | #
# 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... | to a Dask Distributed cluster.""" |
def __init__(self, cluster_address=None):
super().__init__(parallelism=0)
if cluster_address is None:
cluster_address = conf.get('dask', 'cluster_address')
if not cluster_address:
raise ValueError('Please provide a Dask cluster address in airflow.cfg')
self.... |
Versatilus/dragonfly | dragonfly/examples/test_multiple_dictation.py | Python | lgpl-3.0 | 7,289 | 0.003841 | """
Multiple dictation constructs
===============================================================================
This file is a showcase investigating the use and functionality of multiple
dictation elements within Dragonfly speech recognition grammars.
The first part of this file (i.e. the module's doc string) cont... |
Mixed literal and dictation elements
-------------------------------------------------------------------------------
Here we will investigate mixed, i.e. interspersed, fixed literal command
words and dynamic dictation elements. We will use the "MixedDictationRule"
class which has a spec | of
"mixed [<dictation1>] <dictation2> command <dictation3>".
Note that "<dictation1>" was made optional instead of "<dictation2>"
because otherwise the first dictation elements would always gobble up
all dictated words. There would (by definition) be no way to distinguish
which words correspond with which dictation... |
StephanH84/reinforcement_learning_explorations | tensorflow/src/MNIST1.py | Python | mit | 912 | 0.009868 | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf | .zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
sess.run(tf.global_variables_initializer())
y = tf.matmul(x,W) + b
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entr | opy)
for _ in range(1000):
batch = mnist.train.next_batch(100)
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test... |
cloudrain21/hamsterdb | python/setup.py | Python | apache-2.0 | 505 | 0.007921 |
from distutils.core import setup, Extension
module1=Extension('hamsterdb',
libraries=['hamsterdb'],
include_dirs=['../include'],
li | brary_dirs=['../src/.libs'],
s | ources=['src/python.cc'])
setup(name='hamsterdb-python',
version='2.1.8',
author='Christoph Rupp',
author_email='chris@crupp.de',
url='http://hamsterdb.com',
description='This is the hamsterdb wrapper for Python',
license='Apache Public License 2',
ext_modules=[module1])
|
CopyChat/Plotting | Python/download_era-interim.py | Python | gpl-3.0 | 1,297 | 0.048574 | #!/usr/bin/python
import os
from ecmwfapi import ECMWFDataServer
server = ECMWFDataServer()
time=["06"]
year=["2013"]
param=["129.128","130.128","131.128","132.128","157.128","151.128"]
nam=["hgt","air","uwnd","vwnd","rhum","psl"]
#month=["01","02","03","04","05","06","07","08","09","10","11","12"]
for y in year:
... | : | "an",
'param' : "129.128/130.128/131.128/132.128/157.128",
'param' : param[p],
'area' : "0/0/-40/100", # Four values as North/West/South/East
'grid' : "1.5/1.5", # Two values: West-East/North-South increments
'format' : "netcdf", # if grib, just comment this line
'target' ... |
TonyEight/tundle | tundle/urls.py | Python | mit | 428 | 0.004673 | # coding=utf-8
# This will force all string to be unicode strings, even if we don't
# set the 'u'
from __future_ | _ import unicode_literals
# Django modules imports
from django.conf.urls import patterns, include, | url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Frontend URLs
url(r'^', include('frontend.urls')),
# Admin URLs
url(r'^admin/', include(admin.site.urls)),
)
|
CLVsol/oehealth | oehealth_insured_group/oehealth_insured_group_member.py | Python | agpl-3.0 | 2,443 | 0.010643 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from osv import osv
from osv import fie | lds
class oehealth_insured_group_member(osv.Model):
_name = 'oehealth.insured.group.member'
_columns = {
'insured_group_id': fields.many2one('oehealth.insured.group', string='Insured Group',
help='Insured Group Titular'),
'insured_id': fields.many2one... |
zsuzhengdu/camp | paypal/standard/helpers.py | Python | mit | 2,448 | 0.007761 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
def duplicate_txn_id(ipn_obj):
"""Returns True if a record with this transaction id exists and it is not
a payment which has gone from pending to completed.
"""
query = ipn_obj._default_manager.filter(txn_id = ipn_obj.t... | Build the secret with fields availible in both PaymentForm and the IPN. Orde | r matters.
if secret_fields is None:
secret_fields = ['business', 'item_name']
data = ""
for name in secret_fields:
if hasattr(form_instance, 'cleaned_data'):
if name in form_instance.cleaned_data:
data += unicode(form_instance.cleaned_data[name])
else:
... |
50wu/gpdb | gpMgmt/bin/gpcheckcat_modules/unique_index_violation_check.py | Python | apache-2.0 | 2,547 | 0.002748 | #!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_nam... | olumn_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
... | violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, co... |
Akay7/hospital | appointments/views.py | Python | lgpl-3.0 | 757 | 0.001321 | from django.views import generic
from django.http import JsonResponse
from django.core.urlresolvers import reverse_lazy
from .forms import AppointmentForm
from .models import TimeManager
class AppointmentsFormView(generic.FormView):
| form_class = AppointmentForm
success_url = reverse_lazy('appointments:registration')
template_name = 'appointments/appointments.html'
def form_valid(self, form):
form.save()
return super(AppointmentsFormView, self).form_valid(form)
class GetFreeTimeView(generic.View):
def post(self, r... | ay))
return JsonResponse(answer) |
simondodson/Curator | media_db.py | Python | gpl-3.0 | 935 | 0.041711 | import os
from sqlalchemy import create_engine, ForeignKey, func
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm im | port relationship, backref, sessionmaker
Base = declarative_base()
class Series( Base ):
__tablename__ = 'series'
item = Column( String )
tag = Column( String, primary_key=True )
title = Column( String )
imdb = Column(String)
episodes = relationship( 'Episode', backref='episodes' )
class... | eries = Column( String, ForeignKey( 'series.tag' ) )
season = Column( Integer )
class Movie( Base ):
__tablename__ = 'movie'
id = Column( Integer, primary_key=True )
title = Column( String )
path = Column( String )
imdb = Column( String ) |
olitheolix/qtmacs | qtmacs/miniapplets/base_query.py | Python | gpl-3.0 | 18,531 | 0.000432 | # Copyright 2012, Oliver Nagy <olitheolix@gmail.com>
#
# This file is part of Qtmacs.
#
# Qtmacs 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... | leteInput macro. Therefore, ensure to change the
# name in both locations if so desired.
self.completionsAppID = '__Buffer Completions__'
def qteRun(self):
# Fetch the final user input.
userInput = self.qteWidget.toPlainText()
# If a history list was supplied to ``MiniA | ppletBaseQuery``
# then add the latest entry.
global qteQueryHistory, qteHistIdx
if isinstance(qteQueryHistory, list):
qteQueryHistory.append(userInput)
qteHistIdx = len(qteQueryHistory)
# P |
MooseDojo/apt2 | modules/action/exploit_msf_jboss_maindeployer.py | Python | mit | 4,087 | 0.004894 | import re
from core.actionModule import actionModule
from core.keystore import KeyStore as kb
from core.mymsf import myMsf
from core.utils import Utils
class exploit_msf_jboss_maindeployer(actionModule):
def __init__(self, config, display, lock):
super(exploit_msf_jboss_maindeployer, self).__init__(confi... | for part in parts:
callFire = True
self.addVuln(t, self.shortName, {"port": p, "username": user, "password": password, "output": outfile.replace("/", "%2F")})
kb.add("host/" + t + "/files/" + self.sho... | # clean up after ourselves
result = msf.cleanup()
return
|
AEDA-Solutions/matweb | backend/Controllers/Curriculo.py | Python | mit | 541 | 0.014787 | # coding=utf-8
from Framework.Controller import Controller
from Database.Controllers.Curriculo import Curriculo as BDCurriculo
from Models.Curriculo.RespostaListar import RespostaListar
from Database.Models.Curriculo import Curriculo as ModelCurriculo
class Curriculo(Controller):
def Listar(self,pedido_listar):
re... | so(),str(pedido_listar.getQuantidade()) | ,(str(pedido_listar.getQuantidade()*pedido_listar.getPagina())))))
|
caromedellin/starting_git | test.py | Python | mit | 32 | 0 | print("this is a test file") | ≈
| |
bigdig/vnpy | vnpy/api/oes/__init__.py | Python | mit | 109 | 0.018349 | #from .vnctpm | d import MdApi
from .vnoestd import TdApi
from .vnoesmd import MdApi
from .oe | s_constant import * |
dotKom/onlineweb4 | apps/feedback/__init__.py | Python | mit | 62 | 0 | defa | ult_app_config = 'apps.fee | dback.appconfig.FeedbackConfig'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.