content stringlengths 4 20k |
|---|
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정
import numpy as np
from collections import OrderedDict
from Common.layers import *
from Common.gradient import numerical_gradient
class MultiLayerNetExtend:
"""완전 연결 다층 신경망(확장판)
가중치 감소, 드롭아웃, 배치 정규화 구현
Parameters
---... |
"""
This page is in the table of contents.
Cool is a craft tool to cool the shape.
Cool works well with a stepper extruder, it does not work well with a DC motor extruder.
If enabled, before each layer that takes less then "Minimum Layer Time" to print the tool head will orbit around the printed area for 'Minimum Lay... |
import distutils.spawn
import logging
import re
import subprocess
from time import time, sleep
from targetd.main import TargetdError
pools = []
pools_fs = dict()
zfs_cmd = ""
zfs_enable_copy = False
ALLOWED_DATASET_NAMES = re.compile('^[A-Za-z0-9][A-Za-z0-9_.\-]*$')
class VolInfo(object):
"""
Just to ha... |
from django.db import models
from dt.fields import AddedDateTimeField, ModifiedDateTimeField
from djangosphinx.models import SphinxSearch
class Modifier(models.Model):
city = models.CharField(max_length=25, blank=True, null=True)
data = models.TextField()
def __unicode__(self):
return self.data
class Radius(m... |
# -*- coding: utf-8 -*-
import decimal
import logging
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import (
BooleanField,
DecimalField,
Field,
HiddenField,
IntegerField,
SelectField,
SelectMultipleField,
StringField,
SubmitField,
TextField,
... |
import nose.tools
from bs4 import BeautifulSoup
from ckan.tests import helpers
from common import create_fixtures
eq = nose.tools.assert_equals
class TestOrgPage(helpers.FunctionalTestBase):
def test_search_parent_including_children(self):
parent_org, child_org, parent_dataset, child_dataset = \
... |
#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
import numpy
import os
import ConfigParser
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, NotFoundError
# Read relevant NLPy-specific configuration options.
nlpy... |
import argparse
import os
import sys
import unittest
try:
# py2
from StringIO import StringIO
except ImportError:
# py3
from io import StringIO
from swift_build_support.arguments import (
action as argaction,
type as argtype,
)
class ArgumentsTypeTestCase(unittest.TestCase):
def test_boo... |
from graphql.core.execution import execute
from graphql.core.language.parser import parse
from graphql.core.type import (
GraphQLSchema,
GraphQLField,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLList,
GraphQLString,
GraphQLBoolean
)
class Dog(object):
def __in... |
from copy import deepcopy
from api import Volume
from tests.conftest import dummy_ready_volume
class TestVolume:
def test_delete_case(self, mocker, volume_manager, p_volume_manager_by_id, p_volume_manager_update,
p_volume_manager_get_lock, flask_app):
volume = deepcopy(dummy_ready... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import urllib
import json
from array import *
endpointUrl = "https://api.annomarket.com/online-processing/item/"
shopItemId = "2"
keyId = "<your-credentials-here>"
password = "<your-credentials-here>"
# create a password manager
password_mgr = urllib2.HTTPP... |
""" generate a single-file self-contained version of py.test """
import py
def find_toplevel(name):
for syspath in py.std.sys.path:
base = py.path.local(syspath)
lib = base/name
if lib.check(dir=1):
return lib
mod = base.join("%s.py" % name)
if mod.check(file=1):... |
"""Message actions."""
__all__ = [
'Action',
'FilterAction',
]
from enum import Enum
class Action(Enum):
hold = 0
reject = 1
discard = 2
accept = 3
defer = 4
class FilterAction(Enum):
hold = 0
reject = 1
discard = 2
accept = 3
defer = 4
forw... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from fabric.api import cd, settings, env, abort, local, run, get, put
from fabric.contrib.console import confirm
import tempfile
import time
import os
import sys
from datetime import datetime
env.hosts = ['23.253.52.12']
env.user = 'opm'
code_dir = '/sr... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
from bokeh.util.api import INTERNAL, PUBLIC ; INTERNAL, PUBLIC
from bokeh.util.testing import verify_api ; verify_api
#-----------------------------------------------------------------------------
# Imports
#---... |
"""
Support for interface with an Aquos TV.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.aquostv/
"""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
fro... |
"""
TXs a waveform (either from a file, or a sinusoid) in a frequency-hopping manner.
"""
import time
import numpy
import argparse
import pmt
from gnuradio import gr
from gnuradio import blocks
from gnuradio import uhd
def setup_parser():
""" Setup the parser for the frequency hopper. """
parser = argparse.Ar... |
from PyQt4.QtGui import QColor
from qgis.core import QgsSymbolV2, QgsRendererRangeV2, QgsGraduatedSymbolRendererV2
class VectorSymbolizer():
symbology = "StreamTemp_Vector"
def symbolize(self):
# define ranges: label, lower value, upper value, color name
temp_cat = (
('0-10', 0.0,... |
import movespy.utils
import movespy.trajectory
import os.path
def getClassAttr(output_folder):
'''Parses the XML parameters files in a TransModeler simulation output folder.
Returns a dictionary keyed by Class ID. Values are dictionaries with keys for
class_name, and mass_tonnes.
'''
... |
'''
Summer actors takes any number of input channels and adds the signals on each
channel to produce a single output signal. The semantics of the addition
depend on the kind of signals that are being added.
@author: Allan McInnes
@author: Brian Thorne
'''
import logging
#logging.basicConfig(level=logging.DEBUG)
from n... |
"""
Routers for nested resources.
Example:
# urls.py
from rest_framework_nested import routers
router = routers.SimpleRouter()
router.register(r'domains', DomainViewSet)
domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
domains_router.register(r'nameservers', ... |
import numpy as N
def hess_plot(xdata, ydata, weight,
xmin, xmax, nxbins,
ymin, ymax, nybins,
pmax = 1.0, pmin = 0.01):
#x = stellar mass
#y = gas fraction
dx = (xmax - xmin) /nxbins
mbin = xmin + (N.arange(nxbins))*dx + dx/2.0
dy = (ymax - ymin) ... |
import math
import os
import numpy as np
from scipy.spatial.distance import cdist
import bpy
from bpy.props import *
import os
from mathutils import Vector
def no_flyover(mesh):
"""
Compute a static camera position
Parameters
----------
mesh (obj) A DTMRenderContext (terr... |
import subprocess
import paramiko
from paramiko import client
# Devices
TV = 1
AUDIO = 2
# Codes
POWER_ON = 1
POWER_OFF = 2
device_map = {
AUDIO : 'Audio',
TV : 'VizioTv',
}
code_map = {
POWER_ON : 'KEY_POWER',
POWER_OFF : 'KEY_POWER2',
}
class LircCommander(object):
instance = None
def Setu... |
= MPD play daemon =
== ncmpcpp ==
emerge mpd ncmpcpp
== configuration ==
sed '/^#/d;/^$/d' /etc/mpd.conf
{{{
music_directory "/mnt/play/MUSIC"
playlist_directory "/var/lib/mpd/playlists"
db_file "/var/lib/mpd/database"
log_file "/var/lib/mpd/log"
pid... |
"""
Unit tests for
:func:`iris.fileformats.pp_load_rules._reduce_points_and_bounds`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.... |
import paddle
import paddle.fluid as fluid
import math
__all__ = ['InceptionV4']
train_parameters = {
"input_size": [3, 224, 224],
"input_mean": [0.485, 0.456, 0.406],
"input_std": [0.229, 0.224, 0.225],
"learning_strategy": {
"name": "piecewise_decay",
"batch_size": 256,
"epoc... |
"""
compare_fields.py
Driver function that creates two ARTView displays for comparison.
"""
import os
import sys
from ..core import Variable, QtWidgets, QtCore
from ..components import RadarDisplay, Menu, LinkSharedVariables
from ._common import _add_all_advanced_tools, _parse_dir, _parse_field
def run(DirIn=None, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
from mixpanel_jql import JQL, raw, Events, Reducer
class TestAccessorOnlyTransformations(unittest.TestCase):
def setUp(self):
self.query = JQL(api_secret=None, events=Events())
def _test(self, manipulator, expected_fu... |
"""
Defines the functions corresponding to each of the subcommands
"""
import os.path
import pickle
import sys
import time
import greg.classes as c
import greg.aux_functions as aux
try: # lxml is an optional dependency for pretty printing opml export
from lxml import etree as ET
lxmlexists = True
except Impo... |
# -*- coding: utf-8 -*-
"""All exceptions used in the Cookiecutter code base are defined here."""
class CookiecutterException(Exception):
"""
Base exception class.
All Cookiecutter-specific exceptions should subclass this class.
"""
class NonTemplatedInputDirException(CookiecutterException):
"... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
import pytest
import ray
from ray.experimental.serve.examples.adder import ScalerAdder, VectorizedAdder
from ray.experimental.serve.examples.halt import SleepCounter, SleepOnFir... |
from django.conf.urls import patterns, include, url
from .views import *
from django.conf import settings
urlpatterns=patterns('',
url(r'^$' ,login_required(home.as_view()), name='index'),
url(r'^home/$' ,login_required(home.as_view()), name='home'),
url(r'^gestionusuarios/registrar/$', RegistrarUsuario.as_view(), ... |
DATE_FORMAT = 'j. F Y'
TIME_FORMAT = 'G:i:s'
DATETIME_FORMAT = 'j. F Y G:i:s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.m.Y'
SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s'
FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://... |
#!/usr/bin/env python
'''Demo to turn detected faces into TFs at 1m distance'''
import rospy
from opencv_apps.msg import FaceArrayStamped
from geometry_msgs.msg import PoseStamped
import tf
import math
FOV_VERT = math.radians(58)
FOV_HORIZ = math.radians(87)
RES_VERT = 480.
RES_HORIZ = 640.
class Face2TF:
def __... |
"""
Given a string which contains only letters. Sort it by lower case first and upper case second.
Note
It's not necessary to keep the original order of lower-case letters and upper case letters.
Example
For "abAcD", a reasonable answer is "acbAD"
"""
__author__ = 'Danyang'
class Solution:
def sortLetters(self,... |
from abc import ABC
from abc import abstractmethod
from copy import deepcopy
class KernelWriterBase(ABC):
def __init__(self):
super().__init__()
self.state = {}
self.endLine = "\n"
self.getGroupIdStr = "hc_get_group_id"
self.getNumGroupsStr = "hc_get_num_groups"
self.getLocalIdStr = "hc_... |
# -*- coding: utf-8 -*-
from forms import EntregaMonografiaRevisadaForm, EntregaMonografiaOriginalForm
from models import EntregaMonografiaRevisada, EntregaMonografiaOriginal
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import auth, messages
from django.shortcuts import render_to_resp... |
"""
Support for UDP socket based sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.udp/
"""
import logging
import socket
import select
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.... |
import json
import cherrypy
import logging
import sensorPlugins
import importlib
logging.basicConfig(format='%(levelname)s:%(asctime)s %(message)s', level=logging.INFO)
class Plugins:
exposed = True
def GET(self, **kwargs):
logging.debug('GET request to plugins.')
cherrypy.response.headers[... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
update redis query string of all leancloud class, run every 24 hours.
hset class_name:width page_num query_json_string.
"""
import _env
import lean_classname
import time
from config import redis_config
from config.img_config import Img
from redis import Redis
from lib.... |
"""Tests for various Frosted behavior."""
from __future__ import absolute_import, division, print_function, unicode_literals
from sys import version_info
import pytest
from frosted import messages as m
from pies.overrides import *
from .utils import flakes
def test_duplicateArgs():
flakes('def fu(bar, bar): p... |
import logging
import sys
import os
import platform
import shutil
import string
import zipfile
import re
import ctypes
from . import config
from .osdriver import get_physical_disk_number, wmi_get_drive_info, \
log, resource_path, multibootusb_host_dir
def scripts_dir_path():
return os.path.dirname(os.path.r... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Account',
... |
import numpy as np
from .utils import _create_info, _set_tmin, _create_events, \
_create_event_metadata, _validate_ft_struct
from .. import RawArray
from ...epochs import EpochsArray
from ...evoked import EvokedArray
def read_raw_fieldtrip(fname, info, data_name='data'):
"""Load continuous (raw) data from a ... |
import unittest
from blinkpy.common.net.web_test_results import WebTestResults
class WebTestResultsTest(unittest.TestCase):
# The real files have no whitespace, but newlines make this much more readable.
example_full_results_json = """ADD_RESULTS({
"tests": {
"fast": {
"dom": {
... |
""" Unit tests for the Assessment object """
from sqlalchemy.orm import attributes
from ggrc import db
from ggrc.models import Assessment
from ggrc.models import mixins
from ggrc.models import object_document
from ggrc.models import object_person
from ggrc.models import relationship
from ggrc.models import track_obje... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify the mem --format=gnuplot option.
"""
import TestSCons_time
test = TestSCons_time.TestSCons_time()
test.fake_logfile('foo-000-0.log', 0)
test.fake_logfile('foo-000-1.log', 0)
test.fake_logfile('foo-000-2.log', 0)
test.fake_logfile('foo-001-0.l... |
#coding:utf-8
import json
import re
from django.http import HttpResponse
# 数据库接口导入
from hbh import models as hbh_models
info = {
'fail': '失败',
'error': '错误',
'Success': '成功'
}
# 注册用户
def addUser(request):
if request.method == "POST":
data = request.POST
if hbh_models.... |
from opus_core.variables.variable import Variable
from numpy import float32
class income_times_2(Variable):
"""A variable for unit tests.
"""
_return_type="float32"
def dependencies(self):
return ['opus_core.test_agent.income']
def compute(self, dataset_pool):
val... |
import logging
import argparse
import sys
import os
import subprocess
import multiprocessing
import pkg_resources
import subprocess
import itertools
import signal
import shutil
import random
import string
from math import floor, log, ceil
from collections import namedtuple
from pbcore.io.FastaIO import FastaReader
fr... |
# -*- coding: utf-8 -*-
from flask import Flask, render_template, url_for, request, json, g, redirect, request, abort
from hashids import Hashids
import random
import os
import countsyl
import click
from pprint import pprint
app = Flask(__name__)
hashids = Hashids()
SYL_1="5"
SYL_2="8"
SYL_3="5"
BOOK_META="books/book... |
from __future__ import unicode_literals
import frappe
import frappe.defaults
from frappe.core.doctype.data_import.data_import import export_csv
import unittest
import os
class TestDataImportFixtures(unittest.TestCase):
def setUp(self):
pass
#start test for Client Script
def test_Custom_Script_fixture_simple(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import binascii
import hashlib
import os
import shutil
import sys
def concat(file_paths, file):
"""
Concatenates contents in file_paths list to a file-like object, `file`
"""
for file_path in file_paths:
copy_file(file_path, file)
def copy_file(... |
from pybrain.rl.agents.linearfa import LinearFA_Agent
from pybrain.rl.experiments import EpisodicExperiment
from environment import Environment
from tasks import LinearFATileCoding3476BalanceTask
from training import LinearFATraining_setAlpha
from learners import SARSALambda_LinFA_setAlpha
# learning rate applied to ... |
"""The app module, containing the app factory function."""
import os.path
from flask import Flask
from core.database import init_engine
from core.extensions import db, cors, migrate
from ibackend.config import ProdConfig
from ibackend.extensions import set_global_api_blueprint
def create_app(api_blueprint, config_... |
import os
import sys
import click
import pandas as pd
from skbio import io
def sample_genes(ortho_groups_fp,
min_taxa_cutoff=10.0):
""" Select gene families (orthologous groups) from OrthoFinder result
Parameters
----------
ortho_groups_fp : str
orthologous groups definition ... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head... |
from __future__ import unicode_literals
import warnings
from django.conf.urls import url, patterns, include
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest
from tastefulpy.exceptions import NotRegistered, B... |
#!/usr/bin/env python3
"""
Python class example.
"""
# The start of it all:
# Fill it all in here.
class TextWrapper:
def __init__(self, text):
self.text = text
def render(self, file_out, current_ind=""):
file_out.write(current_ind + self.text)
class Element:
tag = "html"
indent = ... |
from .. import signals # NOQA :signals import needs to be here so signals get registered
import logging
import collections
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.template import Context
from django.contrib.a... |
"""Helper functions for dealing with Cloud Datastore's Protobuf API.
The non-private functions are part of the API.
"""
import calendar
import datetime
from google.protobuf.internal.type_checkers import Int64ValueChecker
import pytz
import six
from gcloud.datastore import _datastore_v1_pb2 as datastore_pb
from gclo... |
from bson import DBRef, SON
from base import (BaseDict, BaseList, TopLevelDocumentMetaclass, get_document)
from fields import (ReferenceField, ListField, DictField, MapField)
from connection import get_db
from queryset import QuerySet
from document import Document
class DeReference(object):
def __call__(self, i... |
from lstree.nodes.node import Node
__author__ = 'Shreyas Kulkarni'
__email__ = '<EMAIL>'
class FileNode(Node):
def empty(self):
return False |
import tensorflow as tf
class GcnBiasAndFeatureGates:
def __init__(self, biases, features, transform_1, transform_2, l1_scale=0.0):
self.features = features
self.biases = biases
self.transform_1 = transform_1
self.transform_2 = transform_2
self.l1_scale = 0.0
self... |
"""
Bunch is a dictionary that supports attribute-style access. The only
difference with Bunch(look at https://github.com/dsc/bunch) is that
this library normalizes keys into attribute style notation.
>>> a = {'a': 1}
>>> a['a']
1
>>> b = bunchify(a)
>>> b.a
1
"""
import re
import bunch as _bun... |
"""WebMessage web interface"""
__revision__ = "$Id$"
__lastupdated__ = """$Date$"""
from invenio.config import CFG_SITE_SECURE_URL, CFG_SITE_URL, CFG_ACCESS_CONTROL_LEVEL_SITE
from invenio.webuser import getUid, isGuestUser, page_not_authorized, collect_user_info
from invenio.webmessage import perform_request_displa... |
import os
import shutil
import getpass
from scp import SCPClient
import paramiko
#Variable
location = "/etc/ocsinventory-server"
directory = "/usr/share/ocsinventory-reports/ocsreports/extensions/"
plugins = []
selection = -1
#Get directory where are the plugins
print("Where is the plugins location [" + directory + "... |
# code for mongodb
from flask import Flask, jsonify, request, json, abort, session, redirect, render_template, \
url_for, Response, flash
from flask_pymongo import PyMongo
from flask_restplus import Resource
from bson import json_util
from bson.objectid import ObjectId
from models import *
from jinja2 import *
a... |
from msrest.service_client import ServiceClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.storage_accounts_operations import StorageAccountsOperations
from .operations.usage_operations import UsageOperations
from . import models
... |
#!/usr/bin/env python3
import os
import glob
import time
import flask
import qrcode
import urllib.parse
from flask import Flask
from flask import render_template
from flask import request
from flask import send_from_directory
from config import uploadr as config
from werkzeug.utils import secure_filename
app = Flask(_... |
import urllib
from xml.etree import ElementTree
from xl import common
import logging
logger = logging.getLogger(__name__)
# TODO: The 'new' API doesn't allow general queries, only allows exact
# matching.. if they fix it, we'll fix it. >_>
search_url = 'http://librivox.org/api/feed/audiobooks/?title='
class Book():... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
fro... |
import cPickle as pickle
import irr
import argparse
import numpy as np
#-- Parse command-line arguments
PARSER = argparse.ArgumentParser(description='Estimate the tilt and orientation factor (TOF) for the annual insolation.')
PARSER.add_argument('-lat', '--latitude',
help='latitude of the place', required=False)
PARS... |
import base64
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
class IndexPage(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.dirname(__file__), 'in... |
from celery import shared_task
import requests
import logging
from django.conf import settings
import base64
logger = logging.getLogger(__name__)
@shared_task
def get_character_id_from_sso_code(code):
#first we need to exchange the code for a token
client_id = settings.SSO_CLIENT_ID
client_sec... |
"""
Tests the setup.py script by running ``python setup.py install`` in a
temporarily activated virtual environment.
"""
import os
import re
import shutil
import subprocess
import sys
import unittest
import urllib2
import version
VENV_NAME = '_e'
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
VENV_PATH = o... |
from nmigen import Signal
from nmigen_cfu import SimpleElaboratable
class Delayer(SimpleElaboratable):
"""Delays an input Signal via a shift register.
Parameters
----------
cycles: int
Number of cycles to delay the signal
Public Interface
---------------
input: Signal() in
... |
"""Commands to import or export the current command stack to or from a file."""
import click
import unsync
from unsync.core import NestedUnsyncCommands
import pickle
@unsync.command()
@click.option('--output-file', '-o', type=click.Path(dir_okay=False, readable=True, resolve_path=True), help='File that the command s... |
import argparse
import centinel
import centinel.models
import centinel.views
import config
import logging
from logging.handlers import RotatingFileHandler
import sys
if (2, 7, 9) > sys.version_info:
print ("WARNING: Python is older than 2.7.9, "
"using older SSL version. This is "
"incompatib... |
"""
Run with:
sudo python ./setup.py install
"""
import os
import sys
import warnings
import io
if sys.version_info[:2] < (2, 7) or (sys.version_info[:1] == 3 and sys.version_info[:2] < (3, 5)):
raise Exception('This version of gensim needs Python 2.7, 3.5 or later.')
import ez_setup
ez_setup.use_setuptools()
f... |
from django.conf import settings
from django import template
# Depending on your django version, `reverse` and `NoReverseMatch` has been moved.
# From django 2.0 they've been moved to `django.urls`
try:
from django.urls import reverse, NoReverseMatch
except ImportError:
from django.core.urlresolvers import rev... |
#!/usr/bin/env python2.7
import os
import sys
args = sys.argv [1:]
linecount = int(10)
chunk_size=8
def tail(filehandle, offset=(int(chunk_size * -1)), whence=int(2), data=str()):
length = len(data)
if length == os.path.getsize(filename):
return data
filehandle.seek(offset,whence)
data = filehandle.read(... |
from __future__ import print_function
import string
import logging
import curses # Needed for colours
back = curses.COLOR_WHITE
front = curses.COLOR_BLACK
# Switch for white backgrounds
###back = curses.COLOR_BLACK
###front = curses.COLOR_WHITE
COLORS = [
# Color combinations, (ID#, foreground, background)
... |
# -*- coding: utf-8 -*-
r"""
The :mod:`pygsp.optimization` module provides tools to solve convex
optimization problems on graphs.
"""
from pygsp import utils
logger = utils.build_logger(__name__)
def _import_pyunlocbox():
try:
from pyunlocbox import functions, solvers
except Exception as e:
... |
import readline
from jedi import utils
from .helpers import TestCase, cwd_at
class TestSetupReadline(TestCase):
class NameSpace():
pass
def __init__(self, *args, **kwargs):
super(type(self), self).__init__(*args, **kwargs)
self.namespace = self.NameSpace()
utils.setup_readli... |
import os
from testtools import ExpectedException
from testtools import TestCase
from testscenarios.testcase import TestWithScenarios
from yaml.composer import ComposerError
from jenkins_jobs import builder
from tests.base import get_scenarios, JsonTestCase, YamlTestCase
from tests.base import LoggingFixture
def _ex... |
#!/usr/bin/env python
"""Prepare truth set of crowd sourced CNVs from GiaB samples.
http://biorxiv.org/content/early/2016/12/13/093526
"""
import requests
from bcbio.variation import vcfutils
url = "http://biorxiv.org/content/biorxiv/suppl/2016/12/13/093526.DC1/093526-3.txt"
out_base = "NA24385-crowd-dels-%s.bed"
... |
import pandas as pd
import sys, os
import tarfile
import gzip
class ValidatePhoSimCatalogs(object):
MegaByte = 1024*1024
def __init__(self,
obsHistIDValues,
prefix='InstanceCatalogs/phosim_input_'):
self.obsHistIDValues = obsHistIDValues
self.prefix=prefix
@classmetho... |
title = "Combo boxes"
description = """
The ComboBox widget allows to select one option out of a list.
The ComboBoxEntry additionally allows the user to enter a value
that is not in the list of options.
How the options are displayed is controlled by cell renderers.
"""
from gi.repository import Gtk, Gdk, GdkPixbuf,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import subprocess
import re
from powerline.theme import requires_segment_info
from powerline.bindings.vim import buffer_name
def get_git_status():
has_pending_commits = True
has_untracked_files = False
detached_head = False
d... |
'''
Created on August 23, 2019
This file is subject to the terms and conditions defined in the
file 'LICENSE.txt', which is part of this source code package.
@author: David Moss
'''
from intelligence.intelligence import Intelligence
import utilities.utilities as utilities
import utilities.analytics as analytics
imp... |
import os
from translate.storage.versioncontrol import GenericRevisionControlSystem
from translate.storage.versioncontrol import run_command, prepare_filelist
def is_available():
"""check if git is installed"""
exitcode, output, error = run_command(["git", "--version"])
return exitcode == 0
class git(G... |
import os
import re
import phonenumbers
from gsxws.core import validate
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
def phone_validator(val):
try:
phonenumbers.parse(val, settings.INSTALL_COUNTRY)
except phonenu... |
#!/usr/bin/python
import sys
import re
def main():
if (len(sys.argv)!=3):
print "Usage: antlrpp.py Grammar.g Grammar_pure.g"
return
inf = open(sys.argv[1],"r")
out = open(sys.argv[2],'w')
words = []
for line in inf.readlines():
x = line.strip().split()
#print x
words.extend(x)
line = ''
for w in words... |
from datetime import time
import re
def parse_time(arg):
""" Returns datetime.time object
based on parsed argument string
Only accepts in the following format:
[xx]:[yy] -> am/pm left out, use military time
[xx]-> am/pm left out, use military time
[xx]:[yy][am/pm]
[xx][am/pm] -> xx is eva... |
from twilio.rest.resources.imports import httplib2
from twilio.rest.resources.imports import socks
from twilio.rest.resources.imports import PROXY_TYPE_HTTP
from twilio.rest.resources.imports import PROXY_TYPE_SOCKS4
from twilio.rest.resources.imports import PROXY_TYPE_SOCKS5
class Connection(object):
'''Class fo... |
def isqrt(n):
"""Calculate the floor of the square root of a natural number. Uses a
binary search to find the integer square root, and so runs logarithmically.
"""
a, b = 0, n+1
while b - a != 1:
mid = (a + b) // 2
if mid*mid <= n:
a = mid
else:
b = mid
return a
def perfect_square(n):
"""Calculate i... |
# coding=utf-8
from django.conf import settings
from django.db import models
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.utils.translation.trans_real import get_supported_language_variant
from pybb import defaults, util
from pybb.compat import get_im... |
# -*- coding: utf-8 -*-
from PyQt5.QtCore import Qt
from cadnano.proxies.cnenum import (
ItemEnum,
EnumType
)
from .cnoutlineritem import (
CNOutlinerItem,
RootPartItem,
NAME_COL,
VISIBLE_COL,
COLOR_COL,
LEAF_FLAGS
)
from cadnano.views.abstractitems import AbstractVirtualHelixItem
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.