content stringlengths 4 20k |
|---|
#!/usr/bin/python
import re, os, json, requests, urllib, gzip
from os import listdir
import matplotlib.pyplot as plt
from ftplib import FTP
import ensembl_data
import uniprot_data
global count, total, save
count = {} # Contains the frequency of occurence of each amino acid in the proteome sequence.
"""
The script pa... |
from rest_framework import serializers
from participation import models
import re
class ParticipantSerializer(serializers.ModelSerializer):
class Meta:
model = models.Participant
fields = (
'id', 'first_name', 'last_name', 'birthday', 'phone', 'address',
'user', 'full_name'... |
#!/usr/bin/env python3
'''
A tool for connecting to minecraft hidden servers.
For more info, look at README.md
'''
from socket import socket, SOL_SOCKET, SO_REUSEADDR
from socket import error as sock_err
import selectors
import torsocks
import sys
import threading
import queue
import logging
MC_PORT = 25565
BUFFSIZE =... |
"""
tests.helpers
~~~~~~~~~~~~~
Provides helper functions for unit tests in this package.
:copyright: 2012, 2013, 2014, 2015 Jeffrey Finkelstein
<<EMAIL>> and contributors.
:license: GNU AGPLv3+ or BSD
"""
import sys
is_python_version_2 = sys.version_info[0] == 2
if is_python_ver... |
"""
fs.tests.test_zipfs: testcases for the ZipFS class
"""
import unittest
import os
import random
import zipfile
import tempfile
import shutil
import fs.tests
from fs.path import *
from fs import zipfs
from six import PY3, b
class TestReadZipFS(unittest.TestCase):
def setUp(self):
self.temp_filen... |
"""
Django settings for safehouse project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... |
from flask_wtf import FlaskForm
from wtforms import StringField, \
PasswordField, BooleanField, \
SubmitField, ValidationError
from wtforms.validators import Required, Length, Email, Regexp, EqualTo
from ..models import User
class LoginForm(FlaskForm):
email = StringField(
'Email',
valida... |
import unittest
import numpy as np
from p5.sketch.Vispy2DRenderer.shape import PShape
from p5.core.color import Color
from p5.pmath import PI
vertices = [(0, 0), (1, 0), (1, 1), (0, 1)]
quad = PShape(vertices=vertices, fill_color=Color(255),
stroke_color=Color(0), stroke_weight=2,
stroke_... |
"""
celery workers 启动文件
"""
from celery import Celery
from kombu import Exchange, Queue
import config
tasks = ['tasks.links', 'tasks.logs']
app = Celery('mfw_task', include=tasks, broker=config.CELERY_BROKER, backend=config.CELERY_BACKEND)
app.conf.update(
task_serializer='json',
accept_content=['json'],
... |
"""
Computes the observed order of convergence for the velocity components and the
pressure using the solution on 4 consistently refined grids.
"""
import os
import numpy
import h5py
import pprint
def read_fields_from_hdf5(filepath, gridpath, names=[]):
fields = {}
f = h5py.File(filepath, 'r')
fg = h5py.File(g... |
{
'name': 'Aeroo Reports',
'version': '1.1',
'category': 'Generic Modules/Aeroo Reporting',
'description': """
Aeroo Reports for OpenERP is a comprehensive reporting engine based on Aeroo Library.
Report templates can be created directly in of following formats:
========================================... |
"""Generated client library for container version v1beta1."""
from googlecloudapis.apitools.base.py import base_api
from googlecloudapis.container.v1beta1 import container_v1beta1_messages as messages
class ContainerV1beta1(base_api.BaseApiClient):
"""Generated client library for service container version v1beta1.... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import str
import uuid
from datetime import datetime
from typing import Any
from typing import Dict
from typing import Text
from typing import List
from ra... |
from datetime import date, datetime
import calendar
import unittest
from google.appengine.api.search import GeoPoint
from search import errors
from search import fields
from search import timezone
class Base(object):
def new_field(self, field_class, **kwargs):
f = field_class(**kwargs)
f.name =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('instagram_api', '0010_auto_20160212_1602'),
]
operations = [
migrations.AlterField(
model_name='media',
... |
import requests
import uuid
import logging
import json
from django.template.defaultfilters import slugify
from geoserver.catalog import Catalog
from geoserver.catalog import FailedRequestError
from geonode import GeoNodeException
from geonode.layers.models import Layer
from geonode.layers.utils import get_valid_name... |
import CursesTimer
import Audio
import Utils
import database
import datetime
class Pomodoro:
'''
pomodoro関連
'''
def __init__(self):
self.db = database.database()
self.t = CursesTimer.CursesTimer()
self.u = Utils.Utils()
self.NofPomodoro = 4 #休憩まで何回ポモドーロするか
... |
import nose
from angr import SimState, SIM_PROCEDURES
FAKE_ADDR = 0x100000
def test_calling_conventions():
#
# SimProcedures
#
from angr.calling_conventions import SimCCCdecl, SimCCMicrosoftFastcall
args = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, 100000, 1000000, 2000000, 14, 15, 16 ]
arches = [
... |
"""Python Logger tests
$Id$
"""
import unittest
import logging
from zope.interface.verify import verifyObject
class HandlerStub(logging.Handler):
last_record = None
def emit(self, record):
self.last_record = record
class TestPythonLogger(unittest.TestCase):
name = 'test.pythonlogger'
de... |
from pycp2k.inputsection import InputSection
class _each149(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Meta... |
from typing import Optional
from src.model.Term import Term
from src.model.Sort import Sort
class L4TypeError(Exception):
def __init__(self, msg:str, term:Optional[Term] = None, filename: Optional[str] = None) -> None:
self.term = term
self.msg = msg
self.filename = filename
def __str... |
################################
################################
from MEHI.paralleled.segmentation import *
from MEHI.paralleled.IO import load_tiff
from test_utils import PySparkTestCase
import numpy as np
from nose.tools import assert_equals
import os
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = o... |
import yaml
import os
import re
import shutil
import subprocess
import hashlib
from copy import deepcopy
import CreateSectionTable
TEST_CASE_PATTERN = {
"initial condition": "UTINIT1",
"SDK": "ESP32_IDF",
"level": "Unit",
"execution time": 0,
"auto test": "Yes",
"category": "Function",
"t... |
from setuptools import setup
try:
import pygtk
except ImportError:
print 'You need to install pyGTK to use this'
exit()
def readme():
with open('README.md') as f:
return f.read()
setup(
name='pysugarscape',
version='0.1.0',
description="A simple agent-based implementation of Epste... |
"""Module to convert Python's native typing types to Beam types."""
from __future__ import absolute_import
import collections
import typing
from builtins import next
from builtins import range
from apache_beam.typehints import typehints
# Describes an entry in the type map in convert_to_beam_type.
# match is a func... |
# -*- coding: iso-8859-1 -*-
"""
Creole wiki markup parser
See http://wikicreole.org/ for latest specs.
Notes:
* No markup allowed in headings.
Creole 1.0 does not require us to support this.
* No markup allowed in table headings.
Creole 1.0 does not require us to support this.
* N... |
"""provides runtime services for templates, including Context, Namespace, and various helper functions."""
from mako import exceptions, util
import inspect, sys
class Context(object):
"""provides runtime namespace, output buffer, and various callstacks for templates."""
def __init__(self, buffer, **data):
... |
"""
Django settings for reports project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import date
from datetime import datetime
from datetime import timedelta
import dateparser
from dateparser.search import search_dates
from EmeraldAI.Logic.Singleton import Singleton
class DateUtil(object):
__metaclass__ = Singleton
def __init__(self):
... |
#!/usr/bin/env python
from collections import OrderedDict
class PduDecodingException(Exception):
pass
class Bits(object):
def __init__(self, bits):
self.bits = bits
def __repr__(self):
return "%s('%s')" % (self.__class__.__name__, self.bits)
def read(self, size):
res, self... |
class Printer(object):
def __init__(self, begin, end):
self.begin = begin
self.end = end
def print_result(self, seq, results, out):
matched = [False] * len(seq)
for result in results:
for i in range(result['begin'], result['end']):
matched[i] = True
... |
import collections
import datetime
import gzip
import ipaddress
import logging
import os
import shutil
import sys
import tempfile
import threading
import geoip2.database
import geoip2.errors
import requests
__all__ = ['init_database', 'lookup', 'GeoLocation']
DB_DOWNLOAD_URL = 'http://geolite.maxmind.com/download/ge... |
from oslo_log import versionutils
from oslo_policy import policy
from octavia.common import constants
deprecated_context_is_admin = policy.DeprecatedRule(
name='context_is_admin',
check_str='role:admin or '
'role:load-balancer_admin'
)
deprecated_observer_and_owner = policy.DeprecatedRule(
n... |
import os
import shutil
import tempfile
from contextlib import contextmanager
from errno import ENOENT, EEXIST
import hashlib
import sys
from os.path import abspath, realpath, join as joinpath
import platform
import re
import six
from conans.util.log import logger
import tarfile
import stat
def make_read_only(path):
... |
import sys
import pygame
from yamlui.parsing import parse_children
from yamlui.util import create_surface
from yamlui.widget import Widget
class Window(Widget):
"""A window to display on screen.
This window is the place where the rest of the UI is drawn.
Example yaml definition::
- object: w... |
"""
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
'''@file multi_target_dummy_processor.py
contains the MultiTargetDummyProcessor class'''
import os
import subprocess
import StringIO
import scipy.io.wavfile as wav
import numpy as np
import processor
from nabu.processing.feature_computers import feature_computer_factory
import pdb
class MultiTargetDummyProcessor(pro... |
import pytest
import numpy as np
from gwydion.stats import Poisson
from gwydion.exceptions import GwydionError
SEED = 31415927
TOLERANCE = 0.00001
def test_poisson_creation():
poisson = Poisson()
assert poisson
def test_poisson_non_random():
poisson = Poisson(rand=None, lam=2, xlim=(0,10), N=7)
x,... |
import cPickle as pickle
import numpy as np
from collections import defaultdict
from netCDF4 import Dataset
from scipy.interpolate import griddata
from datetime import datetime
import pdb
lon_high = 101.866
lon_low = 64.115
lat_high= 33.
lat_low=-6.79
#lon_high = 116
#lon_low = 30.5
#lat_high= 40
#lat_low=-11.2... |
from rest_framework import serializers as ser
from rest_framework import exceptions
from modularodm.exceptions import ValidationValueError
from framework.auth.core import Auth
from website.models import Node, User
from website.exceptions import NodeStateError
from website.util import permissions as osf_permissions
... |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils import add_days, cint, cstr, flt, getdate, nowdate, rounded
from frappe.model.naming import make_autoname
from frappe import msgprint, _
from erpnext.setup.utils import get_company_currency
from erpnext.h... |
"""
Author: Bhavana Jonnalagadda, 2016
"""
import random
import math
"""
OUTLINE FOR 3RD TERM:
NeuralNetwork:
- NetworkRunner:
- make flexible for assigning activation, regularization, optimizer, metrics all in general
- Hyperparamter training!!
- RecurrentNode:
- Get working!
- N... |
# -*- coding: utf-8 -*-
""" Python KNX framework
License
=======
- B{PyKNyX} (U{https://github.com/knxd/pyknyx}) is Copyright:
- © 2016-2017 Matthias Urlichs
- PyKNyX is a fork of pKNyX
- © 2013-2015 Frédéric Mantegazza
This program is free software; you can redistribute it and/or modify
it under the terms ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from shop.cart.cart_modifiers_base import BaseCartModifier
from catalog.models import Modifier
class CatalogCartModifier(BaseCartModifier):
def process_cart_item(self, cart_item, request):
"""
Loops through extra cart item fields an... |
"""
# sbpca - subband principal component analysis - core components
# split out of SAcC.py
#
# 2013-09-19 Dan Ellis <EMAIL>
"""
import math
import numpy as np
import scipy.signal
# c extension to calculate autocorr
try:
import _autocorr_py
autoco_ext = True
except ImportError:
autoco_ext = False
#autoc... |
# coding: utf-8
import logging
from functools import wraps
from ppyt.exceptions import NoDataError
logger = logging.getLogger(__name__)
def handle_nodataerror(nodata_return):
"""NoDataErrorを処理するデコレータです。
このデコレータをつけておくと、内部でNoDataErrorが発生したときに[nodata_return]が返るようになります。
Args:
nodata_return: NoDataEr... |
import pytest
import raccoon as rc
def test_columns():
actual = rc.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}, index=['a', 'b', 'c'], columns=['b', 'a'])
names = actual.columns
assert names == ['b', 'a']
assert isinstance(names, list)
# test that a copy is returned
names.append('bad')
as... |
from anthill.common import access
from anthill.common.database import DatabaseError
from anthill.common.model import Model
class NoScopesFound(Exception):
pass
class ScopesCorrupterError(Exception):
pass
class AccessModel(Model):
"""
A model representing a simple role: to clarify whenever an accou... |
"""Distribution Strategy library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.python.distribute import cluster_resolver
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.dis... |
#/usr/bin/python
#-*- coding:utf-8 -*-
from bs4 import BeautifulSoup
import requests
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
headers = {
'Accept': '*/*',
'Origin': 'https://www.zhihu.com',
'X-Requested-With': 'XMLHttpRequest',
'X-Xsrftoken': '00bdcdb1f45057399a176c0e3ed64963... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mayaviviewerwidget.ui'
#
# by: pyside-uic 0.2.13 running on PySide 1.1.0
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.... |
months = [
'jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec'
]
monthsLengths = {
'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30,
'may': 31, 'jun': 30, 'jul': 31, 'aug': 31,
'sep': 30, 'oct': 31, 'nov': 30, 'dec': 31
}
daysOfWeek = {
'mon': 0, 'tue': 1, 'wed':... |
from imagekit.lib import Image, ImageColor, ImageEnhance
class ProcessorPipeline(list):
"""
A :class:`list` of other processors. This class allows any object that
knows how to deal with a single processor to deal with a list of them.
For example::
processed_image = ProcessorPipeline([Processo... |
__all__ = ['EditTextDialog']
# imports
## import os, sys, Tkinter
# PySol imports
# Toolkit imports
from tkwidget import MfxDialog
# ************************************************************************
# *
# ************************************************************************
class EditTextDialog(MfxDialog... |
#!/usr/bin/env python
import argparse
from utils import get_value_from_keycolonvalue_list, ensure_dir
import re
usage = """
- Adds 'intragenic'/'intergenic' label info for mirna
- label 'NA' is when mirna_start and mirna_stop is
not found in the info column
- label 'unknown' is when mirna_start and mirna_stop is
... |
# coding=utf-8
"""Tools for GIS operations."""
import logging
import os
from qgis.core import (
QgsProject,
QgsRasterLayer,
QgsVectorLayer,
QgsDataSourceUri,
QgsLayerDefinition
)
from safe.common.exceptions import InvalidLayerError
from safe.definitions.constants import (
VECTOR_DRIVERS,
... |
from __future__ import absolute_import
import os, traceback, threading, shlex
from . import controller
class ScriptError(Exception):
pass
class ScriptContext:
def __init__(self, master):
self._master = master
def log(self, message, level="info"):
"""
Logs an event.
... |
import re
import subprocess
import sublime_plugin
import sublime
class JsBeautifierCommand(sublime_plugin.TextCommand):
@classmethod
def looks_likes_html(cls, source):
"""Determine if a code block looks like HTML
https://github.com/einars/js-beautify/blob/v1.4.2/index.html#L262-L269
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import threading
import sys
import random
import re
from math import exp
from PySide import QtGui, QtCore
import sys
class Example(QtGui.QWidget):
def getWeights(pythonisdumbdumb,x):
f = open("./../Data/Model.NN","r")
lines = f.readlines();
... |
#!/usr/bin/python
"""
This scripts, based on a source file, inspect a set of dirs and fetch files
required by this source file in order of preference. In case of duplicates,
more important files are fetched in order of preference from left ro right
"""
from itertools import ifilter
from shutil import copy
from md5 i... |
"""
Command line interface tools.
"""
from .. import SlipyError
from .Options import Options, OptionsError
class CommandError(SlipyError):
"""
Exception specific to Command module.
"""
pass
def Parse( clargs, **kwargs ):
"""
Parse command line arguments, `clargs` (i.e., sys.argv).
"""
if type(clargs) is not ... |
import glob
import subprocess
import sys
import os
import re
base_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
# Look for a [Rr]elease build.
perftests_paths = glob.glob('out/*elease*')
metric = 'wall_time'
max_experiments = 10
binary_name = 'angle_perftests'
if sys.platform... |
import numpy as np
block="""37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418... |
import os
import unittest
import decimal
from lxml import etree
from apps.sepa.sepa import SepaAccount, SepaDocument
from .base import SepaXMLTestMixin
class ExampleXMLTest(SepaXMLTestMixin, unittest.TestCase):
""" Attempt to test recreating an example XML file """
def setUp(self):
super(ExampleXML... |
"""
Copyright 2014-2021 Vincent Texier <<EMAIL>>
DuniterPy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DuniterPy is distributed in the... |
import logging
import re
from os import environ
from os.path import exists
from configparser import ConfigParser
from types import GeneratorType
# will be overriden via debian_defaults file few lines later
SUPPORTED = [(3, 4),]
DEFAULT = (3, 4)
RANGE_PATTERN = r'(-)?(\d\.\d+)(?:(-)(\d\.\d+)?)?'
RANGE_RE = re.compile(R... |
#!/home/cdieken/applied_python/bin/python
import telnetlib
import time
import socket
import sys
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_very_eager()
def login(remote_conn, username... |
# -*- coding: utf-8 -*-
import libsbml
import os
import pickle
import urllib
import urllib2
import re
import sys
PREFIXES = [ "acetylated ", "activated ", "associated ", \
"bound ", \
"catabolized ", "catalyzed ", "converted ", \
"deacetylated ", "degradated ", "demethylated ", "dephosporylated ", "deubiqu... |
import os
import stat
import logging
from .configobj import ConfigObj, ConfigObjError
from .validate import get_validator, cfg
from .errors import ConfigError
logger = logging.getLogger(__name__)
DEFAULT_FILENAME = '.signacrc'
CONFIG_FILENAMES = [DEFAULT_FILENAME, 'signac.rc']
HOME = os.path.expanduser('~')
CONFIG_P... |
import os
import json
from ninja_ide import resources
from ninja_ide.core import settings
from ninja_ide.tools.logger import NinjaLogger
logger = NinjaLogger('ninja_ide.tools.json_manager')
def parse(descriptor):
try:
return json.load(descriptor)
except:
logger.error("The file couldn't be p... |
import config
import pymysql.cursors
import html
connection = pymysql.connect(host='localhost',
user='root',
password=config.MYSQL_SERVER_PASSWORD,
db='youtubeProjectDB',
charset='utf8mb4', # dea... |
import random
import collections
class Player:
def __init__(self, name, game):
self.name = name
self.game = game
self.coins = 2
self.assign_roles(2)
def get_role(self, role = None):
if role is None:
role = self.game.deck.deal()
self.__roles[role] +... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect(databaseName="tournament"):
"""Connect to the PostgreSQL database. Returns a database connection and cursor."""
try:
conn = psycopg2.connect("dbname={}".format(databaseName))
cur =... |
"""
Compiler for a regular grammar.
Example usage::
# Create and compile grammar.
p = compile('add \s+ (?P<var1>[^\s]+) \s+ (?P<var2>[^\s]+)')
# Match input string.
m = p.match('add 23 432')
# Get variables.
m.variables().get('var1') # Returns "23"
m.variables().get('var2') # Returns... |
import time
import numpy as np
import logging
logger = logging.getLogger(__file__)
class StereoMRF(object):
"""
Markov Random Field with loopy belief propagation (min-sum message passing).
"""
def __init__(self, dim, n_levels):
self.n_levels = n_levels
self.dimension = (n_levels,) + ... |
# -*- coding: utf-8 -*-
"""
Sycamore - Spelling Action
Word adding based on code by Christian Bird <<EMAIL>>
This action checks for spelling errors in a page using one or several
word lists.
Sycamore looks for dictionary files in the directory "dict" within the
Sycamore package direct... |
from .state import *
from .runner import *
from .test import *
from .suite import *
from .loader import *
from .fixture import *
from .config import *
from main import main
#TODO Remove this awkward bootstrap
#FIXME
from gem5 import *
#TODO Remove this as an export, users should getcwd from os
from os import getcwd |
import RPi.GPIO as io
io.setwarnings(False)
io.setmode(io.BCM)
class Device:
def __init__(self,config):
self.config = config
for device in self.config['gpioPINs']['unavailable']:
io.setup(int(device),io.OUT)
io.output(int(device),False)
for device in self.config['gpioPINs']['available']:
io.setup(int... |
from openstack.object_store.v1 import container as _container
from openstack.tests.functional import base
class TestContainer(base.BaseFunctionalTest):
def setUp(self):
super(TestContainer, self).setUp()
self.require_service('object-store')
self.NAME = self.getUniqueString()
cont... |
import datetime
import uuid
from shoop.simple_cms.models import Page
from shoop.utils.i18n import get_language_name
CONTENT = """
# Bacon ipsum dolor amet doner ham brisket
Pig tenderloin hamburger sausage pork shankle.
Shoulder chicken alcatra boudin.
[Rump short ribs porchetta shankle bacon.](https://baconipsum.com... |
import os
import time
import subprocess
import commands
from random import randint
from easyprocess import Proc
from threading import Thread
def infraestruturar(wlan):
print "INICIANDO PONTO DE ACESSO"
os.system("ifconfig {0} 10.10.0.1/24".format(wlan))
os.system("service isc-dhcp-server start")
os.system("echo 1... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
# from django.db.models.signals import post_save
from user_profile.models import Manager, Profile_abstract
from survey.models import Survey
from dialer_gateway.models import Gateway
from sms.... |
from copy import deepcopy
from random import randint
from process import (
FirstProcessAllocationStrategy,
SecondProcessAllocationStrategy,
ThirdProcessAllocationStrategy,
Process
)
def test():
params = {
'num': 4,
'proc_threshold': 80,
'proc_threshold_min': 20,
'qu... |
import json
import logging
from typing import Any, Dict, Set
from sqlalchemy.orm import Session
from superset.models.dashboard import Dashboard
logger = logging.getLogger(__name__)
JSON_KEYS = {"position": "position_json", "metadata": "json_metadata"}
def find_chart_uuids(position: Dict[str, Any]) -> Set[str]:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This test checks the overall state update
"""
import os
import json
import time
import shlex
import subprocess
import copy
import requests
import unittest2
from alignak_backend.livesynthesis import Livesynthesis
class TestOverallState(unittest2.TestCase):
"""This... |
from __future__ import division
import random
import argparse
import sys
# Based on: http://pythonforbiologists.com/books
parser = argparse.ArgumentParser()
parser.add_argument("input", help="input FASTQ filename")
parser.add_argument("output", help="output FASTQ filename")
parser.add_argument("-f", "--fraction", typ... |
import tkinter as tk
from tkinter import Label
from src.Clock import CTime
from src.Clock import WeekDays
from src.lang import TM_Lang
class Model():
def __init__(self, TManager, title, width, height, clockFont):
root = tk.Tk()
gem = str(width) + "x" + str(height)
root.geometry(gem)
self.TimeManager = TManage... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 24 18:21:39 2017
@author: Alexander
"""
# Twitter Bot
# Imports
# prepare for Python version 3x features and functions
from __future__ import division, print_function
from time import sleep
import tweepy
import sys
import requests
import json
import ran... |
"""Domain objects for learner progress."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
import python_utils
class LearnerProgress(python_utils.OBJECT):
"""Domain object for the progress of the learner... |
from qipy import *
import datetime
import requests as req
import json
from dateutil import parser
import matplotlib.pyplot as plt
#print method for returned events
def dumpEvents(foundEvents):
print "Total Events found: "+ str(len(foundEvents))
for i in foundEvents:
print i
authItems = {'resource'... |
import uuid
from werkzeug.urls import url_join
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class AdyenAccount(models.Model):
_inherit = 'adyen.account'
store_ids = fields.One2many('adyen.store', 'adyen_account_id')
terminal_ids = fields.One2many('adyen.terminal', ... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_duration,
)
class RtlNlIE(InfoExtractor):
IE_NAME = 'rtl.nl'
IE_DESC = 'rtl.nl and rtlxl.nl'
_VALID_URL = r'''(?x)
https?://(?:(?:www|static)\.)?
(?:
... |
from __future__ import unicode_literals
from django.db import models
from django import forms
from django.utils.translation import ugettext as __
from django.conf import settings
import traceback, sys, requests
from papers.models import *
class DepositError(Exception):
"""
The exception to raise when someth... |
#!/usr/bin/env python
import socket, sys
from thread import *
from time import sleep
from decimal import Decimal, getcontext
if len(sys.argv) != 4:
print "Usage: {} <precision> <iterations> <port>".format(sys.argv[0])
sys.exit()
HOST, PORT = '', int(sys.argv[3])
def printerr(thing):
sys.stderr.write(thin... |
"""Utilities for managing the config file"""
config_stanzas = {
'AcuRite' :
"""
[AcuRite]
# This section is for AcuRite weather stations.
# The station model, e.g., 'AcuRite 01025' or 'AcuRite 02032C'
model = 'AcuRite 01035'
""",
'CC3000' :
... |
import os
import decorator
from oslo_utils import strutils
from rally.common import fileutils
from rally.common.i18n import _
from rally import exceptions
ENV_DEPLOYMENT = "RALLY_DEPLOYMENT"
ENV_TASK = "RALLY_TASK"
ENV_VERIFICATION = "RALLY_VERIFICATION"
ENVVARS = [ENV_DEPLOYMENT, ENV_TASK, ENV_VERIFICATION]
MSG_MI... |
"""Post list directive for reStructuredText."""
from __future__ import unicode_literals
import os
import uuid
import natsort
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from nikola import utils
from nikola.plugin_categories import RestExtension
from nikola.packages.datecond imp... |
import numpy as np
import pyparsing as pa
import matplotlib.pyplot as plt
# enable catching
# pa.ParserElement.enablePackrat()
# Parser
floatNumber = pa.Regex(r'(\-)?\d+(\.)(\d*)?([eE][\-\+]\d+)?')
natural = pa.Word(pa.nums)
def parse_file(file_name):
parser = generate_parser()
xs = parser.parseFile(file_na... |
"""Support for Mailgun."""
import hashlib
import hmac
import json
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_API_KEY, CONF_DOMAIN, CONF_WEBHOOK_ID
from homeassistant.helpers import config_entry_flow
_LOGGER = logging.getLogger(__n... |
# -*- coding: utf-8 -*-
from functools import wraps
from collections import defaultdict
from cStringIO import StringIO
import unicodecsv
from flask import g, current_app, abort, render_template
from lastuser_core.models import db, User, USER_STATUS
from .. import lastuser_ui
def requires_dashboard(f):
"""
D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.