code stringlengths 1 199k |
|---|
import __builtin__
import ConfigParser
import logging
import optparse
import os
import StringIO
import sys
from version_number import VERSION_NUMBER
import version_manager
version_manager.main()
sys.path.insert(0, os.path.abspath("src"))
logging.basicConfig(level=logging.ERROR)
class OMConfig(ConfigParser.RawConfigPars... |
"""
django.core.mail uses part of the email package.
Problem is: when using runserver with autoreload mode, the thread that
checks fore changed files unwillingly trigger further imports within
the email package because of the LazyImporter in email (used in 2.5 for
backward compatibility).
We then need to name those mod... |
import re
from requests.utils import dict_from_cookiejar
import traceback
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class BlueTigersProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes
... |
import math, audioop, time, wave, os
from collections import deque
from pocketsphinx import *
import pyaudio
from VoiceDecoder import VoiceDecoder
class Listener():
def __init__(self):
print "Listener Created"
# INIT FUNCTIONS
# self.setupMic()
# self.listen()
self.d = VoiceD... |
import usb
from time import sleep
class RocketManager:
vendor_product_ids = [(0x1941, 0x8021), (0x0a81, 0x0701), (0x0a81, 0xff01), (0x1130, 0x0202), (0x2123,0x1010)]
launcher_types = ["Original", "Webcam", "Wireless", "Striker II", "OIC Webcam"]
housing_colors = ["green", "blue", "silver", "black", "gray"]
... |
import datetime
import sys
import os
homedir = os.environ['HOME']
log_path = homedir + "/Pigrow/logs/trigger_log.txt"
script = "write_log.py"
message = ""
for argu in sys.argv[1:]:
argu_l = str(argu).lower()
if argu_l == 'help' or argu_l == '-h' or argu_l == '--help':
print(" Script for writing to a log... |
"""Actions that can be reverted, i.e. undone and redone."""
import aeidon
__all__ = ("RevertableAction", "RevertableActionGroup",)
class RevertableAction:
"""
Action that can be reverted, i.e. undone and redone.
:ivar description: Short one line description
:ivar docs: Sequence of :attr:`aeidon.document... |
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
def dfs(root, target):
if not root:
return
if not root.left and not root.right:
if target ... |
import argparse
import logging
from datetime import datetime
from os import sys
from perceval.backends.bugzilla import Bugzilla
from perceval.backends.gerrit import Gerrit
from perceval.backends.github import GitHub
from grimoire_elk.elastic import ElasticConnectException
from grimoire_elk.elastic import ElasticSearch
... |
from unittest import TestCase
from common.timer import timed
@timed
def fib(n):
ls = [1, 1]
if n == 0:
return 0
if n <= 2:
return ls[n - 1]
for i in range(3, n + 1):
tmp = ls[1]
ls[1] = ls[0] + ls[1]
ls[0] = tmp
return ls[-1]
class Test(TestCase):
def test... |
from chowdren.writers.objects import ObjectWriter
from chowdren.common import get_animation_name, to_c, make_color
from chowdren.writers.events import (StaticConditionWriter,
StaticActionWriter, StaticExpressionWriter, make_table)
class Util(ObjectWriter):
class_name = 'Utility'
static = True
def write_... |
import sys
import os.path
import setuptools # Fix distutils issues
from cffi import FFI
ffi = FFI()
mod_name = 'instrumental.drivers.cameras._pixelfly.errortext'
if sys.platform.startswith('win'):
ffi.set_source(mod_name, """
#define PCO_ERR_H_CREATE_OBJECT
#define PCO_ERRT_H_CREATE_OBJECT
... |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 lat... |
import os
import sys
import re
import pdb
import pycparser
import subprocess
KNOWN_TYPES = ['int', 'double', 'float', 'char', 'short', 'long',
'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t']
def get_arglists(pf):
pyc = pycparser.CParser()
p = pyc.parse(pf)
args = {}
for (dc, d) in p.childr... |
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
from statsmodels.distributions.empirical_distribution import ECDF
from collections import Counter
from ..guifiwrapper.guifiwrapper import *
root = 17711
g = CNMLWrapper(root)
import os
basedir = os.path.join(o... |
import os
import hashlib
from Anomos.bencode import bencode, bdecode
from Anomos.btformats import check_message
NOISY = False
def parsedir(directory, parsed, files, blocked, errfunc,
include_metainfo=True):
if NOISY:
errfunc('checking dir')
dirs_to_check = [directory]
new_files = {}
... |
import sys
import os
import pty, shlex
import signal
import subprocess
import socket
import time
import atexit
import re
import string
import logging
import random
from .vif import VirtualInterface
from .vnet import VirtualNet
from .riotnative import RIOT
from string import Template
import libvirt
import hashlib
all_do... |
i = 0
while i < 25:
i = i + 1 |
import Foundation
import AppKit
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def notifyMac(title, subtitle, info_text, delay=0):
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
n... |
from rest_framework import generics
from .models import Proj
from .serializers import ProjSerializer
class ProjList(generics.ListCreateAPIView):
"""be report project list"""
queryset = Proj.objects.all()
serializer_class = ProjSerializer
class ProjDetail(generics.RetrieveUpdateDestroyAPIView):
"""be rep... |
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2013 Task Coach developers <developers@taskcoach.org>
Task Coach 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
(... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('season', '0003_auto_20161206_0216'),
]
operations = [
migrations.AddField(
model_name='groupround',
name='schedule_is_set',
... |
"""This module defines some utility `Tab` subclasses, including HTTP
error handlers.
"""
from MarkupPy import markup
from .registry import (get_tab, register_tab)
from gwdetchar.io import html
__author__ = 'Duncan Macleod <duncan.macleod@ligo.org>'
__all__ = ['AboutTab', 'Error404Tab']
Tab = get_tab('basic')
class Abou... |
import serial # if you have not already done so
from time import sleep
import matplotlib.pyplot as plt
import re
import datetime
import numpy
import pickle
class DataExtruder:
def __init__(self,port='/dev/ttyACM0',baudrate=115200):
self.pattern_pixels=re.compile(r'data=(?P<pixels>[\w ]*) \((?P<nerror>\d*) errors'... |
"""Package initialization."""
from .core import *
from .main import main
from .pandocattributes import PandocAttributes |
"""
Copyright 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 l... |
"""
Flaskr
~~~~~~
A microblog example application written as Flask tutorial with
Flask and sqlite3.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from sqlite3 import dbapi2 as sqlite3
from flask import (Flask, request, session,
redire... |
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from collections import namedtuple, defaultdict
from datetime import datetime
from random import randint
from random import choice as randchoice
from copy import deepcopy
from .utils import checks
from __main__ import send_cmd_help
imp... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class ModuleDocFragment(object):
# Standard F5 documentation fragment
DOCUMENTATION = r'''
options:
provider:
description:
- A dict object containing connection details.
type: dict
version_added: "1.0.0"
... |
import time
import zlib
from bs4 import BeautifulSoup
from scraper import BaseScraper
from price_parser import parse_price_text
from MySQL_connector import db_connector
db = 'realestate_db'
class Parser(object):
scr_db = 'scraper_dumps'
tgt_db = 'realestate_db'
def __init__(self):
self.html = ""
... |
from __future__ import print_function, absolute_import
from .script_interface import ScriptInterfaceHelper, script_interface_register
@script_interface_register
class ComFixed(ScriptInterfaceHelper):
"""Fix the center of mass of specific types.
Subtracts mass-weighted fraction of the total
force action on a... |
import sys
input_data = sys.stdin.readlines()
static = input_data.pop(0).rstrip().split()
teams = int(static[0])
pizza = int(static[1])
nopizza= int(static[2])
input_data.pop(0)
pizza_scores = input_data[0:pizza]
input_data = input_data[pizza:]
pizza_scores = [-1 if x.rstrip() == '?' else int(x.rstrip()) for x in pizza... |
from mg.constructor import *
from mg.core.auth import AuthLogList
from mg.constructor.player_classes import DBCharacterOnlineList, DBPlayerList
from mg.constructor.interface import DBFirstVisitList
from mg.core.config import DBConfigGroup, DBConfigGroupList
import re
class DBDailyStat(CassandraObject):
clsname = "D... |
"""
Created on Wed Apr 06 15:59:04 2016
.. moduleauthor:: Adam Collin <adam.collin@ieee.org>
.. moduleauthor:: Mathew Topper <mathew.topper@dataonlygreater.com>
"""
from datetime import timedelta
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
from matplotlib.dates impo... |
import pytest
from cplpy import run_test, prepare_config
import subprocess as sp
import os
import glob
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.g... |
import re
import statistics
def count_letters(text):
'''
Text letter count
'''
count = 0
for char in text:
if char.isalpha():
count += 1
if count == 0:
return 1
else:
return count
def letter_dict(text):
'''
letter count dictionary
'''
text ... |
VERSION = None
BRANCH = 'master' |
"""
trend.datasource.trendfile.py
Handling and parsing of trendfiles (*.hdb)
Copyright (C) 2016/2017 Stefan Braun
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 (a... |
from gi.repository import Gtk
import re
import unicodedata
import data
import uigtk.dialogs
import uigtk.interface
import uigtk.search
import uigtk.widgets
class Nations(uigtk.widgets.Grid):
name = "Nations"
def __init__(self):
uigtk.widgets.Grid.__init__(self)
self.set_border_width(5)
N... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as snd
import seaborn as sns
from skimage import img_as_float, morphology, measure
from skimage.color import rgb2hsv
from skimage.morphology import reconstruction
from skimage.exposure import rescale_intensity
from skimage.measure import label
from... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. """
title = forms.CharField... |
from random import choice
from .DisjointSet import DSNode
from .DisjointSet import union
from .DisjointSet import find
from .DisjointSet import split_sets
from .Terrain import TerrainFactory
from .Terrain import CYBERSPACE_WALL
from .Terrain import CYBERSPACE_FLOOR
class Maze(object):
def __init__(self, length, wid... |
import http.server
import socketserver
from os import path, mkdir, listdir, makedirs, chdir
from shutil import copy2, copytree
import sys
import yaml
def config():
"""
Parse the configuration yaml file.
"""
try:
cfg = yaml.load(open('config.yml', 'r').read(), Loader=yaml.BaseLoader)
except I... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('db', '0052_auto_20161112_2141'),
]
operations = [
migrations.AlterField(
model_name='yearlevel',
name='name',
field=m... |
import logging
from django.core.management.base import BaseCommand
from citation.ping_urls import verify_url_status
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''Method that check if the code archived urls are active and working or not '''
def handle(self, *args, **options):
... |
"""
OutgoingMail module.
The OutgoingMail class allows to send mail, and encrypts/signs it if needed.
"""
import re
from StringIO import StringIO
from copy import deepcopy
from email.parser import Parser
from email.encoders import encode_7or8bit
from email.mime.application import MIMEApplication
from email.mime.multipa... |
"""
@file rebuildSchemata.py
@author Michael Behrisch
@date 2011-07-11
@version $Id: rebuildSchemata.py 11671 2012-01-07 20:14:30Z behrisch $
Let all SUMO binarie write the schema for their config
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyright (C) 2011-2012 DLR (http://www.dlr.de/... |
from stetl.output import Output
from stetl.util import Util
from stetl.packet import FORMAT
import httplib
import base64
log = Util.get_log('httpoutput')
class HttpOutput(Output):
"""
Output via HTTP protocol, usually via POST.
consumes=FORMAT.etree_doc
"""
def __init__(self, configdict, section, co... |
"""Module provides provides a convinient class :class:`Attachment` to access (Create,
Read, Delete) document attachments."""
import base64, logging
from os.path import basename
from copy import deepcopy
from mimetypes import guess_type
from httperror import *
f... |
"""Detached renderer window"""
from utils.globals import GlobalData
from .qt import (QMainWindow, QTimer, QStackedWidget, QLabel, QVBoxLayout,
QWidget, QPalette, Qt, QFrame)
from .mainwindowtabwidgetbase import MainWindowTabWidgetBase
class DetachedRendererWindow(QMainWindow):
"""Detached flow ui/m... |
from vsvbp import container, solver
import argparse, sys, os, re
def parse(inputfile):
""" Parse a file using format from
Brandao et al. [Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression (2013)]
Format:
d (number of dimensions)
C_1 ... C_d cap... |
from django.test import TestCase
from apps.taxonomy.models import Act
from apps.taxonomy.tests import factories
from apps.taxonomy.tests.base import TaxonomyBaseTestMixin
class TestActCreation(TestCase):
def setUp(self):
super(TestActCreation, self).setUp()
factories.TaxonRankFactory(id=0)
def t... |
from __future__ import absolute_import
"""
This module provides loaders for local file system and over http
local and remote access
"""
import os
import hmac
import requests
import yaml
import six
from six.moves.urllib.parse import unquote_plus, urlsplit, urlencode
import time
import pkgutil
import base64
import cgi
im... |
from cwrap import BaseCEnum
class FieldTypeEnum(BaseCEnum):
TYPE_NAME = "field_type_enum"
ECLIPSE_RESTART = None
ECLIPSE_PARAMETER = None
GENERAL = None
UNKNOWN_FIELD_TYPE = None
FieldTypeEnum.addEnum('ECLIPSE_RESTART', 1)
FieldTypeEnum.addEnum('ECLIPSE_PARAMETER', 2)
FieldTypeEnu... |
from resources.lib.gui.gui import cGui
from resources.lib.gui.guiElement import cGuiElement
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
from resources.lib.handler.ParameterHandler import ParameterHandler
from resources.lib import logger
from resources.lib.co... |
from django.db import migrations, models
import weblate.utils.backup
class Migration(migrations.Migration):
dependencies = [("wladmin", "0005_auto_20190926_1332")]
operations = [
migrations.AddField(
model_name="backupservice",
name="paperkey",
field=models.TextField(... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^list/$', views.list, name='list'),
url(r'^search/$', views.search, name='search'),
url(r'^add/$', views.add, name='add'),
url(r'^restaurant/(?P<id>[0-9]+)$', views.restaurant, name='res... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book', '0004_auto_20180717_1547'),
]
operations = [
migrations.AddField(
model_name='book',
name='authors',
field=mod... |
from setuptools import setup
setup(
name='TracGenericWorkflow',
version='1.0.4',
packages=['tracgenericworkflow','tracgenericworkflow.upgrades'],
package_data={'tracgenericworkflow' : ['*.txt', 'templates/*.html', 'htdocs/*.*', 'htdocs/js/*.js', 'htdocs/css/*.css', 'htdocs/images/*.*']},
author = 'R... |
"""
Module implementing the cooperation server.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtNetwork import QTcpServer
from .Connection import Connection
import Preferences
class CooperationServer(QTcpServer):
"""
Class implementing the cooperation server.
@si... |
from django.contrib import messages
from django.core.exceptions import PermissionDenied
class UploadPermissionDenied(PermissionDenied):
def __init__(self, request, log_func, error_message, *args, **kwargs):
log_func(error_message)
messages.error(request, error_message)
super(UploadPermission... |
"""288. An enormous factorial
https://projecteuler.net/problem=288
For any prime p the number N(p,q) is defined by N(p,q) = ∑n=0 to q Tn*pn
with Tn generated by the following random number generator:
S0 = 290797
Sn+1 = Sn2 mod 50515093
Tn = Sn mod p
Let Nfac(p,q) be the factorial of N(p,q).
Let NF(p,q) be the number of... |
import pandas
import numpy
import operator
from sklearn.preprocessing import OneHotEncoder
from typing import Mapping
def one_hot_encode(vector, dtype='float32', categories=None, index=None):
if isinstance(vector, pandas.Series):
index = vector.index
vector = vector.values
encoder = OneHotEncoder(
categories='a... |
from __future__ import (absolute_import, print_function,
unicode_literals, division)
import warnings
import numpy as np
try:
import cvxopt, cvxopt.modeling
except ImportError:
warnings.warn("cvxopt not found, optimizations will fail", ImportWarning)
from .utils import (select_tensor, expand_tensor, rota... |
import time
import maestro
try:
servo = maestro.Controller()
servo.setRange(1,4000,8000)
# about 5 clicks per full motion
# 1040 for left/right + is left, - is right.
# 800 for up/down + is up, - is down.
x = servo.getPosition(1) + 800
servo.setAccel(1,6)
servo.setTarget(1,x)
finally:
servo.close |
from . import advancetools
from flask import render_template,redirect,Response,url_for
@advancetools.route('/')
def index():
return redirect(url_for('auto_decode_base'))
@advancetools.route('/auto_decode_base')
def auto_decode_base():
return render_template('advancetool/auto_decode_base.html') |
import random
import re
import wolframalpha
import time
import sys
from sys import maxint
from client import jarvispath
WORDS = ["WHO", "WHAT", "WHERE", "HOW MUCH"]
def handle(text, mic, profile):
app_id=profile['keys']['WOLFRAMALPHA']
client = wolframalpha.Client(app_id)
query = client.query(text)
if l... |
print "I could have code like this." # and the comment after is ignored
print "This won't not run" |
import sys
import os
import shlex
sys.path.insert(0, os.path.abspath('../eruditorg'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings.base')
import django
django.setup()
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
sou... |
import numpy as np
import os
from tensorutils.antisym import get_antisymmetrizer_product as asym
test_dir_path = os.path.dirname(os.path.realpath(__file__))
array_path_template = os.path.join(test_dir_path, "random_arrays", "{:s}.npy")
def test__composition_1():
array1 = np.load(array_path_template.format("15x15"))... |
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty
from kivy.graphics import Color, Ellipse, Line
from kivy.graphics.transformation import Matrix
from kivy.core.window ... |
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.lib.six import callable
def binned_statistic(x, values, statistic='mean',
bins=10, range=None):
"""
Compute a binned statistic for a set of data.
This is a generalization of a histogram functi... |
from . import db
from iptools import IpRange
from datetime import datetime, timedelta
from core import Board, User
class Ban (db.Model):
""" Ban is an abstract model for IPBan and UserBan. It provides
methods to check for affected boards and some to get different parts
of the ban duration """
__abstract... |
"""
Created on Sun Jan 22 23:03:45 2017
@author: Shabaka
"""
import pandas as pd
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
from sqlalchemy.sql import func
from sqlalchemy import MetaData, Table
metadata = MetaData()
engine = create_engine('sqlite:///census_nyc.sqlite')
census = Table('census'... |
import sys
sys.path.append('/home/pi/Desktop/ADL/YeastRobot/PythonLibrary')
from RobotControl import *
deck="""\
DW96P DW96P DW96W DW96W BLANK
DW96P DW96P DW96W DW96W BLANK
DW96P DW96P DW96W DW96W BLANK
BLANK BLANK BLANK BLANK BLANK
"""
OffsetDict={0: 'UL', 1: 'UR', 2: 'LL', 3: 'LR'}
DefineDeck(deck)
pr... |
from __future__ import division
import sys, os, time, platform, math
from struct import unpack, pack
"""
生成测试数据:
rm test.txt test.txt.bz2
echo 'hello, world(世界)!!!!' > test.txt
bzip2 -z test.txt
解压数据:
python bzip2.py
参考资料:
https://en.wikipedia.org/wiki/Bzip2
注:
bzip2 并没有 RFC 文档,
所以你只有参考维基百科上... |
import time
import plugins
import hangups
def _initialise(bot):
plugins.register_handler(on_hangout_call, type="call")
def on_hangout_call(bot, event, command):
if event.conv_event._event.hangout_event.event_type == hangups.schemas.ClientHangoutEventType.END_HANGOUT:
lastcall = bot.conversation_memory_g... |
''' Spatial graphs generation and methods '''
import os
import time
import numpy as np
import nngt
from nngt.geometry import Shape
ell = Shape.ellipse(radii=(3000., 5000.))
num_nodes = 1000
population = nngt.NeuralPop.uniform(num_nodes)
g = nngt.generation.gaussian_degree(
100., 5., nodes=num_nodes, shape=ell, pop... |
"""
Created on Tue Jul 07 09:44:36 2015
@author: Marcus
"""
import pygimli as pg
import numpy as np
from pygimli.physics.traveltime.fastMarchingTest import fastMarch
import matplotlib.pyplot as plt
import time as time
from pygimli.mplviewer import drawMesh # , drawField, drawStreamLines
class TravelTimeFMM(pg.Modellin... |
import pygame
import src.sprite as game
pygame.init()
screen = pygame.display.set_mode((400,300))
done = False
GameUpdateList = []
GameRenderList = []
catapult = game.Sprite("data/img/catapult.png", 5)
boulder = None
catapultAnim = game.Animation(catapult, 96, 96, 5, 100)
GameUpdateList.append(catapultAnim)
GameRenderL... |
"""Retrieves the paths to the required schedule files."""
from datetime import datetime
import logging
import pytz
from unipath import Path
LOG = logging.getLogger(__name__)
def get_date(tz_string):
"""Generates todays date as string (in format yyyy-mm-dd)"""
schedule_tz = pytz.timezone(tz_string)
today = d... |
import sys
from collections import namedtuple
test_cases = open(sys.argv[1], 'r')
test_lines = (line.rstrip() for line in test_cases)
def num_to_components(num):
num_comp = namedtuple('NumComponents', ('thousands', 'hundreds', 'tens', 'singles'))
thousands = int(num/1000)
hundreds = int((num - 1000*thousands)/100)
... |
__id__ = "$Id: baseclass.py 6843 2013-01-09 22:14:20Z juhas $"
from diffpy.pyfullprof.containerclass import *
from diffpy.pyfullprof.exception import *
class BaseClass:
"""BaseClass defines the basic parameters and objects(i.e., subclasses in the
SubClassDict and ObjectListDict). The definition can be used for ... |
'''
Created on 15.11.2021
@author: michael
'''
from alexandriabase.daos import DocumentDao, DaoModule, DOCUMENT_TABLE,\
DocumentFileInfoDao
from injector import Injector, inject
from alexandriabase import AlexBaseModule
from alexandriabase.services import ServiceModule, DocumentFileManager,\
DocumentFileNotFoun... |
"""
Test the `ipalib.frontend` module.
"""
from ipatests.util import raises, read_only
from ipatests.util import ClassChecker, create_test_api
from ipatests.util import assert_equal
from ipalib.constants import TYPE_ERROR
from ipalib.base import NameSpace
from ipalib import frontend, backend, plugable, errors, paramete... |
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.template.defaultfilters import filesizeformat
from hav.apps.media.models import Media
from hav.apps.hav_collections.models import Collection
from hav.apps.archive.models import ArchiveFile
from ...tasks import c... |
import threading, time, Queue, os, sys, shutil, random
from util import user_dir, appdata_dir, print_error, print_msg
from bitcoin import *
import interface
from blockchain import Blockchain
DEFAULT_PORTS = {'t':'50011', 's':'50012', 'h':'8181', 'g':'8282'}
DEFAULT_SERVERS = {
'server.electrum-exe.org': DEFAULT_POR... |
import pylab as pl
import scipy as sp
from serpentine import *
from elements import *
import visualize
class AtfExt :
def __init__(self) :
print 'AtfExt:__init__'
# set twiss parameters
mytwiss = Twiss()
mytwiss.betax = 6.85338806855804
mytwiss.alphax = 1.11230788371885
... |
"""
Created on Thu Jun 05 13:55:13 2014
@author: Alison Kirkby
"""
import mtpy.core.edi as mtedi
import os
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as si
import mtpy.utils.exceptions as MTex
import mtpy.utils.calculator as MTcc
import mtpy.analysis.geometry as MTg... |
from django.core.urlresolvers import reverse
from tests.test_utils import create_generic_job
from treeherder.model.models import JobLog
def test_get_job_log_urls(test_repository, result_set_stored,
failure_classifications,
generic_reference_data, webapp):
job1 = c... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import absolute_import
import HTMLParser
import StringIO
import ast
import base64
import cgi
from collections import Mapping
import datetime
from decimal import Decimal
import gzip
import hashl... |
from __future__ import print_function
'PackagesHTTPD - stream folder content as .tar over http'
__author__ = 'Mathias Gumz <mgumz@tpip.net>'
__license__ = 'MPL2'
__version__ = ''
import sys
import os, os.path
import zipfile, tarfile
from StringIO import StringIO
import cgi
try:
from http.server import SimpleHTTPRe... |
'''Common test fixtures
@author: Jesse Schwartzentruber (:truber)
@license:
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
'''
import logging
import os
import shutil
impo... |
from __future__ import unicode_literals
import unittest
class TestUDPipe(unittest.TestCase):
def test_model(self):
import ufal.udpipe
model = ufal.udpipe.Model.load('test/data/test.model')
self.assertTrue(model)
tokenizer = model.newTokenizer(model.DEFAULT)
conlluOutput = ufa... |
'''
Set of analytics based on ssdeep hash.
- compare
Simple implementation of ssdeep comparisions using a few optimizations
described at the links below
https://www.virusbulletin.com/virusbulletin/2015/11/optimizing-ssdeep-use-scale
http://www.intezer.com/intezer-community-tip-ssdeep-comparisons-with-el... |
from __future__ import unicode_literals
from django.db import migrations, models
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0028_merge'),
('home', '0023_remove_homepage_live_feed_intro'),
]
operations = [
migrations.CreateModel... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("studies", "0001_initial")]
operations = [migrations.AlterModelOptions(name="extension", options={"ordering": ("-id",)})] |
"""
Serializers for Video Abstraction Layer
Serialization is usually sent through the VideoSerializer which uses the
EncodedVideoSerializer which uses the profile_name as it's profile field.
"""
from rest_framework import serializers
from django.core.exceptions import ValidationError
from edxval.models import Profile, ... |
from tfidf import *
import psycopg2
import psycopg2.extensions
import math
def cos_sim(A,B):
def dot_product(a,b):
sum = 0.0
for key in a.keys():
if key in b:
sum += a[key]*b[key]
return sum
return dot_product(A,B)/(math.sqrt(dot_product(A,A)) * math.sqrt(dot_... |
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('ccx', '0008_auto_20170523_0630'),
]
operations = [
migrations.AlterField(
model_name='customcourseforedx',
name='... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.