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 |
|---|---|---|---|---|---|---|---|---|
IBMStreams/streamsx.topology | test/python/topology/test_names.py | Python | apache-2.0 | 4,606 | 0.020408 | # Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
import itertools
from streamsx.topology.topology import *
def f42():
pass
class cool_source(object):
def __init__(self):
pass
def __call__(self):
return []
class cool_class(object):
def __init__(self):
... |
self.assertEqual(streamsx.ec.__version__, v)
import streamsx.rest
self.assertEqual(streamsx.rest.__version__, v)
import streamsx.spl.spl
self.assertEqual(streamsx.spl.spl.__version__, v)
import streamsx.spl.op
self.assertEqual(streamsx.spl.op.__version__, v)
... | al(streamsx.topology.context.__version__, v)
import streamsx.topology.schema
self.assertEqual(streamsx.topology.schema.__version__, v)
import streamsx.topology.state
self.assertEqual(streamsx.topology.state.__version__, v)
import streamsx.topology.topology
self.assertEqua... |
Muxi-Studio/muxi_site | basedir.py | Python | mit | 104 | 0 | # codi | ng: utf-8
"""
basedir.py
"""
import os
basedir = os.path.abspath(os.path.dirname(__file__)) | |
daimon99/pyer | my_blog/article/admin.py | Python | gpl-3.0 | 127 | 0 | fr | om django.contrib import admin
from article.models import Article
# Register your models here.
a | dmin.site.register(Article)
|
jlafon/django-rest-framework-oauth | setup.py | Python | mit | 2,889 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from setuptools.command.test import test as TestCommand
import re
import os
import sys
# This command has been borrowed from
# https://github.com/getsentry/sentry/blob/master/setup.py
class PyTest(TestCommand):
def finalize_options(self):... | sopen.com',
packages=get_packages('rest_framework_oauth'),
package_data=get_package_data('rest_framework_oauth'),
cmdclass={'test': PyTest},
install_requires=[
'django-oauth-plus==2.2.4',
'oauth2==1.5.211',
'django-oauth2-provider'
],
classifiers=[
'Developmen... | 'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
]
)
|
AntonioMtn/NZBMegaSearch | miscdefs.py | Python | gpl-2.0 | 12,563 | 0.042426 | # # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## # ## #
#~ This file is part of NZBmegasearch by pillone.
#~
#~ NZBmegasearch 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 ver... | h.username, auth.password,1):
retu | rn self.authenticate()
return f(*args, **kwargs)
else:
return f(*args, **kwargs)
return f(*args, **kwargs)
return decorated
#~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
class DownloadedStats:
#~ megatransfer
def __init__(self):
import urlparse
cfgsets = config_se... |
aitjcize/micropython | tests/basics/class-super.py | Python | mit | 181 | 0.01105 | cl | ass Base:
def meth(self):
print("in Base meth")
class Sub(Base):
def meth(self):
print("in Sub meth")
retur | n super().meth()
a = Sub()
a.meth()
|
trin5tensa/pigjar | pigjar/support.py | Python | gpl-3.0 | 17,792 | 0.002024 | # -*- coding: utf-8 -*-
"""Manage low level support for pigjar.
**Copyright 2014-2018 Stephen Rigden.**
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your op... | h_key: str # 'From' account history key
to_acc_h_key: Optional[str] = None # 'To' account history key if to_pig_acc is an Account
@classmethod
def from_json(cls, **namespace: dict) -> 'RegisterHistoryRecord':
"""Alternative constructor for json loads decoder.
Args:
**namespac... | dict:
"""Create a json serialized string that can recreate self.
Returns:
dict: A dictionary with the keys __class__, __id__, __args__,
and __kw__.
'__class__' is a tag used to identify this class.
'__id__' is used to memoize decoded objects.
... |
martinrotter/textilosaurus | src/libtextosaurus/3rd-party/scintilla/test/win32Tests.py | Python | gpl-3.0 | 5,057 | 0.028487 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Requires Python 2.7 or later
# These are tests that run only on Win32 as they use Win32 SendMessage call
# to send WM_* messages to Scintilla that are not implemented on other platforms.
# These help Scintilla behave like a Win32 text control and can help screen readers... | sertEquals(data.value, t)
def testGetTextShort(self):
self.assertEquals(self.ed.GetStatus(), 0)
self.SetText(b"ab")
data = ctypes.create_unicode_buffer(100)
lenData = self.GetText(2, data)
self.assertEqual | s(self.ed.GetStatus(), 0)
self.assertEquals(lenData, 1)
self.assertEquals(data.value, "a")
def testGetTextJustNUL(self):
self.assertEquals(self.ed.GetStatus(), 0)
self.SetText(b"ab")
data = ctypes.create_unicode_buffer(100)
lenData = self.GetText(1, data)
self.assertEquals(self.ed.GetStatus(), 0)
#~ p... |
paulhayes/fofix | src/Theme.py | Python | gpl-2.0 | 112,732 | 0.022203 | #####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire X (FoFiX) #
# Copyright (C) 2006 Sami Kyöstilä ... | ored hopo_color
self.meshColor = get("mesh_color", "color", "#000000")
self.hopoColor = get("hopo_color", "color", "#00AAAA")
self.spotColor | = get("spot_color", "color", "#FFFFFF")
#keys when they are not textured are made of three parts (Mesh, Key_001, Key_002),
#two of which can be colored by the CustomTheme.py or the Theme.ini (Mesh, Mesh_002).
#These will only work if the object has a Glow_001 mesh in it, else it will render
#the wh... |
abortz/saycbridge | scripts/saycbot.py | Python | bsd-3-clause | 2,638 | 0.000379 | #!/usr/bin/env python
# Copyright (c) 2013 The SAYCBridge 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 logging
import sys
import find_src
from factory import BidderFactory
from core.call import Call, Pass
from core.board imp... | ef main(self, args):
self.configure_logging(True)
args = BidderFactory.configure_from_args(args)
bidder = BidderFactory.default_bidder()
if "-v" in args:
args.remove("-v")
self.verbose = True
if args:
for identifier in args:
s... | bidder)
return 0
try:
while True:
self._bid_board(Board.random(), bidder)
except KeyboardInterrupt:
print
print "User interrupted."
return 0
if __name__ == '__main__':
SAYCBot().main(sys.argv[1:])
|
rootofevil/watercounter | watercounter/db_creater.py | Python | gpl-3.0 | 35 | 0.028571 | from app import db
db.create_al | l() | |
emory-libraries/readux | readux/annotations/__init__.py | Python | apache-2.0 | 157 | 0.012739 | '''
An | implementation of the
`Annotation store API <http://docs.annotatorjs.org/en/v1.2.x/storage.html.>`_
for `Annotator.js <http://annotatorjs.org/>`_.
' | '' |
larsonmpdx/grpc | src/python/grpcio/grpc/framework/core/_interfaces.py | Python | bsd-3-clause | 10,428 | 0.007 | # Copyright 2015, 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... | ""A manager responsible for aborting the | operation if it runs out of time."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def change_timeout(self, timeout):
"""Changes the timeout allotted for the operation.
Operation duration is always measure from the beginning of the operation;
calling this method changes the operation's allotted t... |
juancarlospaco/python-course | 6/advanced_types.py | Python | lgpl-3.0 | 273 | 0.003663 |
di | ctionary = {key: value for key, value in zip(range(0, 9), "find the bug")}
assert len(dictionary) == 12
dictionario = {"a": 0, "b": 1, "c": 2}
assert dictionario.has("b")
string_original = "abcdefg"
string_modified = "".join([ ])
assert string_modified == "aBcDeFg | "
|
hperala/kontuwikibot | pywikibot/__init__.py | Python | mit | 26,829 | 0.000336 | # -*- coding: utf-8 -*-
"""The initialization file for the Pywikibot framework."""
#
# (C) Pywikibot team, 2008-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__release__ = '2.0rc4'
__version__ = '$Id: e26392a530582f286edf2d99e729218b2e93405e $'
import datetime
imp... | eNotSaved, OtherPageSaveError,
LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
EditConflict, PageDeletedConflict, PageCreatedConflict,
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect, InterwikiRedirectPage,
WikiBaseError, CoordinateGlobeUnkn... | r
import pywikibot.textlib as textlib
import pywikibot.tools
textlib_methods = (
'unescape', 'replaceExcept', 'removeDisabledParts', 'removeHTMLParts',
'isDisabled', 'interwikiFormat', 'interwikiSort',
'getLanguageLinks', 'replaceLanguageLinks',
'removeLanguageLinks', 'removeLanguageLinksAndSeparator',... |
assisi/assisipy-examples | bees_in_casu_array/spawn_bees_in_casu_array.py | Python | lgpl-3.0 | 1,170 | 0.008547 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simulated world featuring 36 Casus and 36 bees.
"""
from assisipy import sim
from math import pi, sin, cos
from random import random
import threading
if __name__ == '__main__':
simctrl = sim.Control()
# Parameters of the CASU array.
casu_rows = 6
... | casu_dist = 8
num_bees = 36
radius = 40 # Arena radius
# Spawn the Casus and run their controllers
casus = []
x = range(-int(casu_dist*casu_cols/2), int(casu_dist*(casu_cols+1)/2), casu_dist)
y = range(-int(casu_dist*casu_rows/2), int(casu_dist*(casu_rows+1)/2), casu_dist)
for i in ra... | # Spawn the bees at randomly generated poses and let them run :)
bees = []
for i in range(1,num_bees+1):
d = 0.9*radius*random()
a = 2*pi*random()
if i < 10:
simctrl.spawn('Bee', 'Bee-00{0}'.format(i), (d*cos(a), d*sin(a), a))
else:
simctrl.spawn('Bee',... |
galaxyfeeder/CodeSubmission | main/models.py | Python | mit | 1,166 | 0.007719 | """
Copyright (c) 2016 Gabriel Esteban
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute... | TWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import unicode_literals
from dja | ngo.db import models
# Create your models here.
|
alxgu/ansible | lib/ansible/modules/cloud/memset/memset_dns_reload.py | Python | gpl-3.0 | 5,850 | 0.003077 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Simon Weald <ansible@simonweald.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | completed, then I(job.status) is also required.
description:
- Request a reload of Memset's DNS infrastructure, and optionally poll until it finishes.
options:
api_key:
required: true
description:
- The API key obtained from the Memset control panel.
poll:
default: fa... | bool
description:
- Boolean value, if set will poll the reload job's status and return
when the job has completed (unless the 30 second timeout is reached first).
If the timeout is reached then the task will not be marked as failed, but
stderr will indicate ... |
au9ustine/org.au9ustine.puzzles.pythonchallenge | pc/level_03.py | Python | mit | 1,436 | 0.000696 | import unittest
import requests
import logging
import re
import string
# Default is warning, it's to suppress requests INFO log
logging.basicConfig(format='%(message)s')
def solution(data):
pattern = r'[^A-Z][A-Z]{3}[a-z][A-Z]{3}[^A-Z]'
return ''.join(x[4] for x in re.findall(pattern, data))
class Solutio... | self.prefix = "http://www.pythonchallenge.com/pc/def/"
self.suffix = ".html"
self.src_url = "http://www.pythonchallenge.com/pc/def/equality.html"
def test_solution(self):
r = requests.get(self.src | _url)
actual = solution(''.join(re.findall('<!--[^>]*-->', r.text)))
expected = 'linkedlist'
self.assertEquals(actual, expected)
r.close()
origin_url = ''.join([self.prefix, actual, self.suffix])
try:
r = requests.get(origin_url)
except:
ra... |
spadae22/odoo | addons/website/__openerp__.py | Python | agpl-3.0 | 857 | 0 | {
'name': 'Website Builder',
'category': 'Website',
'summary': 'Build Your Enterprise Website',
'website': 'https://www.odoo.com/page/website-builder',
'version': '1.0',
'description': """
OpenERP W | ebsite CMS
===================
""",
'author': 'OpenERP SA',
'depends': ['web', 'share', 'mail', 'portal'],
'installable': True,
'data': [
'data/data.xml',
'security/ir.model.access.csv',
'security/ir_ui_view.xml',
'views/website_templates.xml',
'views/web... | s.xml',
'views/themes.xml',
'views/res_config.xml',
'views/ir_actions.xml',
'views/website_backend_navbar.xml',
],
'demo': [
'data/demo.xml',
],
'qweb': ['static/src/xml/website.backend.xml'],
'application': True,
}
|
c17r/TagTrain | src/tagtrain/reddit/__init__.py | Python | mit | 4,844 | 0.000826 | import datetime
import logging
import time
import traceback
import praw
import prawcore
_logger = logging.getLogger('reddit')
def _preface_each_line(text, preface):
lines = text.split('\n')
lines = [preface + line for line in lines]
return '\n'.join(lines)
class Reply(object):
body = None
child... | ocess_func):
self.config = config
self.p | rocess_func = process_func
def _create_reddit(self):
_logger.debug('Creating reddit object...')
self.reddit = praw.Reddit(**self.config['reddit'])
def _get_data(self):
_logger.debug('_get_data...')
while True:
try:
yield from self._get_data_backlog()... |
hobson/pug-dj | pug/dj/miner/tests.py | Python | mit | 3,596 | 0.002781 | # import time
# import unittest
import doctest
from django.test import LiveServerTestCase #, TestCase
from selenium import webdriver
import pug.nlp.util
# from pug.dj import db as djdb
# from traceback import print_exc
class HomeTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox... | o (but test statistics don't)
# # HTML page with more than 1 SVG element and more than 100 bytes for the first 2 p | lots
# plots = self.browser.find_elements_by_tag_name('svg')
# try:
# self.assertGreater(len(plots), 1)
# except:
# print_exc()
# time.sleep(3600*48)
# # line chart with at least some text
# self.assertGreater(len(plots[0].text), 50)
... |
TRDDC-TUM/wcet-benchmarks | scripts/find_wcet.py | Python | mit | 38,915 | 0.003983 | #!/usr/bin/python
# This script uses cbmc to find a WCET value of an timing-annotated C source.
# it keeps running cbmc until either the user aborts or the WCET cannot be
# tightened anymore.
#
# Major Version: 3
# - proper XML parsing
# - collection of all counterexamples
# Last update:
# - 2018/Feb/16: allow mult... | # Read environment variables
if 'CBMC' in os.environ:
CBMC = os.environ['CBMC']
else:
CBMC = "cbmc"
if 'CBMCFLAGS' in os.environ:
CBMCFLAGS = os.environ['CBMCFLAGS']
else:
CBMCFLAGS = "--all-properties --slice-formula"
if 'GOTOCC' in os.environ:
GOTOCC = os.environ['GOTOCC']
else:
GOTOCC = "goto... | S = os.environ['GOTOINS']
else:
GOTOINS = "goto-instrument"
if 'GOTOINSFLAGS' in os.environ:
GOTOINSFLAGS = os.environ['GOTOINSFLAGS']
else:
GOTOINSFLAGS = ""
if 'CBMCOUTPUT' in os.environ: # relative to source file
CBMCOUTPUT_REL = os.environ['CBMCOUTPUT'].strip()
else:
CBMCOUTPUT_REL = os.getcwd(... |
jswetzen/sie-parse | gui.py | Python | gpl-3.0 | 12,714 | 0.002678 | #!/usr/bin/python3
import sys
import platform
import ctypes
from pathlib import Path
from itertools import count
import difflib
import PySide
from PySide.QtCore import *
from PySide import QtGui
from PySide.QtGui import *
from sie_parse import SieParser
from accounting_data import SieIO
from petra_output import PetraO... | tton)
vismaPetraBox.addWidget(QtGui.QLabel("=>"))
vismaPetraBox.addWidget(self.diffButton)
vismaPetraBox.addStretch(0)
petraVismaBox = QtGui.QHBoxLayout()
petraVismaBox.addWidget( | self.readPetraButton)
petraVismaBox.addWidget(QtGui.QLabel("=>"))
petraVismaBox.addWidget(self.writeVismaButton)
petraVismaBox.addStretch(0)
mainBox = QtGui.QVBoxLayout()
mainBox.addWidget(QtGui.QLabel("Visma till Petra"))
mainBox.addLayout(vismaPetraBox)
mainBox... |
Lipen/LipenDev | Azeroth/Northrend/TP Olymp/TaskB.py | Python | gpl-3.0 | 526 | 0.051331 | def solve(s):
if len(s) != 80:
return '0'*80
elif s.startswith('1111') and not s.endswith('1111'):
return s
elif s.endswith('1111') and not s.s | tartswith('11 | 11'):
return s[::-1]
else:
return '0'*80
def main():
##
with open('input.txt', 'r') as f:
data = f.read().splitlines()
s = data[0]
##
# s = input()
ans = solve(s)
# print(ans)
##
ans = str(ans)
with open('output.txt', 'w') as f:
f.write(ans)
print('Done:')
if len(ans) > 500:
print(ans[:200... |
NicovincX2/Python-3.5 | Analyse (mathématiques)/Analyse fonctionnelle/Équation différentielle/euler.py | Python | gpl-3.0 | 468 | 0.002137 | # -*- c | oding: utf-8 -*-
import os
from pygal import *
def listeEuler(f, x0, y0, pas, n):
x, y, L = x0, y0, []
for k in range(n):
L += [(x, y)]
x += pas
y += pas * f(x, y)
return L
def euler(f, x0, y0, xf, n):
pas = (xf - x0) / n
courbe = XY()
courbe.title = "Methode d Euler... | der_to_file("courbeEulerPython.svg")
os.system("pause")
|
akaariai/drf-fast-serializer | benchmark/tester/migrations/0002_mysimplemodel.py | Python | mit | 651 | 0.001536 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tester', '0001_initial'),
]
operations = [
migrations.CreateModel(
name | ='MySimpleModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('f1', models.CharField(max_length=20)),
('f2', models.CharField(max_length=20)),
],
opt | ions={
},
bases=(models.Model,),
),
]
|
Dallinger/Dallinger | dallinger/command_line/config.py | Python | mit | 1,173 | 0 | """This module includes utilities to store and retrieve dallinger
configuration for the command line in the current user directory.
"""
from pathlib import Path
from typing import Dict
import json
from dallinger.command_line import appdirs
APPDIRS = appdirs.AppDirs("dallinger", "dallinger")
def get_configured_host... | data_dir) / "hosts"
if not hosts_dir.is_dir():
hosts_dir.mkdir(parents=True)
(hosts_dir / host["host"]).write_text(json.dumps(host))
d | ef remove_host(hostname: str):
host_path = Path(APPDIRS.user_data_dir) / "hosts" / hostname
if host_path.exists():
host_path.unlink()
else:
print(f"Host {hostname} not found")
|
davy39/eric | eric6_doc.py | Python | gpl-3.0 | 15,567 | 0.00167 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2003 - 2014 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Eric6 Documentation Generator.
This is the main Python script of the documentation generator. It is
this script that gets called via the source documentation interface.
This script can be used... | de empty modules.")
print(" --eol=eol-type")
| print(" Use the given eol type to terminate lines.")
print(" Valid values are 'cr', 'lf' and 'crlf'.")
print(" --exclude-file=pattern")
print(" Specify a filename pattern of files to be excluded.")
print(" This option may be repeated multiple times.")
print(" -h or --he... |
hmcmooc/ec2-edx-configuration | playbooks/edx-east/lifecycle_inventory.py | Python | agpl-3.0 | 2,195 | 0.004556 | #!/usr/bin/env python
"""
Build an ansible inventory based on autoscaling group instance lifecycle state.
Outputs JSON to stdout with keys for each state and combination of autoscaling
group and state.
{
"InService": [
"10.0.47.127",
"10.0.46.174"
],
"Terminating:Wait": [
"10.0.48.104"
],
"e-d-... | e(":","_")].append(private_ip_address)
print json.dumps(inventory, sort_keys=True, indent=2)
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--profile', help='The aws profile to use when connect | ing.')
parser.add_argument('-l', '--list', help='Ansible passes this, we ignore it.', action='store_true', default=True)
args = parser.parse_args()
LifecycleInventory(args.profile).run()
|
fluffels/ytlist | ytlist/ytlist/tests.py | Python | mit | 2,148 | 0.000931 | import json
from django.http import HttpRequest
from django.http import HttpResponseForbidden
from django.test import TestCase
from django.test import Client
from .models import Video
from .views import VideoAPIView
class VideoAPITestCase(TestCase):
def setUp(self):
self.client = Client()
v = Vi... | n.loads(response.content)
self.assertEqual(message['status'], 1)
def test_parse_error(self):
response = self.client.post('/videos/', {'data': '{"test"}'})
message = json.loads(response.content)
self.assertEqual(message['status'], 2)
def test_no_url(self):
response = sel... | 3)
def test_get(self):
response = self.client.get('/videos/')
self.assertEqual(response.status_code, 200)
def test_delete(self):
v2 = Video()
v2.url = "delete"
v2.save()
response = self.client.delete('/videos/{}/'.format(v2.id))
message = json.loads(re... |
thanhtien522/nova-docker | novadocker/virt/docker/opencontrail.py | Python | apache-2.0 | 4,378 | 0 | # Copyright (C) 2014 Juniper Networks, 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... | ersion'] == 4):
if ips['address'] is not None:
ipv4_address = ips['address']
if (ips['version'] == 6):
if ips['address'] is not None:
ipv6_address = ips['address']
params = {
'ip_address': ipv4_ad... | tname': instance['hostname'],
'host': instance['host'],
'vm_project_id': instance['project_id'],
'port_type': 'NovaVMPort',
'ip6_address': ipv6_address,
}
try:
utils.execute('ip', 'link', 'set', if_remote_name, 'netns',
... |
iohannez/gnuradio | gr-blocks/python/blocks/qa_unpack_k_bits.py | Python | gpl-3.0 | 1,845 | 0.016802 | #!/usr/bin/env python
#
# Copyright 200 | 6,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any lat | er version.
#
# GNU Radio 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.
#
# You should have received a copy of the GNU General Public Licen... |
openrural/open-data-nc | opendata/settings/base.py | Python | mit | 7,040 | 0.00142 | # Django settings for opendata project.
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
from django.core.urlresolvers import reverse_lazy
PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PROJECT_ROOT = os.path.abspath(os.path.join(PROJECT_PATH, os.pardir... | e, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
US... | .com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public', 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be co... |
Pakoach/Sick-Beard-Animes | sickbeard/tvcache.py | Python | gpl-3.0 | 10,306 | 0.002814 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 Lice... | oviderName):
db.DBConnection.__init__(self, "cache.db")
# Create the table if it's not already there
try:
sql = "CREATE TABLE "+providerName+" (name TEXT, season NUMERIC, episodes TEXT, tvrid NUMERIC, tvdbid NUMERIC, url TEXT, time NUMERIC, quality TEXT, release_group TEXT, proper N... | commit()
except sqlite3.OperationalError, e:
if str(e) != "table "+providerName+" already exists":
raise
# Create the table if it's not already there
try:
sql = "CREATE TABLE lastUpdate (provider TEXT, time NUMERIC);"
self.connection.execute(s... |
pavel-odintsov/ru_open_statistics | helpers/utils.py | Python | gpl-2.0 | 3,681 | 0.006127 | # -*- coding: utf-8 -*-
# Служебная библиотека
from datetime import datetime
from config.eq_domain import eq_domains |
import re
from dns.resolver i | mport NXDOMAIN, NoAnswer, Timeout, NoNameservers
def convert_string_to_date(date):
"""
Дату в строчном представлении конвертируем в объект 01.02.2009
:type date: unicode
:rtype: datetime
"""
format = "%d.%m.%Y"
return datetime.strptime(date, format)
def load_domains_file_to_memory(file_nam... |
Csega/PythonCAD3 | Interface/Preview/polygon.py | Python | gpl-2.0 | 3,133 | 0.014044 | #!/usr/bin/env python
#
# Copyright (c) 2010 Matteo Boscolo
#
# This file is part of PythonCAD.
#
# PythonCAD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your opti... | super(QtPolygonItem, self).__init__(command)
self.command=command
# get the geometry
@property
def polygonPoint(self):
"""
get the poligon points
"""
if self.side<=0:
self.side=6
deltaAngle=(math.pi*2)/self.side
cPoint=Point... | .norm
angle=vertexVector.absAng
pol=QtGui.QPolygonF()
pFirst=None
for i in range(0, int(self.side)):
angle=deltaAngle+angle
xsP=cPoint.x+radius*math.cos(angle)*-1.0
ysP=cPoint.y+radius*math.sin(angle)*-1.0
p=QtCore.QPointF(xsP,ysP)
... |
lukas-hetzenecker/home-assistant | homeassistant/components/homeassistant/scene.py | Python | apache-2.0 | 9,460 | 0.001268 | """Allow users to set and activate scenes."""
from __future__ import annotations
import logging
from typing import Any, NamedTuple
import voluptuous as vol
from homeassistant import config as conf_util
from homeassistant.components.light import ATTR_TRANSITION
from homeassistant.components.scene import DOMAIN as SCE... | d)
if isinstance(info, dict):
entity_attrs = info.copy()
state = entity_attrs.pop(ATTR_STATE, None)
attributes = entity_attrs
else:
state = info
attributes = {}
# YAML translates 'on' to a boolean
# http://yaml.or | g/type/bool.html
if isinstance(state, bool):
state = STATE_ON if state else STATE_OFF
elif not isinstance(state, str):
raise vol.Invalid(f"State for {entity_id} should be a string")
result[entity_id] = State(entity_id, state, attributes)
return result
def _ensure_... |
YiqunPeng/Leetcode-pyq | solutions/208ImplementTrie.py | Python | gpl-3.0 | 1,935 | 0.005685 | class TrieNode:
def __init__(self, val):
self.val = val
self.children = [None] * 26
self.is_word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode('')
def insert(self, word):
... |
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
cur_node = self.root
for c in word:
pos = ord(c) - ord('a')
| if cur_node.children[pos]:
cur_node = cur_node.children[pos]
continue
else:
return False
if not cur_node.is_word:
return False
else:
return True
def startsWith(self, prefix):
"""
Returns ... |
Azure/azure-sdk-for-python | sdk/timeseriesinsights/azure-mgmt-timeseriesinsights/azure/mgmt/timeseriesinsights/aio/__init__.py | Python | mit | 574 | 0.003484 | # coding=utf-8
# --------------------------------------------------------------------------
# C | opyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# -----------------------... | client import TimeSeriesInsightsClient
__all__ = ['TimeSeriesInsightsClient']
|
narrowcast/facebook-ads-api | setup.py | Python | mit | 720 | 0.001389 | import subprocess
import sys
from distutils.core import setup, Command
class TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, 'test_facebook.py'])
raise... | ,
author_email='yoonchee@gmail.com',
py_modules=['facebook', ],
url='http://github.com/narrowcast/faceboo | k-ads-api',
license='LICENSE',
description='Python client for the Facebook Ads API',
long_description=open('README.md').read(),
cmdclass={'test': TestCommand},
)
|
Kianoosh76/fop-project | phase1/apps.py | Python | mit | 87 | 0 | from django.apps import AppConfig
class Phase1Config(AppConfig | ):
name = 'phas | e1'
|
rsj217/dmblog | dmblog/utils/paginatorer.py | Python | mit | 1,092 | 0.000916 | # -*- coding: utf-8 -*-
from djang | o.core.paginator import Paginator, InvalidPage
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseServerError, Http404
def paginat | or_parse(request, obj, item_per_page=1):
paginator = Paginator(obj, item_per_page)
try:
page_number = int(request.GET['page'])
except (KeyError, ValueError):
page_number = 1
try:
current_page = paginator.page(page_number)
except InvalidPage:
raise Http404
curr... |
benlk/harvey-senior-homes | helpers.py | Python | mit | 3,147 | 0.010168 | # Helper functions for the Maine Legislature project
import app_config
import collections
import copytext
import re
import json
import numbers
from unicodedata import normalize
from operator import itemgetter
CACHE = {}
def get_copy():
"""
Thank you Ryan for this neat trick to avoid thrashing the disk
ht... | s will sort, but we shall see
"""
locations_statuses = get_locations_statuses()
history = []
for row in locations_statuses:
if row['id'] == slug:
history.append( row )
if len( history ) > 1 :
history = sorted( history, key=itemgetter( 'date', 'time' ), reverse=T... | istory
def get_location_status_by_slug(slug):
history = get_location_history_by_slug(slug)
try:
return history[0]
except IndexError:
return {}
def get_location_status_color_by_slug(slug):
status = get_location_status_by_slug(slug)
try:
if status['color'] not in {'red', 'yel... |
google-research/proteinfer | protein_dataset_test.py | Python | apache-2.0 | 6,527 | 0.004137 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ]
expected_sequence_one_hot = _nump | y_one_hot(
expected_sequence_indexes, depth=len(utils.AMINO_ACID_VOCABULARY))
# Because the label vocab is exactly the labels in the first example, we
# just get range(len(label_vocab_array))
expected_label_indexes = range(len(label_vocab_array))
expected_id = b'P0CB34'
# Assert values corr... |
msullivan/advent-of-code | 2018/19b.py | Python | mit | 724 | 0.008287 | from functools import reduce
from itertools import chain, combinations
import operator
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2, | ) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(i | terable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
# N = 996
N = 10685796
def brute(N):
x = 0
for i in range(1,N+1):
for j in range(1,N+1):
if i*j == N:
x += i
return x
def factors(facs):
x = 0
for thing in set(powerset(facs))... |
livni/old-OK | src/knesset/laws/migrations/0013_add_law_merged_into.py | Python | bsd-3-clause | 20,248 | 0.007458 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Law.merged_into'
db.add_column('laws_law', 'merged_into', self.gf('django.db.models.fields... | True'}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'committees'", 'symmetrical': 'False', 'to': "orm['mks.Member']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '256'})
},
'committees.committeemeeting': {
... | ', [], {'to': "orm['committees.Committee']"}),
'date': ('django.db.models.fields.DateField', [], {}),
'date_string': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mks_attended':... |
LiuRoy/dracula | dracula/ev.py | Python | apache-2.0 | 4,857 | 0.000211 | # -*- coding=utf8 -*-
"""libev接收请求"""
import errno
import signal
import socket
import logging
import pyev
from .const import (
READ_BUFFER_SIZE,
ReadState,
)
from .thrift import (
TError,
Decoder,
Encoder,
TMessageType,
)
logging.basicConfig(level=logging.ERROR)
# python的垃圾回收机制可能会把socket都回收掉,... | ad_state = None
self.encoder = None
self.address = address
def server_run(sock, service, handler):
"""运行thrift server"""
thread_info = ThreadInfo(sock, service, handler)
main_loop = pyev.Loop(0, data=thread_info)
io_watcher = pyev.Io(sock, pyev.EV_READ, main_loop, on_request)
io_w... | GINT, main_loop, on_stop, priority=5)
stop_watcher.start()
main_loop.start()
def on_request(watcher, revents):
thread_data = watcher.loop.data
sock = thread_data.sock
try:
client_socket, address = sock.accept()
logging.info("accept address: {}".format(address))
except socket.e... |
jaredwo/topowx | scripts/step05_calc_obs_cnts.py | Python | gpl-3.0 | 1,001 | 0.011988 | '''
Script to add period-of-record daily observations counts to the station
observation netCDF file.
'''
import os
from twx.utils import TwxConfig, ymdL
from twx.db import add_obs_cnt
if __name__ == '__main__':
twx_cfg = TwxConfig(os.getenv('TOPOWX_INI'))
for elem | in twx_cfg.obs_main_elems:
print ("Adding monthly observation counts for %s from %d to %d... " %
(elem, ymdL(twx_cfg.obs_start_date), ymdL(twx_cfg.obs_end_date)))
add_obs_cnt(twx_cfg.fpath_stndata_nc_all, elem,
twx_cfg.obs_start_date, twx_cfg.obs_end_da... | print ("Adding monthly observation counts for %s from %d to %d... " %
(elem, ymdL(twx_cfg.interp_start_date), ymdL(twx_cfg.interp_end_date)))
add_obs_cnt(twx_cfg.fpath_stndata_nc_all, elem,
twx_cfg.interp_start_date, twx_cfg.interp_end_date,
... |
shearern/pak | src/paklib/cmds/install_cmd.py | Python | gpl-3.0 | 1,786 | 0.006159 | import os
import gflags
from textwrap import dedent
import hashlib
import zipfile
from ..exceptions import UsageError
from ..Bunch import Bunch
from ..TreeScanner import TreeScanner
from ..PakManifest import PakManifest, PakFile, PakFolder
def help():
return dedent("""\
Command Usage: pak install | pkg_name-1.0.pak /target/path
""")
def run(args):
if len(args) != 2:
raise UsageError("Got %d arguments, but I only expected 2 (%s)" % (len(args), ' '.join(args)))
else:
pak_path, target_path = args
# Validate target_path path
target_path = os.path.abspath(target_path)
if... | th)
if not os.path.isdir(target_path):
raise UsageError("Target path isn't a directory: " + target_path)
# Examine pak path
pak_path = os.path.abspath(pak_path)
if not os.path.exists(pak_path):
raise UsageError("Package doesn't exist: " + pak_path)
if not os.path.isfile(pak_path):
... |
ibackus/testdust | testdust/settling/ppdgrid.py | Python | mit | 5,659 | 0.007775 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:17:42 2016
@author: ibackus
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
def _hexline(nx, firstSpacing=1):
"""
"""
x = np.zeros(nx)
nx0 = int((nx + 1)/2)
nx1 = nx - nx0
x0 = 3 * np.arang... | he lattice sites, shape (nx x ny)
"""
xeven = _hexline(nx, firstSpacing=2)
xodd = _hexl | ine(nx, firstSpacing=1)
xshift = np.zeros(ny)
xshift[1::2] = 0.5
y = (np.sqrt(3)/2.) * np.arange(ny, dtype=float)
xmat = np.ones([nx, ny])
ymat = np.dot(np.ones([nx, 1]), y[None, :])
for i in range(0, ny, 2):
# Even loop
xmat[:,i] = xshift[i] + xeven
f... |
basicScandal/jackyrelay | conf/main-dist.py | Python | gpl-2.0 | 1,648 | 0.018204 | ########
# CONF #
########
DEBUG = False
## put to True if you want to activate ACLs
#useacl = True
useacl = False # /!\ OPEN RELAY /!\
## You can add ips to restrict access
## a dict with 'ip' : max_connections_per_ip
ACL = {}
# ACL = {'129.43.24.87' : 20,
# '24.56.12.190' : 1,
# '42.53.94.24': 10}
#ACL = {... | m nntp authentification
## uses it to check user rights
## and replaces it by other login/pass before forwarding.
import nntp_auth_rewrite_plugin as nntp_auth_rewrite
### This one compresses and uncompresses in bzip2
import bzip2_compressor_plugin as bzip2_compressor
import bzip2_decompressor_plugin as bzip2_decomp | ressor
## ORDER IS IMPORTANT
activeplugins = [] # None activated
#activeplugins = [ bzip2_decompressor, nntp_auth_rewrite, simple_logger , bzip2_compressor ]
#activeplugins = [ nntp_auth_rewrite , bzip2_compressor ]
#activeplugins = [ bzip2_decompressor, nntp_auth_rewrite ]
|
zstackio/zstack-woodpecker | integrationtest/vm/multihosts/preallocation_resize_vm_volume.py | Python | apache-2.0 | 2,917 | 0.00857 | import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.account_operations as acc_ops
import apibinding.api_actions as api_actions
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.resource_operations as res_op... | ize = volume.volume.size
vm_create_option = test_util.Vm | Option()
vm = test_lib.lib_create_vm(vm_create_option)
test_obj_dict.add_vm(vm)
rootvol_size = test_lib.lib_get_root_volume(vm.get_vm()).size
rootvolume_uuid = test_lib.lib_get_root_volume(vm.get_vm()).uuid
volume.attach(vm)
size = random.randrange(rootvol_size,... |
googleinterns/stampify | extraction/content_extractors/embedded_tweet_extractor.py | Python | apache-2.0 | 946 | 0 | """This script checks whether DOM has embedded tweet tag or not and
creates and returns the ETweet object"""
import bs4
from data_models.embedded_tweet import ETweet
from extraction.content_extractors.interface_content_extractor import \
IContentExtractor
class ETweetExtractor(IContentExtractor):
"""This cl... | return ETweet(tweet_id)
return | None
|
adazey/Muzez | libs/pafy/backend_youtube_dl.py | Python | gpl-3.0 | 4,573 | 0.000437 | import sys
import time
import logging
if sys.version_info[:2] >= (3, 0):
# pylint: disable=E0611,F0401,I0011
uni = str
else:
uni = unicode
import youtube_dl
from . import g
from .backend_shared import BasePafy, BaseStream, remux
dbg = logging.debug
early_py_version = sys.version_info... | self._mediatype = 'normal'
self._threed = info.get('format_note') == '3D'
self._rawbitrate = info.get('abr', 0) * 1024
height = info.get('height') or 0
width = info.get('width') or 0
self._resolu | tion = str(width) + 'x' + str(height)
self._dimensions = width, height
self._bitrate = str(info.get('abr', 0)) + 'k'
self._quality = self._bitrate if self._mediatype == 'audio' else self._resolution
self._extension = info['ext']
self._notes = info.get('format_note') or ''
... |
klusta-team/kwiklib | patches/add_start_time.py | Python | bsd-3-clause | 1,769 | 0.005653 | """
This script fixes data files that were recorded with a version of spikedetekt2
that contained a minor bug. This bug prevented the program to save the start time
of each recording. As a result, KlustaViewa was not able to display correlograms
because the spike times were not sorted (the spike times were in local tim... | ges, spkrec = changes[chgroup]
i = np.nonzero(spkrec == recidx)[0]
if i.size == 0:
continue
spkidx = mychanges[i][0]
t = max(t, exp.channel_groups[chgroup].spikes.time_samples[spkidx])
# t is now the la | rgest spike time in that recording (local frame)
last_t += int(t + (10 * sr))
exp.close()
print "Done!" |
ahmadassaf/zulip | zerver/decorator.py | Python | apache-2.0 | 27,850 | 0.00395 | from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.csrf import csrf_exempt
from django.http import QueryDict, HttpResponseNotAllowed, HttpRe... | n wrapper # type: ignore # https://github.com/python/mypy/issues/1927
from zerver.lib.user_agent import parse_user_agent
def get_client_name(request, is_json_view):
# type: (HttpRequest, bool) -> text_type
# If the API request specified a client in the request content,
# that has priority. Otherwise, ext... | TTP_USER_AGENT" in request.META:
user_agent = parse_user_agent(request.META["HTTP_USER_AGENT"])
# We could check for a browser's name being "Mozilla", but
# e.g. Opera and MobileSafari don't set that, and it seems
# more robust to just key off whether it was a json view
if user_a... |
ferb96/burogu | runp.py | Python | mit | 107 | 0.009346 | #!flask/bin/python3
from app import app
if __name__ == "__main__":
app.r | un(debug=False | ,host='0.0.0.0')
|
mukund-kri/django-and-ember | ember/wsgi.py | Python | unlicense | 1,416 | 0.000706 | """
WSGI config for ember project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``ru | nserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could ... | the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "ember.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ember.settings")
# This application ... |
dreibh/planetlab-lxc-plcapi | PLC/Methods/GetAddressTypes.py | Python | bsd-3-clause | 1,109 | 0.007214 | from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Filter import Filter
from PLC.AddressTypes import AddressType, AddressTypes
from PLC.Auth import Auth
class GetAddressTypes(Method):
"""
Returns an array of structs containing detail | s about address
types. If address_type_filter is specified and is an array of
address type identifiers, or a struct of address type attributes,
only address types matching the filter will be returned. If
return_fields is specified, only | the specified details will be
returned.
"""
roles = ['admin', 'pi', 'user', 'tech', 'node']
accepts = [
Auth(),
Mixed([Mixed(AddressType.fields['address_type_id'],
AddressType.fields['name'])],
Filter(AddressType.fields)),
Parameter([str], "Li... |
joshuamsmith/ConnectPyse | sales/order.py | Python | mit | 1,974 | 0 | from ..cw_model import CWModel
class Order(CWModel):
def __init__(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String... | None # (OpportunityReference)
self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
self.poNumber = None # (String(50))
self.locationId = None # (Integer)
... | ence)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (Boolean)
self.restrictDownpaymentFlag = None # (Boolean)
self.description = None # (String)
self.topCommentFlag = None # (Boolean)
self.bottomComm... |
warpri81/pyXlsxTemplate | sphinx/conf.py | Python | bsd-2-clause | 8,021 | 0.007356 | # -*- coding: utf-8 -*-
#
# pyXlsxTemplate documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 29 17:00:08 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
... | true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options ... | s = [
('index', 'pyxlsxtemplate', u'pyXlsxTemplate Documentation',
[u'Warren Price'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tup... |
bkfox/foxcms | foxcms/admin/perms.py | Python | lgpl-3.0 | 302 | 0.016556 | from django.contrib import admin
from f | oxcms.models.perms import Clearance, Permission
class PermissionInline(admin.TabularInline):
model = Permission
extra = 3
@admin.register(Clearance)
class ClearanceAdmin(admin.ModelAdmin):
fields | = [ 'name' ]
inlines = [ PermissionInline ]
|
Maplecroft/django-cms-saq | cms_saq/migrations/0001_initial.py | Python | mit | 9,981 | 0.003306 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import cms.models.fields
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_initial'),
('cms', '0003_auto_2014092... | only for multiple languages)')),
('label', models.CharField(max_length=512, blank=True)),
('help_text', models.CharField(max_length=512, blank=True)),
| ('question_type', models.CharField(max_length=1, choices=[(b'S', b'Single-choice question'), (b'M', b'Multi-choice question'), (b'F', b'Free-text question')])),
('optional', models.BooleanField(default=False, help_text=b'Only applies to free text questions')),
('depends_on_answ... |
SeriousBug/redditcurl | tests/test_base.py | Python | gpl-3.0 | 2,526 | 0.005542 | import os
import tempfile
import unittest
import shutil
from unittest.mock import MagicMock
test_links = {
"direct": "https://i.imgur.com/AaLX1Wn.jpg",
"gfycat": "https://gfycat.com/QualifiedDefensiveAddax",
"imgur_link": "https://imgur.com/AaLX1Wn",
"imgur_album": "https://imgur.com/a/IEKXq",
"im... | s", "test,testing"]
test_config = """
[redditcurl]
savedir = testdir
processes = 0
notitles = true
"""
test_config_auth = """
[oauth]
clientid = testid
redirect = http://testredirect
refresh_token = refreshtoken
access_token = accesstoken
"""
def create_submission(url="", title="", subreddit=""):
submission = M... | breddit.display_name = subreddit
return submission
test_submissions = [create_submission(url, title, "testsubreddit") for title, url in test_links.items()]
test_downloaded = [(url, (lambda x: x != "fail")(title)) for title, url in test_links.items()]
# Creates a downloaded items list, with all test links as succe... |
oomlout/oomlout-OOMP | old/OOMPpart_CAPC_0402_X_PF33_V50.py | Python | cc0-1.0 | 244 | 0 | impor | t OOMP
newPart = OOMP.oompItem(8809)
newPart.addTag("oompType", "CAPC")
newPart.addTag("oompSize", "0402")
newPart.addTag("oompColor", "X")
newPart.addTag("oompDesc", "PF33")
newPart.addTag("oompIndex", "V50")
OOMP.parts.append(n | ewPart)
|
chainer/chainercv | examples/fpn/train_multi.py | Python | mit | 11,453 | 0 | from __future__ import division
import argparse
import multiprocessing
import numpy as np
import PIL
import chainer
import chainer.functions as F
import chainer.links as L
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensio... | ead(hs, mask_rois, mask_roi_indices)
mask_loss = mask_head_loss_post(
segms, mask_roi_indices, gt_segms, gt_mask_labels, B)
else:
# Compute dummy variables to complete the computational graph
| mask_rois[0] = self.xp.array([[0, 0, 1, 1]], dtype=np.float32)
mask_roi_indices[0] = self.xp.array([0], dtype=np.int32)
segms = self.model.mask_head(hs, mask_rois, mask_roi_indices)
mask_loss = 0 * F.sum(segms)
loss = (rpn_loc_loss + rpn_conf_loss +
... |
wesm/ibis | ibis/sql/sqlite/compiler.py | Python | apache-2.0 | 5,142 | 0 | # Copyright 2014 Cloudera 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, so... | False
)
_operation_registry.update({
ops.Cast: _cast,
ops.Substring: _substr,
ops.StrRight: _string_right,
ops.StringFind: _string_find,
ops.StringLength: unary('length'),
ops.Least: varargs(sa.func.min),
ops.Greatest: varargs(sa.func.max),
ops.IfNull: fixed_arity(sa.func.i... | im'),
ops.RStrip: unary('rtrim'),
ops.StringReplace: fixed_arity(sa.func.replace, 3),
ops.StringSQLLike: _infix_op('LIKE'),
ops.RegexSearch: _infix_op('REGEXP'),
ops.Strftime: _strftime,
ops.ExtractYear: _strftime_int('%Y'),
ops.ExtractMonth: _strftime_int('%m'),
ops.ExtractDay: _strft... |
difcareer/Krakatau | Krakatau/ssa/ssa_ops/tryreturn.py | Python | gpl-3.0 | 506 | 0.005929 | from .base import BaseOp |
from .. import excepttypes
from ..constraints import ObjectConstraint
from ..constraints import returnOrThrow, maybeThrow, throw, return_
class TryReturn(BaseOp):
def __init__(self, parent, canthrow=True):
super(TryReturn, self).__init__(paren | t, [], makeException=True)
self.outExceptionCons = ObjectConstraint.fromTops(parent.env, [], (excepttypes.MonState,), nonnull=True)
def propagateConstraints(self):
return maybeThrow(self.outExceptionCons) |
AlanCristhian/namedobject | setup.py | Python | mit | 1,413 | 0 | from setuptools import setup # type: ignore[import]
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="objname",
version="0.12.0",
packages=["objname"],
package_data={
"objname": ["__init__.py", "py.typed", "_module.py",
"test_objname.py"],
... | long_description,
long_description_content_type="text/markdown",
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3... | on :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development',
'Topic :: Software De... |
JayvicWen/Crawler | topit/topit/items.py | Python | mit | 309 | 0 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class PictureItem(scrapy.Item):
# define the fields for y | our item here like:
image_urls = scrapy.Field()
images = s | crapy.Field()
|
chunywang/crosswalk-test-suite | misc/webdriver-w3c-tests/navigation/refresh-page.py | Python | bsd-3-clause | 1,126 | 0.001776 | # -*- mode: python; fill-column: 100; comment-column: 100; -*-
import unittest
import sys
import os
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
class RefreshPageTest(base_test.WebDriverBaseTest):
# Get a static page that must be the same upon ... | tion/res/refreshPageStatic.html'))
body = self.driver.find_eleme | nt_by_css("body").get_text()
self.driver.execute_script(
"document.getElementById('body').innerHTML=''")
self.driver.refresh()
newbody = self.driver.find_element_by_css("body").get_text()
self.assertEqual(body, newbody)
self.driver.get(
self.webserver.whe... |
stackforge/solum | solum/tests/api/camp/v1_1/test_plans.py | Python | apache-2.0 | 1,582 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | pecan.request', new_callable=fakes.FakePecanRequest)
@mock.patch('pecan.response', new_callable=fakes.FakePecanResponse)
@mock.patch('solum.api.handlers.camp.plan_handler.PlanHandler')
class TestPlans(base.BaseTestCase):
def setUp(s | elf):
super(TestPlans, self).setUp()
objects.load()
def test_plans_get(self, PlanHandler, resp_mock, request_mock):
hand_get_all = PlanHandler.return_value.get_all
fake_plan = fakes.FakePlan()
hand_get_all.return_value = [fake_plan]
resp = plans.PlansController().ge... |
ianlini/flatten-dict | src/flatten_dict/flatten_dict.py | Python | mit | 5,769 | 0.001907 | import inspect
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
import six
from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer
from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter
REDUCER_DICT = {
... | ise ValueError("duplicated key '{}'".format(flat_key))
flat_dict[flat_key] = value
return has_item
_flatten(d, depth=1)
return flat_dict
def nested_set_dict(d, keys, value):
"""Set a value to a sequence of nested keys.
Parameters
----------
d : Mapping
keys : Sequenc... | raise ValueError("duplicated key '{}'".format(key))
d[key] = value
return
d = d.setdefault(key, {})
nested_set_dict(d, keys[1:], value)
def unflatten(d, splitter="tuple", inverse=False):
"""Unflatten dict-like object.
Parameters
----------
d : dict-like object
T... |
fishroot/nemoa | nemoa/system/commons/links.py | Python | gpl-3.0 | 1,111 | 0.007201 | # -*- coding: utf-8 -*-
__author__ = 'Patrick Michl'
__email__ = 'frootlab@gmail.com'
__license__ = 'GPLv3'
import nemoa
import n | umpy
class Links:
"""Class to unify common ann link attributes."""
params = {}
def __init__(self): pass
@staticmethod
def energy(dSrc, dTgt, src, tgt, links, calc = 'mean'):
"""Return link energy as numpy array."""
if src['class'] == 'gauss':
M = - links['A'] * links... | p(src['lvar'])).T
elif src['class'] == 'sigmoid':
M = - links['A'] * links['W']
else: raise ValueError('unsupported unit class')
return numpy.einsum('ij,ik,jk->ijk', dSrc, dTgt, M)
@staticmethod
def get_updates(data, model):
"""Return weight updates of a link layer.... |
Microsoft/PTVS | Python/Product/Miniconda/Miniconda3-x64/Lib/idlelib/grep.py | Python | apache-2.0 | 6,741 | 0.000148 | """Grep dialog for Find in Files functionality.
Inherits from SearchDialogBase for GUI and uses searchengine
to prepare search pattern.
"""
import fnmatch
import os
import sys
from tkinter import StringVar, BooleanVar
from tkinter.ttk import Checkbutton
from idlelib.searchbase import SearchDialogBase
from idle... | tputWindow parent.
"""
root = text._root()
engine = searchengine.get(root)
if not hasattr(engine, "_grepdialog"):
engine._grepdialog = GrepDialog(root, engine, flist)
dialog = engine._grepdialog
searchphrase = text.get("sel.first", "sel.last")
dialog.open(text, searchphrase, io)
c... | ."
title = "Find in Files Dialog"
icon = "Grep"
needwrapbutton = 0
def __init__(self, root, engine, flist):
"""Create search dialog for searching for a phrase in the file system.
Uses SearchDialogBase as the basis for the GUI and a
searchengine instance to prepare the search.
... |
thetoine/eruditorg | erudit/core/editor/tests/test_models.py | Python | gpl-3.0 | 927 | 0 | from django.test import TestCase
from ..factories import IssueSubmissionFactory
from ..models import IssueSubmission
class IssueSubmissionTestCase(TestCase):
def test_version(self):
issue = IssueSubmissionFactory()
copy = issue.save_version()
self.assertEqual(issue.journal, copy.journal)... | ual(issue.id, copy.id)
self.assertEqual(issue.paren | t, copy)
class IssueSubmissionWorkflowTestCase(TestCase):
def test_refuse(self):
issue = IssueSubmissionFactory()
issue.submit()
issue.refuse()
issues = IssueSubmission.objects.all().order_by('id')
self.assertEqual(issues.count(), 2)
self.assertEqual(issues[0].par... |
mokuki082/EggDrop | code/helper.py | Python | gpl-3.0 | 1,600 | 0.005625 | import pygame
import os, sys
from pygame.locals import *
import socketserver
import socket
def min(a, b):
return a if a < b else b
''' Load an animation strip.'''
def load_strip(filename, nframes, width=None, height=None, colorkey=None):
full_image, full_rect = load_image(filename, width=width, height=height)... | e(image, (width, height))
if width:
ratio = width/image.get_size()[0]
image = pygame.transform.scale(image, (int(width), int(image.get_size()[1] * ratio)))
elif height:
ratio = height/image.get_size()[1]
image = pygame.transform.scale(image, (int(image.get_size()[0] * ratio), int... | ullpath)
|
RedHatQE/cfme_tests | cfme/tests/networks/test_tag_tagvis.py | Python | gpl-2.0 | 3,856 | 0.001815 | import pytest
from cfme.cloud.provider.azure import AzureProvider
from cfme.markers.env_markers.provider import ONE_PER_CATEGORY
from cfme.networks.views import BalancerView
from cfme.networks.views import CloudNetworkView
from cfme.networks.views import FloatingIpView
from cfme.networks.views import NetworkPortView
f... | dren(provider, appliance, request, relationship, view,
tag, user_restricted):
"""
Polarion:
assignee: anikifor
initialEstimate: 1/8h
casecomponent: Tagging
"""
collection = appliance.collections.network_providers.filter({'provider': provi... | ve_tag(tag=tag))
actual_visibility = child_visibility(appliance, network_provider, relationship, view)
assert actual_visibility
with user_restricted:
actual_visibility = child_visibility(appliance, network_provider, relationship, view)
assert not actual_visibility
@pytest.fixture(params=... |
brynmathias/rootpy | rootpy/plotting/style.py | Python | gpl-3.0 | 10,083 | 0.014777 | from ROOT import TStyle, TColor, TGaxis, gROOT
__use_matplotlib = True
try:
from matplotlib.colors import colorConverter
except ImportError:
__use_matplotlib = False
##############################
#### Markers #################
markerstyles_root2mpl = {
1 : '.',
2 : '+',
3 : '*',
4 : 'o',
... | solid' : 1001,
}
def convert_fillstyle(inputstyle, mode, inputmode=None):
"""
Convert *inputstyle* to ROOT or matplotlib format.
Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*
may be a ROOT fill style, a matplotlib hatch style | , or a description
such as 'hollow' or 'solid'.
"""
mode = mode.lower()
if mode != 'mpl' and mode != 'root':
raise ValueError("%s is not an understood value for mode" % mode)
if inputmode is None:
try:
# inputstyle is a ROOT linestyle
inputstyle = int(inputsty... |
gurisxie/weex-test | test/tools/getjsfm.py | Python | apache-2.0 | 398 | 0.027638 | #!/usr/bin/python
# -*- coding=utf-8 -*-
import os
import os.path
import re
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='get jsfm version....')
parser.add_argument("-path", type=str, help="jsfm path | ")
args = parser.parse_args()
f = open(args.path, 'r')
content = f.read(110)
pattern = re.compile('"(.*)"')
p | rint pattern.findall(content)
|
stweil/letsencrypt | certbot-ci/snap_integration_tests/dns_tests/test_main.py | Python | apache-2.0 | 1,935 | 0.004651 | #!/usr/bin/env python3
import glob
import os
import re
import subprocess
import pytest
@pytest.fixture(autouse=True, scope="module")
def install_certbot_snap(request):
with pytest.raises(Exception):
subprocess.check_call(['certbot', '--version'])
try:
snap_folder = request.config.getoption("s... | universal_newlines=True)
subprocess.check_call(['snap' | , 'connect', snap_name + ':certbot-metadata',
'certbot:certbot-metadata'])
subprocess.check_call(['snap', 'install', '--dangerous', dns_snap_path])
finally:
subprocess.call(['snap', 'remove', plugin_name])
|
joedursun/.emacs.d | elpa/elpy-20150226.1148/elpy/__init__.py | Python | gpl-3.0 | 1,388 | 0 | # Elpy, the Emacs Lisp Python Environment
# Copyright (C) 2013 Jorgen Schaefer
# Author: Jorgen Schaefer <contact@jorgenschaefer.de>
# URL: http://github.com/jorgenschaefer/elpy
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as publishe... | ) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Pu... | ironment.
Elpy is a mode for Emacs to support writing Python code. This package
provides the backend within Python to support auto-completion,
documentation extraction, and navigation.
Emacs will start the protocol by running the module itself, like so:
python -m elpy
This will emit a greeting string on a single ... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/keras/estimator/__init__.py | Python | mit | 227 | 0.004405 | """Impo | rts for Python API.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.python.keras._impl.keras.estimator import model_to_est | imator |
TheSriram/haxor | tests/test_job_stories.py | Python | mit | 463 | 0 | #!/usr/bin/env python
"""
Tests job_stories()
@author avinash | sajjanshetty
@email hi@avi.im
"""
import unittest
from hackernews import HackerNews
class TestjobStories(unittest.TestCase):
def setUp(self):
self.hn = HackerNews()
def test_job_stories(self):
job_stories = self.hn.job_stories()
self.assertIsInstance(job_storie | s, list)
self.assertIsNotNone(job_stories)
if __name__ == '__main__':
unittest.main()
|
gkc1000/pyscf | pyscf/grad/uhf.py | Python | apache-2.0 | 4,855 | 0.009063 | #!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. 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
#
# U... | , 0.757 , 0.587)] ]
mol.basis = '631g'
mol.build()
mf = scf.UHF(mol)
mf.conv_tol = 1e-14
| e0 = mf.scf()
g = Gradients(mf)
print(g.grad())
#[[ 0 0 -2.41134256e-02]
# [ 0 4.39690522e-03 1.20567128e-02]
# [ 0 -4.39690522e-03 1.20567128e-02]]
mol = gto.Mole()
mol.atom = [
['O' , (0. , 0. , 0.)],
[1 , (0. , -0.757 , 0.587)],
[1 , (0. , 0.75... |
js0701/chromium-crosswalk | tools/telemetry/telemetry/internal/backends/mandoline/desktop_mandoline_backend.py | Python | bsd-3-clause | 5,112 | 0.010563 | # Copyright 2015 The Chromium 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 logging
import os
import shutil
import subprocess
import sys
import tempfile
from telemetry.core import exceptions
from telemetry.core import util
fr... | _tmp_output_file.close()
self._tmp_output_file = None
if not self.browser_options.show_stdout:
self._tmp_output_file = tempfile.NamedTemporaryFile()
self._proc = su | bprocess.Popen(
args, stdout=self._tmp_output_file, stderr=subprocess.STDOUT, env=env)
else:
self._proc = subprocess.Popen(args, env=env)
try:
self._WaitForBrowserToComeUp()
self._InitDevtoolsClientBackend()
except:
self.Close()
raise
@property
def pid(self):
... |
Pysellus/streaming-api-test | twitter-api-full-example/main_with_threads.py | Python | mit | 2,615 | 0.007648 | #!/usr/bin/env python3
import re
import json
from threading import Thread
from rx import Observable
import APIReaderTwitter as Twitter
emoji_re = re.compile(u'['
u'\U0001F300-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF\u2700-\u27BF]+',
re.UNICODE)
# Util
def process_stream(... | 0
# Tests
def tweet_has_more_than_two_emojis(element):
return count_emoji(element['text']) > 2
# https://dev.twitter.com/overview/api/tweets
def original_tweet_has_less_ | than_50_retweets(element):
return element['retweeted_status']['retweet_count'] <= 50
def hashtag_longer_than_twelve_letters(element):
return all(len(h['text']) > 12 for h in element['entities']['hashtags'])
# Expects
# All retweeted tweets should have less than 50 retweets
def retweet_test(element):
if no... |
endlessm/chromium-browser | third_party/chromite/test/portage_testables_unittest.py | Python | bsd-3-clause | 1,975 | 0.011139 | # -*- coding: utf-8 -*-
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for test/portage module."""
from __future__ import print_function
import pytest # pylint: disable=import-error
i... | [overlay])
def test_emerge_against_fake_sysroot(m | inimal_sysroot):
"""Test that a basic `emerge` operation works against a test sysroot."""
overlay, sysroot = minimal_sysroot
pkg1 = cr.test.Package('foo', 'bar')
overlay.add_package(pkg1)
pkg2 = cr.test.Package('foo', 'spam', depend='foo/bar')
overlay.add_package(pkg2)
sysroot.run(['emerge', 'foo/spam']... |
harisbal/pandas | pandas/plotting/_core.py | Python | bsd-3-clause | 128,319 | 0.000023 | # being a bit too dynamic
# pylint: disable=E1101
from __future__ import division
import warnings
import re
from collections import namedtuple
from distutils.version import LooseVersion
import numpy as np
from pandas.util._decorators import cache_readonly, Appender
from pandas.compat import range, lrange, map, zip, ... | r symbol")
def _iter_data(self, data=None, keep_index=False, fillna=None):
if data is None:
data = self.data
if fillna is not None:
data = data.fillna(fillna)
# TODO: unused?
# if self.sort_columns:
# columns = com.try_sort(data.columns)
| # else:
# columns = data.columns
for col, values in data.iteritems():
if keep_index is True:
yield col, values
else:
yield col, values.values
@property
def nseries(self):
if self.data.ndim == 1:
return 1
el... |
psf/black | tests/data/pep_572_py39.py | Python | mit | 251 | 0 | # Unparenthesized walruses are now allowed in set literals & set comprehensions
# since Python 3.9
{x := 1, 2, 3}
{x4 := x**5 for x in range(7)}
# We bet | ter not remove th | e parentheses here (since it's a 3.10 feature)
x[(a := 1)]
x[(a := 1), (b := 3)]
|
tempbottle/restcommander | play-1.2.4/python/Lib/site-packages/Rpyc/Demo/testmodule.py | Python | apache-2.0 | 373 | 0.010724 | import time
from Rpyc import Async
def threadfunc(callback):
"""this function will call the | callback every second"""
callback = Async(callback)
try:
| while True:
print "!"
callback()
time.sleep(1)
except:
print "thread exiting"
def printer(text):
print text
def caller(func, *args):
func(*args)
|
evojimmy/linux-server-backup | scripts/widgets/BaseWidget.py | Python | mit | 202 | 0.00495 | class BaseWidget(object):
| def __init_ | _(self, path):
self._path = path
def expand(self):
"Implement this in sub classes"
raise Exception("Not implemented in Base class.")
|
Smarsh/django | django/db/backends/postgresql/operations.py | Python | bsd-3-clause | 8,671 | 0.006343 | import re
from django.db.backends import BaseDatabaseOperations
# This DatabaseOperations class lives in here instead of base.py because it's
# used by both the 'postgresql' and 'postgresql_psycopg2' backends.
class DatabaseOperations(BaseDatabaseOperations):
def __init__(self, connection):
super(Databas... | None:
from django.db.backends.postgresql.version import get_version
cursor = self.connection.cursor()
self._postgres_version = get_version(curs | or)
return self._postgres_version
postgres_version = property(_get_postgres_version)
def date_extract_sql(self, lookup_type, field_name):
# http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
if lookup_type == 'week_day':
# For consis... |
jheidel/passpoller | multi_notifier.py | Python | mit | 386 | 0.020725 | import threading
class MultiNotifier(object):
"""Multithreaded notifier implementation."""
def __init__(self, notifiers):
self.notifiers = notifiers
def send(self, *args, **kw | args):
threads = [threading.Thread(target=n.send, args=args, kwargs=kwargs)
for n in self.notifiers]
for t in threads:
t.start()
for t in | threads:
t.join()
|
fragforce/fragforce.org | ffdonations/migrations/0013_auto_20181004_2337.py | Python | gpl-2.0 | 437 | 0 | # Generated by Django 2.1.2 on 2018-10-05 03:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ffdonations', '0012_remove_donationmodel_tracked'),
]
operations = [
migrations.AlterField(
mode | l_name='participantmodel',
name='created',
| field=models.DateTimeField(null=True, verbose_name='Created At'),
),
]
|
jibaku/blogging | blogging/actions.py | Python | bsd-3-clause | 2,706 | 0.001478 | # -*- coding: utf-8 -*-
"""Bloggin app actions for admin."""
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext
from blogging.models import Post
# Post Actions
def make_published(modeladmin, request, queryset):
"""Mark the given posts as published."""
count... | ladmin.message_user(request, message)
make_draft.short_description = _(u"Mark selected stories as draft")
def make_selected(modeladmin, request, queryset):
"""Mark the given posts as selected."""
count = queryset.update(selected=True)
message = ungettext(
u'%(count)d post was su | ccessfully marked as selected.',
u'%(count)d posts were successfully marked as selected',
count
) % {'count': count}
modeladmin.message_user(request, message)
make_selected.short_description = _(u"Mark selected stories as selected")
def make_post_type_action(key, name):
"""Create Post acti... |
Sanjurjo7/microblog | db_upgrade.py | Python | mit | 317 | 0.003155 | #!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from co | nfig import SQLALCHEMY_MIGRATE_REPO
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEM | Y_MIGRATE_REPO)
print('Current database version: ' + str(v))
|
hbldh/b2ac | b2ac/fit/reference.py | Python | mit | 7,871 | 0.001527 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. module:: ellipse_fitting
:platform: Unix, Windows
:synopsis: Ellipse fitting algorithms and handling of ellipse information.
.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>
Created on 2013-05-05, 23:22
"""
from __future__ import division
from __future_... | S2 = D1’ * D2; % combined part of the scatter matrix
S3 = D2’ * D2; % linear part of the scatter matrix
T = - inv(S3) * S2’; % for getting a2 from a1
M = S1 + S2 * T; % reduced scatter matrix
M = [M(3, :) ./ 2; - M(2, :); M(1, :) ./ 2]; % premultiply by inv(C1)
| [evec, eval] = eig(M); % solve eigensystem
cond = 4 * evec(1, :) .* evec(3, :) - evec(2, :) .ˆ 2; % evaluate a’Ca
a1 = evec(:, find(cond > 0)); % eigenvector for min. pos. eigenvalue
a = [a1; T * a1]; % ellipse coefficients
:param points: The [Nx2] array of points to fit ellipse to.
:t... |
osspeak/osspeak | osspeak/recognition/actions/library/directinput.py | Python | mit | 4,326 | 0.008322 | # direct inputs
# source to this solution and code:
# http://stackoverflow.com/questions/14489013/simulate-python-keypresses-for-controlling-a-game
# http://www.gamespp.com/directx/directInputKeyboardScanCodes.html
import ctypes
import time
HELD = set()
SendInput = ctypes.windll.user32.SendInput
mouse_button_down_m... | Input)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actuals Functions
def release_all():
held = | list(HELD)
for key in held:
release(key)
try:
HELD.remove(key)
except KeyError:
pass
def hold(key):
hexKeyCode = CODES[str(key)]
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
x = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.