content stringlengths 4 20k |
|---|
# coding=utf-8
import pandas as pd
import numpy as np
train_df = pd.DataFrame(columns=['x1', 'x2', 'y1', 'y2', 'label'], dtype=int)
test_df = pd.DataFrame(columns=['x1', 'x2', 'y1', 'y2', 'label'], dtype=int)
annotation = '/home/dujiajun/thyroid nodule/annotation/position&size&TIRADS/benign tumour.csv'
df = pd.read... |
import arrow
from decimal import Decimal
class BaseSerializer(object):
def deserialize(self, method_name, value):
if hasattr(self, method_name):
return getattr(self, method_name)(value)
raise NotImplementedError("Desserialization method not found")
def serialize_dict(self, data):... |
import json
import logging
from queue import Queue
from core.entities import Base
from sqlalchemy import Column, String, Boolean, orm
from core.NodeFactory import NodeFactory
class Scenario(Base):
__tablename__ = 'scenarios'
_config = None
name = Column('name', String(32), primary_key=True)
descript... |
import time
from unittest import TestCase
from astrolabe import Interval
class IntervalTest(TestCase):
def test_started(self):
interval = Interval()
self.assertFalse(interval.started)
interval.start()
self.assertTrue(interval.started)
def test_stopped(self):
interval... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks
from fbmc_vector_reshape_vcvc import fbmc_vector_reshape_vcvc
import random
class qa_fbmc_vector_reshape_vcvc (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test... |
#!/usr/bin/env python
"""Chainer example: train a multi-layer perceptron on MNIST
This is a minimal example to write a feed-forward net.
"""
from __future__ import print_function
import argparse
import numpy as np
import six
import chainer
from chainer import computational_graph
from chainer import cuda
import chai... |
QOS_QUEUE = 'QoS Queue'
NET_EXTERNAL = 'router:external'
VNIC_INDEX_EXT = 'VNIC Index'
DNS_INTEGRATION = 'DNS Integration'
MULTI_NET_EXT = 'Multi Provider Network'
FIP_PORT_DETAILS = 'Floating IP Port Details Extension'
SUBSTR_PORT_FILTERING = 'IP address substring filtering'
PORT_BINDING = 'Port Binding'
PORT_BINDING_... |
__author__ = "David Rusk <<EMAIL>>"
import os
from src.daomop import storage
from progress import LocalProgressManager, VOSpaceProgressManager
def get_context(directory, userid=None):
if directory.startswith("vos:"):
return VOSpaceWorkingContext(directory, userid=userid)
else:
return LocalDi... |
from pyanaconda.installclass import BaseInstallClass
from pyanaconda.product import productName
from pyanaconda import network
from pyanaconda import nm
from pyanaconda.i18n import N_
class FedoraBaseInstallClass(BaseInstallClass):
# name has underscore used for mnemonics, strip if you dont need it
id = "fedor... |
from datetime import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from datetime import datetime, timedelta
from ..models import Assignment, AssignmentGroup, Delivery, Deadline
from ..testhelper import TestHelper
from ..models.... |
"""
Copyright (c) 2017, Michael Sonntag (<EMAIL>)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted under the terms of the BSD License. See
LICENSE file in the root of the project.
"""
import os
import imghdr
import yaml
class BulkRename:
"""
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow_examples.lite.model_maker.core import compat
from tensorflow_examples.lite.model_maker.core.task import question_answer_test
class QuestionAnswerV1Test(question_answer_... |
__author__ = 'Henri Kivelä <<EMAIL>>, Lasse Häll <<EMAIL>>'
import os
import sys
import time
import subprocess
import unittest
from appium import webdriver
from selenium.common.exceptions import WebDriverException
import pprint
import tempfile
def log(msg):
header = ''
if os.environ.get('APPIUM_DEVICE'):
... |
class Node1D(object):
"""docstring for MeshNode"""
def __init__(self, x1, index):
self.x1 = x1
self.index = index
def __eq__(self, other):
return self.index == other.index
def __hash__(self):
return hash(repr(self))
def __repr__(self):
return "Node1D('{} -... |
import os
request = context.REQUEST
response = request.RESPONSE
session = request.SESSION
if context.REQUEST['data'] != '':
dat_inicio_sessao = context.REQUEST['data']
pauta = [] # lista contendo a pauta da ordem do dia a ser impressa
# converte data para formato yyyy/mm/dd
data = context.pysc.data_c... |
"""
Parse docker timestamps
"""
import re
import datetime
# This class inherits a LOT of public methods, but most of what
# appears here is all 'behind the scenes' stuff for producing
# immutable instances.
class DockerTime(datetime.datetime): # pylint: disable=R0903
"""
Immutable Docker specialized zulu-t... |
from core.utils import *
from copy import deepcopy
hidden = True
def process(m):
if has_tag(m.receiver.id, 'resend:?') or has_tag(m.receiver.id, 'fwd:?'):
id = str(m.receiver.id)
for tag in tags.list[id]:
if tag.startswith('resend:'):
cid = tag.split(':')[1]
... |
import itertools
import time
import hyperframe.frame
from hpack.hpack import Encoder, Decoder
from mitmproxy.net.http import http2
import mitmproxy.net.http.headers
import mitmproxy.net.http.response
import mitmproxy.net.http.request
from mitmproxy.types import bidi
from .. import language
class TCPHandler:
d... |
import mock
from oslotest import base
from gluebox.utils.reno import RenoManager
class TestRenoManager(base.BaseTestCase):
"""Test case for reno utils."""
def setUp(self):
super(TestRenoManager, self).setUp()
def test_get_current_version(self):
manager = RenoManager('test')
mana... |
# These things are comments. They dont get run as code
# and are just to explain whats happening
# Import os so we can clear screen
import os
# DEFINE FUNCTIONS - have to be defined above where you call them
def showMap():
print "You have peaked at the secret map!"
print "It shows you the choices from each r... |
from __future__ import absolute_import
import cStringIO
import types
__name__ = 'pyrehol'
__author__ = 'James Brown <<EMAIL>>'
version_info = (0, 3)
__version__ = '.'.join(map(str, version_info))
INDENT_CHAR = ' '
PREDEFINED_SERVICES = frozenset([
'any', 'anystateless', 'all',
'AH', 'apcupsd', 'apcupsdnis'... |
from Quartz import *
from AppKit import NSEvent
from base import PyMouseMeta, PyMouseEventMeta
pressID = [None, kCGEventLeftMouseDown, kCGEventRightMouseDown, kCGEventOtherMouseDown]
releaseID = [None, kCGEventLeftMouseUp, kCGEventRightMouseUp, kCGEventOtherMouseUp]
class PyMouse(PyMouseMeta):
def press(self, x, ... |
"""
This module provides a CLI that interacts with cloud
repositories such as GitHub.
"""
import click
from datetime import datetime
import pprint
import github_api
from Models import GitHubCredentials
newCredentials = GitHubCredentials.GitHubCredentials()
@click.group()
def repository_cli():
pass
# get_user_... |
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
import cocos
from cocos.director import director
from cocos.actions import *
from cocos.layer import *
from cocos.scenes import *
from cocos.sprite import *... |
"""
GMP URL streams.
Test stream: http://198.154.106.104:8496/stream
"""
import wx, application, logging, functions
from wx.lib.sized_controls import SizedFrame
from sound_lib.stream import URLStream
from sound_lib.main import BassError
logger = logging.getLogger('URL Frame')
class URLFrame(SizedFrame)... |
# parse slack messages into structured data.
# example:
# mentor_paulcutsinger [11:23 AM]
# yes @andrew, we have a demo device that you can use during demo day. I'll be around from 6pm on so you can practice hooking up to it. Other folks will need it too so we'll have to share it :smile:
# we want to parse... |
'''
Timeline - An AS3 CPPS emulator, written by dote, in python. Extensively using Twisted modules and is event driven.
Penguin is a extension of LineReceiver, protocol. Implements the base of Client Object
'''
from Timeline.Server.Constants import TIMELINE_LOGGER, PACKET_TYPE, PACKET_DELIMITER, WORLD_SERVER, AS3... |
from ..synchandler import *
from ..debugtools import *
from algorithm import *
from numpy import zeros, ones, inf, tile,\
nonzero, isscalar, maximum, minimum, kron, squeeze
from numpy.random import rand
__all__ = ['PSO']
class PSO(OptimizationAlgorithm):
"""
Particle Swarm Optimization algorith... |
# http://www.tangjikai.com/algorithms/leetcode-207-208-course-schedule-i-ii
# If node v has not been visited, then mark it as 0.
# If node v is being visited, then mark it as -1. If we find a vertex marked as -1 in DFS, then there is a cycle.
# If node v has been visited, then mark it as 1. If a vertex was marked as... |
import pygame, math
from pygame.gfxdraw import *
from pygame.font import *
from pygame.locals import *
class Text():
def __init__(self, x, y, fcolor=(255,255,255), bcolor=(0,0,0)):
self.x = x
self.y = y
self.bcolor = bcolor
self.fcolor = fcolor
self.font = pygame.font.SysFont("", 24)
def write(self, txt)... |
# -*- coding: utf-8 -*-
# Validador Fornecedor
Fornecedor.razao_social.requires = [IS_NOT_EMPTY(error_message='Informe a Razão Social'), IS_UPPER()]
Fornecedor.nome.requires = IS_NOT_EMPTY(error_message='Informe o nome do Fornecedor')
Fornecedor.cnpj.requires = [IS_CNPJ(), IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'forneced... |
"""A simple wrapper to demonstrate basic mql reads and writes."""
__author__ = "<EMAIL> (Brendan Neutra)"
import json
from absl import app
from absl import flags
from collections import OrderedDict
from pymql import MQLService
from pymql.mql.graph import TcpGraphConnector
FLAGS = flags.FLAGS
flags.DEFINE_string(
... |
# -*- coding: utf-8 -*-
import os
import subprocess
import psutil
from datetime import datetime
from flask import Blueprint, render_template, redirect, url_for, flash
from flask.ext.babel import gettext
mod = Blueprint('system', __name__)
@mod.route('/')
def index():
uptime = datetime.now() - datetime.fromtimesta... |
# gets the first link on any webpage
def get_next_target(page):
copy = page
repl = ['= ', ' =', ' = ']
for i in range(0, len(repl)):
copy = copy.replace(repl[i], "=")
first_link_start = copy.find("<a")
if (first_link_start == -1):
return None
else:
first_url_start = copy.find("href=", first_l... |
import dolfin as df
import os
import numpy as np
from . import *
from common.io import mpi_is_root
from common.bcs import Fixed, NoSlip, FreeSlip, Slip, ContactAngle
from common.functions import max_value
__author__ = "Gaute Linga and Asger Bolet"
'''
Control paremetors in BERNAISE units
Potential drop over the elec... |
"""
Support for Prometheus metrics export.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/prometheus/
"""
import logging
import voluptuous as vol
from aiohttp import web
from homeassistant.components.climate import ATTR_CURRENT_TEMPERATURE
from homeas... |
import functools
import logging
from ..decorators.decorator import RequestResponseDecorator
from ..decorators.security import (get_apikeyinfo_func, get_basicinfo_func,
get_bearerinfo_func,
get_scope_validate_func, get_tokeninfo_func,
... |
# -*- coding: UTF-8
"""
Test issue #458:
Traceback (most recent call last):
File "/usr/local/bin/behave", line 11, in <module>
sys.exit(main())
File "/Library/Python/2.7/site-packages/behave/__main__.py", line 123, in main
print(u"Exception %s: %s" % (e.__class__.__name__, text))
UnicodeEncodeError: 'ascii... |
import sys
import json
from copy import copy
# Django Libraries
from django.db import models
class APIExtractor(object):
"""
Class object used to extract values from the database internal to the
APIQuerySet object.
"""
def __init__(self):
# Object manager
self._objects = O... |
import django
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Bartosz Nowak', '<EMAIL>'),
)
MANAGERS = ADMINS
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
DATABASES = {
'default': {
'ENGINE': '... |
import byteplay
import inspect
def ___cstack():
if 'stack' in locals():
___stack___ = list(locals()['stack'])
else:
___stack___ = []
return ___stack___
___stack_code = list(filter(lambda x: x[0] != byteplay.SetLineno,
(byteplay
.Co... |
from wpilib.command import Subsystem
from wpilib import RobotDrive
from wpilib import LiveWindow
from wpilib import PIDController
from wpilib.interfaces import PIDOutput
from wpilib import CANTalon
from wpilib import SmartDashboard
from utils.bno055 import BNO055
from commands.driveTrainCmds import JoystickDrive... |
# Codes for the analyses in Fig 3b.
import math
# Read the HGMD mutations and store disease-causing mutations in a dictionary.
noncoding_mut_count = 0
noncoding_mut_dict = {}
disease_list = []
with open("regulatory-2015.2.txt") as hgmd_file:
hgmd_reader = hgmd_file.readlines()
del hgmd_reader[0]
for row ... |
# -*- coding: utf-8 -*-
import pytest
import requests
try:
# Faster, C-ext
from cStringIO import StringIO
except ImportError:
# Slower, pure python
from StringIO import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from p... |
import unittest, os
import itertools
from ecl.util.test import TestAreaContext
from tests import ResTest
from tests.utils import tmpdir
from res.test import ErtTestContext
from ecl.util.util import BoolVector
from res.enkf import ResConfig, EnKFMain, EnkfFs, ErtRunContext
from res.enkf.enums import EnKFFSType, EnkfR... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from jinja2 import Template
CREATE_INCIDENT = Template("""
*INCIDENT CREATED!*
This incident is now being tracked and documented, but we still need your help!
When you have a moment, please use these commands to provide more information:
```
@commander set title <title>... |
class SolutionMemo(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
N = len(nums)
maxsum = [0] * (N+1)
totalSum = 0
for i, n in enumerate(nums):
maxsum[i+1] = maxsum[i] + n
totalSum += n
# print maxsum, totalSum
if totalSum % 2 != 0:
return False
findSu... |
"""Just using regular lists and tuples for the things taken care of using
GLM in the original tutorial. Nothing here is complex enough to require resorting
to numpy or another library yet."""
import sys,os,math
import pygame as pg
##import numpy as np
from OpenGL import GL
sys.path.append("..")
sys.path.append("data")... |
from oslo_log import log as logging
import six
from heat.common.i18n import _
from heat.common.i18n import _LW
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support
try:
from pyrax.exceptions impor... |
# -*- coding: utf-8 -*-
import json
import urllib.request
import urllib.parse
import re
class books:
def __init__(self, core, client):
try:
self.apikey = core.readConf("config.googleapikey")
if self.apikey == "":
return
except:
return
co... |
from __future__ import unicode_literals
import json
import os
import shutil
import sys
import tempfile
import unittest
from mozfile.mozfile import NamedTemporaryFile
from mozunit import main
from mach.logging import LoggingManager
from mozbuild.base import (
BadEnvironmentException,
MachCommandBase,
Mo... |
#!/usr/bin/python
#coding=utf-8
import pexpect
import threading
import os
import sys
ip=''
if len(sys.argv) < 5:
print "fileName,oper,ip,user,command"
#class batExec(threading.Thread):
class batExec():
def __init__(self, ssh_mysql, ip ,username, cmd):
self.ssh_mysql = ssh_mysql
self.cmd ... |
import logging
""" Helper module for Analysis classes """
class AnalysisModule(object):
"""
Base class for Analysis modules.
:param trace: input Trace object
:type trace: :mod:`libs.utils.Trace`
"""
def __init__(self, trace):
self._log = logging.getLogger('Analysis')
self.... |
from direct.fsm.FSM import FSM
from direct.showbase.DirectObject import DirectObject
from panda3d.core import PandaNode, PGButton, NodePath, MouseWatcherRegion
class Clickable(FSM, PandaNode, DirectObject):
def __init__(self, name):
FSM.__init__(self, name)
PandaNode.__init__(self, name)
D... |
"""Shared implementation of connections to API servers."""
import json
from pkg_resources import get_distribution
import six
from six.moves.urllib.parse import urlencode # pylint: disable=F0401
import httplib2
from gcloud.exceptions import make_exception
API_BASE_URL = 'https://www.googleapis.com'
"""The base of ... |
try:
import ovirtsdk4 as sdk
import ovirtsdk4.types as otypes
except ImportError:
pass
from ansible.module_utils.ovirt import *
def _search_by_lun(disks_service, lun_id):
"""
Find disk by LUN ID.
"""
res = [
disk for disk in disks_service.list(search='disk_type=lun') if (
... |
# -*- coding: utf-8 -*-
"""
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
"""
from .common import * # noqa
import socket
import os
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool... |
"""Calculate terrain attributes from DEM and other optional inputs for deriving slope position.
Slope, Curvature, RPI, HAND, Hillslope, etc.
@author : Liangjun Zhu
@changelog:
- 15-09-08 - lj - initial implementation.
- 17-07-31 - lj - reorganize and incorporate with pygeoc.
"""
from __future... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import re
import socket
import itertools
def print_board(b):
print("{0:^3}|{1:^3}|{2:^3}".format(b[0], b[1], b[2]))
print("---+---+---")
print("{0:^3}|{1:^3}|{2:^3}".format(b[3], b[4], b[5]))
print("---+---+---")
print("{0:^... |
# -*- coding: utf-8 -*-
import doctest
import logging
import os
import sys
import tempfile
import traceback
import unittest
import tldextract
def _temporary_file():
""" Make a writable temporary file and return its absolute path.
"""
return tempfile.mkstemp()[1]
fake_suffix_list_url = "file://" + os.pa... |
from django import forms
from django.contrib.auth.models import User
from ControlMode.models import ComRoom, Cabinet, Cabinet_inner_IP, Cabinet_outer_IP, Equipments, Customers
class RegisterForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'groups']
class LoginFor... |
from random import randint
import pytest
from pynq import Overlay
from pynq.lib.pmod import Pmod_DevMode
from pynq.lib.pmod import PMODA
from pynq.lib.pmod import PMODB
from pynq.lib.pmod import PMOD_SWCFG_IIC0_TOPROW
from pynq.lib.pmod import PMOD_SWCFG_IIC0_BOTROW
from pynq.lib.pmod import PMOD_SWCFG_DIOALL
from pynq... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
BioDownloader: a Command Line Tool for downloading protein structures,
protein sequences and multiple sequence alignments.
Copyright (C) 2017 Fábio Madeira
This program is free software: you can redistribute it and/or modify
it under the terms of ... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request, FormRequest
from urlparse import urlparse
from collections import OrderedDict
from datetime import date
import time, json, re, csv
class CategoriesOfCompresegurosCom(scrapy.Spider):
name = "categories_of_compreseguros_com"
start_urls = ['https://... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016-2021 Philippe Schmouker, schmouk (at) typee.ovh
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, includi... |
import collections
import copy
import ddt
import mock
from cinder import exception
from cinder import test
from cinder.tests.unit.volume.drivers.netapp.dataontap.client import (
fakes as fake_client)
import cinder.tests.unit.volume.drivers.netapp.dataontap.utils.fakes as fake
import cinder.tests.unit.volume.drive... |
def extract_menu_day_elements(day, parent_element):
return parent_element.find('div', {'id': 'menu-plan-tab' + str(day)})
def extract_menu_item(parent_element):
return parent_element.findAll('div', {'class': 'menu-item'})
def extract_menu_title(parent_element):
menu_title = parent_element.find('h2', {'c... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.CaptchaService import ReCaptcha
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class CrockoCom(SimpleHoster):
__name__ = "CrockoCom"
__type__ = "hoster"
__version__ = "0.19"
__pattern__ = r'http://(?... |
"""Logging fixtures and functions."""
import contextlib
import logging
import logging.handlers
import socket
import pytest
@pytest.fixture(scope='session')
def services_log(worker_id):
"""A services_logger with the worker id."""
handler = None
for kwargs in (dict(socktype=socket.SOCK_RAW), dict(socktype=... |
import numpy as np
from scipy import sparse
from scipy.stats import poisson
from scipy.special import xlogy, gammaln
eps = 1e-10
def zip_ll(data, means, M):
"""
Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (arra... |
import os
import sys
from dev_tools import all_checks, prepared_env
def main():
args = sys.argv
verbose = True
only = [e.split('--only=')[1]
for e in args
if e.startswith('--only=')]
checks = [
all_checks.pylint,
all_checks.typecheck,
all_checks.pytest,... |
import numpy as np
from collections import defaultdict
from enum import Enum
from multiprocessing import cpu_count
from psutil import virtual_memory
import GPUtil
import logging
import datetime
import math
log = logging.getLogger('scanner')
log.setLevel(logging.INFO)
log.propagate = False
if not log.handlers:
cla... |
#!/usr/bin/python
############################################################################################
# Converts sample dumps from HBC into format readable by HBC
############################################################################################
import sys
#########################################... |
"""
Config module with all options
"""
from copy import deepcopy
from pygal.style import Style, DefaultStyle
from pygal.interpolate import INTERPOLATIONS
class FontSizes(object):
"""Container for font sizes"""
CONFIG_ITEMS = []
class Key(object):
_categories = []
def __init__(
self, defau... |
"""
.. _RefKey:
Key action
============================================================================
This section describes the :class:`Key` action object. This
type of action is used for sending keystrokes to the foreground
application. Examples of how to use this class are given in
:ref:`RefKeySpecE... |
#!/usr/bin/env python
'''
Generate trigger function and installation sql statements.
For most basic usage you need only name of the table you
want to be notified on changes.
$ python -m pg_bawler.gen_sql mytable
And pg_bawler will generate plpgsql function code and
create trigger statements. Thus installation sh... |
"""CLI tests for logging.
:Requirement: Logging
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: logging
:TestType: Functional
:CaseImportance: Medium
:Upstream: No
"""
import re
from fauxfactory import gen_string
from robottelo import manifests
from robottelo import ssh
from robottelo.cli.fac... |
import os
import shutil
import subprocess
import tempfile
import pytest
import yaml
thisdir = os.path.dirname(os.path.realpath(__file__))
@pytest.fixture(scope="function")
def tmpdir(request):
tmpdir=tempfile.mkdtemp()
def fin():
shutil.rmtree(tmpdir)
request.addfinalizer(fin)
return tmpdir
... |
import logging
import time
from datetime import datetime, timedelta
from django.conf import settings
from django.db import connection, transaction
import cronjobs
from kitsune.questions import config
from kitsune.questions.models import (
Question, QuestionVote, QuestionMappingType, QuestionVisits)
from kitsune.... |
import asyncio
import feedparser
import html
import logging
import os.path
import pickle
import re
from time import sleep
from pprint import pprint
class DotaFeeder:
DOTA2_BLOG_RSS_URL = "http://blog.dota2.com/feed/"
STEAM_NEWS_JSON_URL = "http://api.steampowered.com/ISteamNews/GetNewsForApp"\
... |
from __future__ import absolute_import, division, print_function
from wtforms import validators
from wtforms.fields import Flags
from wtforms.widgets import (
HTMLString,
HiddenInput,
Select,
TextInput,
html_params,
)
from inspire_schemas.api import load_schema
from inspirehep.modules.forms.field_... |
"""Test RunLast class"""
# ============================================================================
# Imports
# ============================================================================
# Stdlib imports
import asyncio
from collections import defaultdict
# Third-party imports
import pytest
# Local imports
fr... |
"""Defines observable events in PerfKitBenchmarker.
All events are passed keyword arguments, and possibly a sender. See event
definitions below.
Event handlers are run synchronously in an unspecified order; any exceptions
raised will be propagated.
"""
from blinker import Namespace
_events = Namespace()
initializ... |
"""
Interprets decklists of various formats, and converts it into a usable structure
"""
import re
import xml
from typing import Any, Dict, Tuple
import untangle
from magic import oracle
from magic.models import CardRef, Deck
from shared.pd_exception import InvalidDataException
SectionType = Dict[str, int]
DecklistT... |
from openslides.core.exceptions import ProjectorException
from openslides.core.views import TagViewSet
from openslides.utils.projector import ProjectorElement, ProjectorRequirement
from .models import Assignment, AssignmentPoll
from .views import AssignmentViewSet
class AssignmentSlide(ProjectorElement):
"""
... |
#Jenny Steffens
from Analysis import *
import random, time
def main():
# This list and dictionary are now the default in the Analyzer. They
# do not need to be entered in a driver. However, if the dictionary is updated,
# either do so in Analysis.py or when initializing, set kD= name of new dicitonary
# dic... |
"""This module provides methods to calculate the astrophysical sensitive
distance of an instrumental power-spectral density.
"""
import warnings
from math import pi
from scipy import integrate
from astropy import (units, constants)
__author__ = 'Duncan Macleod <<EMAIL>>'
def inspiral_range_psd(psd, snr=8, mass1=1... |
import re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = "0.3"
setup(
name='laurel',
version=version,
author='Matthew Garrett',
author_email='<EMAIL>',
url='http://github.com/google/python-laurel',
packages=find_packages(),
scripts=[... |
## @package lstm_benchmark
# Module caffe2.python.lstm_benchmark
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from caffe2.python import workspace, core, utils, rnn_cell, model_hel... |
import numpy as np
import cv2
import glob
import pickle
camera_cal_dir_glob = 'camera_cal/calibration*.jpg'
test_images_dir_glob = 'test_images/test*.jpg'
calibration_mtx_dist_filename = 'dist_pickle.p'
chessboard_size = (9,6)
def calibrate_camera_and_pickle_mtx_dist():
print("Starting calibration process....")
... |
"""Utilities for loading parameters from config files, with automatic type
conversion."""
import ast
import logging
import datetime
from tkp.utility import adict
logger = logging.getLogger(__name__)
## Use prefix loads / dumps for 'load string', 'dump string', a la JSON.
dt_w_microsecond_format = '%Y-%m-%dT%H:%M:%... |
from drydock_provisioner.orchestrator.validations.validators import Validators
from netaddr import IPNetwork, IPAddress
class IpLocalityCheck(Validators):
def __init__(self):
super().__init__('IP Locality Check', "DD2002")
def run_validation(self, site_design, orchestrator=None):
"""
... |
from os.path import join
from django.conf import settings
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from django.forms.widgets import Widget, Select
from cms.models import PageUser
class PluginEditor(Widget):
... |
# -*- coding: utf-8 -*-
"""ATA over Ethernet ATA command"""
from __future__ import print_function
from __future__ import absolute_import
from . import dpkt
ATA_DEVICE_IDENTIFY = 0xec
class AOEATA(dpkt.Packet):
"""ATA over Ethernet ATA command.
See more about the AOEATA on \
https://en.wikipedia.org/wik... |
from dnload.common import is_verbose
from dnload.glsl_block_source import assert_glsl_block_source
from dnload.glsl_block_source import is_glsl_block_source
########################################
# Globals ##############################
########################################
class GlslSourceChain:
"""Chain of... |
from odoo import api, fields, models, _
from odoo.exceptions import UserError, AccessError
class GamificationBadgeUserWizard(models.TransientModel):
_inherit = 'gamification.badge.user.wizard'
employee_id = fields.Many2one('hr.employee', string='Employee', required=True)
user_id = fields.Many2one('res.us... |
"""
Course API Serializers. Representing course catalog data
"""
import urllib
from django.urls import reverse
from rest_framework import serializers
from openedx.core.djangoapps.models.course_details import CourseDetails
from openedx.core.lib.api.fields import AbsoluteURLField
class _MediaSerializer(serializers.... |
import json
from unittest import mock
from datetime import timedelta
from superdesk.utc import utcnow
from superdesk.tests import TestCase
from superdesk.publish.formatters.ninjs_newsroom_formatter import NewsroomNinjsFormatter
from superdesk.publish import init_app
import planning.assignments as planning_assignment... |
""" Visualization of the system cells and MPI domains.
"""
import espressomd
from espressomd.visualization_opengl import openGLLive
import numpy as np
required_features = ["LENNARD_JONES"]
espressomd.assert_features(required_features)
box = [40, 30, 20]
system = espressomd.System(box_l=box)
system.set_random_state_P... |
import logging
import sys
from ming.orm import ThreadLocalORMSession
from pylons import tmpl_context as c, app_globals as g
from allura import model as M
from allura.lib import helpers as h
from allura.lib import utils
log = logging.getLogger(__name__)
def main(options):
log.addHandler(logging.StreamHandler(sy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.