content string |
|---|
from setuptools import find_packages, setup
try:
from azure_bdist_wheel import cmdclass
except ImportError:
from distutils import log as logger
logger.warn("Wheel is not available, disabling bdist_wheel hook")
cmdclass = {}
from io import open
import re
# azure v0.x is not compatible with this package
... |
import re, setuptools, os, distutils
from setuptools import setup, find_packages, Command
class RunTestsCommand(Command):
description = "Test command to run testr in virtualenv"
user_options = [
('coverage', 'c', "Generate code coverage report"),
('testrun=', None, "Run a specific test"),
... |
#!/usr/bin/python
"""
Zookeeper collector
Refer to the following zookeeper commands documentation for details:
http://zookeeper.apache.org/doc/trunk/zookeeperAdmin.html#sc_zkCommands
"""
import sys
import socket
import time
import subprocess
import re
from collectors.lib import utils
COLLECTION_INTERVAL = 15 # se... |
#!/usr/bin/env python
"""
Simple example of a full screen application with a vertical split.
This will show a window on the left for user input. When the user types, the
reversed input is shown on the right. Pressing Ctrl-Q will quit the application.
"""
from __future__ import unicode_literals
from prompt_toolkit.app... |
import os
import re
import subprocess
import cere_configure
import logging
import networkx as nx
import vars as var
from graph_utils import plot, save_graph
logger = logging.getLogger('Profile')
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath = ... |
#!/usr/bin/python
# import necessary library.
import threading
import sys
import rados
import socket
import time
import os
import getopt
#global variable to measure the time of total operations
avgsecond = 0.0
# create an interface class.
class multithread (threading.Thread):
# define init process.
def __init__(se... |
import re
from library.frontend import Base
from library.utils.type_conv import str2list
class Manager_Uri(Base):
def __init__(self, mongoclient=None, redisclient=None):
self.uridict = {
'/':{'name':'首页', 'nav':False, 'referer' : True, 'level':0, 'parent':'/'},
'/login.html':{'nam... |
import json
from sqlalchemy import or_, text
from anyblok.declarations import Declarations
from anyblok.column import String, Integer
@Declarations.register(Declarations.Model.FuretUI)
class Space:
code = String(primary_key=True)
label = String(nullable=False)
role = String()
order = Integer(default=1... |
#TFLearn bug regarding image loading: https://github.com/tflearn/tflearn/issues/180
#Monochromes img-magick: https://poizan.dk/blog/2014/02/28/monochrome-images-in-imagemagick/
#How to persist a model: https://github.com/tflearn/tflearn/blob/master/examples/basics/weights_persistence.py
from __future__ import division,... |
# Задача 12
# Разработайте игру "Крестики-нолики". (см. М.Доусон Программируем на Python
#гл. 6).
# Titov I. V.
# 02.06.2016
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
def display_instruct():
"""Инструкции"""
print(
"""
Да начнётся битва!
На своём ходу, введи цифру, согласно ри... |
#!/usr/bin/env python
import os
import sys
import unittest
DIR = os.path.dirname(os.path.abspath(__file__))
sys.path[0] = os.path.dirname(DIR)
from yorbay.builder import build_from_path, build_from_standalone_source
from yorbay.compiler import CircularDependencyError
from yorbay.loader import FsLoader, SimpleLoader... |
import numpy as np
# OPTIONS
np.set_printoptions(threshold=np.nan) #display all values
# SHAPE
np.shape
# CREATE ARRAY
list = [1,2,3,4]
np.array(list)
# RESHAPE AN ARRAY
test_score
array([ 0.66666667, 0.76086957, 0.80072464, 0.80434783, 0.8115942 ,
0.8115942 , 0.80797101, 0.8115942 , 0... |
# -*- coding: utf-8 -*-
import hashlib
import os
import ConfigParser
import logging
from suds.client import Client
from suds.sax.element import Element
logging.basicConfig(level=logging.FATAL)
"Here is a full Python Client for Yousign Api"
class ApiClient():
@property
def env_dict(self):
return {"de... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... |
import threading
import os
from collections import defaultdict
class Dispatcher(object):
def __init__(self, *args, **kwargs):
self.file = None
self.file_obj = None
self.logger = None
self.observers = defaultdict(list)
class BaseDispatcher(threading.Thread):
daemon = True
... |
import itertools
from collections import namedtuple
from odoo.fields import Date
Criteria = namedtuple(
'Criteria',
[
'when', # Contract line relatively to today (BEFORE, IN, AFTER)
'has_date_end', # Is date_end set on contract line (bool)
'has_last_date_invoiced', # Is last_date_inv... |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from rest_framework import routers
from diag_app import views
from django.views.generic import TemplateView
router = routers.DefaultRouter()
router.register(r'accounts', views.UserView, 'list... |
from datetime import date, datetime, time, timedelta
import importlib
from dateutil.relativedelta import relativedelta
from django.db import models
import numpy as np
import pandas as pd
import pytz
from ctrack import categories
class Transaction(models.Model):
"""A single one-way transaction."""
when = mode... |
#! /usr/bin/python
from bismarck_cli.servers.defs.abstract_repo import AbstractRepo
from bismarck_cli.servers.defs.app_repos_def import AppReposDef
from bismarck_cli.utils.storage import Storage
#----------------------------------------------------------------------
class LocalRepoDef( AbstractRepo ):
'''
(... |
import math
import time
t1 = time.time()
# N = 5 or 15
N = 15
grid = []
if N == 15:
grid.append([7,53,183,439,863,497,383,563,79,973,287,63,343,169,583])
grid.append([627,343,773,959,943,767,473,103,699,303,957,703,583,639,913])
grid.append([447,283,463,29,23,487,463,993,119,883,327,493,423,159,743])
... |
import time
locations = ["Urban", "Rural", "Unallocated"]
light = ["Daylight", "", "", "Darkness - lights lit", "Darkness - lights unlit", "Darkness - no lighting", "Darkness - lighting unknown"]
start_time = int(round(time.time() * 1000))
# now we have a file
text_file = sc.textFile("hdfs://hdfs-rpc.service.consul:... |
"""
Creates a new campaign
Usage:
new_campaign -h | --help
new_campaign <wiki> <name> <form> <view> <labels-per-task>
<tasks-per-assignment> [--info-url=<info-url>]
[--config=<path>] [--force]
Arguments:
<wiki> Wiki database id, for example fawiki, dewiki... |
from __future__ import absolute_import
from ast import literal_eval
from textwrap import dedent
from . import Block, register_build_in
from ._templates import MakoTemplates
from .. import utils
from ..base import Element
from ._build import _build_params as build_core_params
DEFAULT_CODE = '''\
"""
Embedded Python... |
"""split criteo data in mlperf format"""
import math
import os
import numpy as np
from tqdm import tqdm
from absl import app
from absl import logging
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_enum("stage", "val", ["train", "val", "test"], "")
flags.DEFINE_string("bin_data_root", "", "path to binary cri... |
from gui_lib.container import Container
from gui_lib.label import Label
from gui_lib.listbox import Listbox
from factuurDetail import factuurDetail
from verenigingNaamCoupler import getVerenigingNaam
import curses
class factuurListItem(Label):
def __init__(self, width, factuur, manager):
self.manager = man... |
# leastsq_bounds.py
from __future__ import division
import numpy as np
from scipy.optimize import leastsq
__date__ = "2012-03-26 mar"
def leastsq_bounds( func, x0, bounds, boundsweight=10, Dfun = None, **kwargs ):
""" leastsq with bound conatraints lo <= p <= hi
run leastsq with additional constraints to min... |
import re
import six
class NwaWorkflow(object):
'''Workflow definition of NWA. '''
_path_prefix = '/umf/workflow/'
_nameid_initialized = False
_nameid = {
'CreateTenantNW': '40030001',
'DeleteTenantNW': '40030016',
'CreateVLAN': '40030002',
'DeleteVLAN': '40030018',
... |
""" TensorFlow Sample for running TPU Training """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
from absl import logging
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tf.compat.v2.enabl... |
import json
import os
import socket
import sys
import threading
import time
import traceback
import urlparse
import uuid
from .base import (CallbackHandler,
RefTestExecutor,
RefTestImplementation,
TestharnessExecutor,
extra_timeout,
... |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from common import public
class rmfygg():
"""人民法院公告"""
need_check_ziduan = [u'bbd_dotime',
u'notice_people',
u'notice_time',
u'litigant'
... |
from django.core import exceptions
from django.db import IntegrityError
from oscar.core.loading import get_model
Benefit = get_model('offer', 'Benefit')
Condition = get_model('offer', 'Condition')
Range = get_model('offer', 'Range')
def _class_path(klass):
return '%s.%s' % (klass.__module__, klass.__name__)
d... |
"""
This software was developed by Institut Laue-Langevin as part of
Distributed Data Analysis of Neutron Scattering Experiments (DANSE).
Copyright 2012 Institut Laue-Langevin
"""
# this is a dead simple dialog for getting font family, size,style and weight
import wx
from matplotlib.font_manager import FontProperti... |
# -*- coding: utf-8 -*-
import requests
import pandas as pd
from netCDF4 import Dataset
import datetime
#from dateutil.parser import parse
# from lib.parse_urls import parse_urls
from . parse_urls import parse_urls
#import collections
import itertools
class dataset:
def __init__(self,datasetkey,datahub,debug=Fal... |
"""This example gets all custom fields.
To create custom fields, run create_custom_fields.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
sec... |
import sys
import threading
import time
import unittest
from test import test_support
class UntracedThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
sys.settrace(None)
for i in range(10):
self.untracedcall()
def ... |
"""
The FilterScheduler is for creating instances locally.
You can customize this scheduler by specifying your own Host Filters and
Weighing Functions.
"""
import random
from oslo_log import log as logging
from six.moves import range
import nova.conf
from nova import exception
from nova.i18n import _, _LI
from nova ... |
from time import sleep
import json
from flask import Blueprint, session, redirect, url_for
from mouse import mousemove, mouseclick
import utils
iplayer = Blueprint('iplayer', __name__)
mediaweb_config = {
'blueprint': iplayer,
'title': 'iPlayer',
'id': 'iplayer',
'buttons': (
... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from django_countries.fields import CountryField
from courses.models import Course
# Create your models here.
class Product(models.Model):
course = models.ForeignKey(Course, related_name='p... |
#!/usr/bin/env python
import os
import sys
import shutil
import setuptools.command.egg_info as egg_info_cmd
from setuptools import setup, find_packages
SETUP_DIR = os.path.dirname(__file__)
README = os.path.join(SETUP_DIR, 'README.rst')
try:
import gittaggers
tagger = gittaggers.EggInfoFromGit
except Impor... |
import re
def _process_docstring(app, what, name, obj, options, lines):
liter_re = re.compile(r'\s*```\s*$')
liter_flag = False
offset = 0
for j in range(len(lines)):
i = j+offset
line = lines[i]
# first literal block line
if not liter_flag and liter_re.match(line):
... |
from datetime import timedelta
import numpy as np
import pytest
import pandas as pd
from pandas import Series, TimedeltaIndex, timedelta_range
import pandas._testing as tm
from pandas.tseries.offsets import DateOffset, Day, Hour
class TestTimedeltaIndexOps:
def test_value_counts_unique(self):
# GH 7735... |
import logging
import logging.handlers
import os
import re
import time
from logging.handlers import RotatingFileHandler
from sys import exit
from sys import platform as _platform
from typing import Optional
import click
import humanfriendly # type: ignore
import pid # type: ignore
from mysql_autoxtrabackup.api impo... |
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import socket
print(socket.gethostname())
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run wit... |
'''
Use the fitted version of the Brandt curve to create a map of shear.
'''
from astropy.io import fits
import astropy.units as u
import astropy.constants as c
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
from cube_analysis.rotation_curves.curve_fitting import (oortA_brandt,
... |
from matplotlib import use as mplt_use
mplt_use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import scipy.cluster.hierarchy as sch
from matplotlib import rcParams
import matplotlib.colors as pltcolors
rcParams['pdf.fonttype'] = 42
rcParams['svg.fonttype'] = 'none'
old_settings = np.seterr(all='ignore')
... |
from mock import patch, call
from pytest import raises
import mock
from kiwi.package_manager.pacman import PackageManagerPacman
from kiwi.exceptions import KiwiRequestError
class TestPackageManagerPacman:
def setup(self):
repository = mock.Mock()
repository.root_dir = '/root-dir'
reposi... |
# -*- coding: utf-8 -*-
"""
This is a plugin for Bottle web applications.
When you install it to an application, it will
log all requests to your site. It's even imitating
Apache's combined log format to allow you to use
any of the many tools for Apache log file analysis.
Homepage: https://github.com/pklaus/bottlelog... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: uu_codec.py
""" Python 'uu_codec' Codec - UU content transfer encoding
Unlike most of the other codecs which target Unicode, this codec
will... |
import textwrap
import unittest
import pytest
from conans.test.utils.tools import TestClient
class PropagateSpecificComponents(unittest.TestCase):
"""
Feature: recipes can declare the components they are consuming from their requirements,
only those components should be propagated to their own c... |
class Report:
def __init__(self):
self.lines = []
def add_title(self, title, length=50, offset=4):
a = '=' * length
b = '=' * offset + ' ' + title + ' ' + '=' * (length - len(title) - offset - 2)
self.add_string_line(a)
self.add_string_line(b)
self.add... |
"""
Class Hierarchy
G{classtree: Simulator}
Package tree
G{packagetree: simulator}
Import Graph
G{importgraph: simulator}
"""
#/usr/bin/python
# -*- coding:utf-8 -*-
from region_pool import RegionPool
class Simulator:
"""
a simulator hosts N regions
create a simulator ini/xml file containing N region ini/xml... |
'''
Created on May 17, 2014
@author: anroco
'''
from flask import Blueprint, abort, g, request, current_app
from flask.ext import restful
from commons import validate_user_auth, decrypt_token
from dynamoDBqueries import User
# from flask.ext.restful import reqparse
auth = Blueprint('auth', __name__)
api = restful.A... |
from django.http import HttpResponse
'''
Creating the JSONResponse
'''
import simplejson
from django.utils.encoding import force_unicode
from django.db.models.base import ModelBase
class JSONResponse(HttpResponse):
""" JSON response class """
def __init__(self,conten... |
#!/usr/bin/env python
"""
These results have not been validated.
D region absorption during eclipse
http://nvlpubs.nist.gov/nistpubs/jres/69D/jresv69Dn7p939_A1b.pdf
"""
from dateutil.parser import parse
import numpy as np
from matplotlib.pyplot import show
import seaborn as sns
#
from piradar.plots import plotgas,plot... |
__author__ = 'socialmoneydev'
from models.jsonBase import JsonBase
from utils.requestor import Requestor
from models.accountidonly import AccountIdOnly
from accountclose import AccountClose
class Account(JsonBase) :
def __init__(self):
self.requestId = None
self.customerId = None
self.acco... |
from enum import Enum
class McInvalidValue(Enum):
"""Special values which may be assigned to attributes.
Attributes:
MC_NO_VALUE: This is the initial value for attribute until it receives a value for an Env. This will only be observed
when iterating over the env values of an attribute and... |
import os
import stat
import struct
import urllib
import gzip
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from const import *
# XXX calcsize()? We need to do some overriding however.
fmts = {
DMAP_TYPE_LIST: ('0s', 0),
DMAP_TYPE_BYTE: ('b', 1),
DMAP_TYPE_... |
import copy
import json
import jsonschema
import re
import six
from mistral import exceptions as exc
from mistral import expressions as expr
from mistral import utils
from mistral.workbook import types
CMD_PTRN = re.compile("^[\w\.]+[^=\s\"]*")
INLINE_YAQL = expr.INLINE_YAQL_REGEXP
_ALL_IN_BRACKETS = "\[.*\]\s*"
_A... |
#!/usr/bin/env python
"""
@file odConnectionsCheck.py
@author Yun-Pang Wang
@author Michael Behrisch
@date 2007-03-20
@version $Id: odConnectionsCheck.py 14425 2013-08-16 20:11:47Z behrisch $
This script checks if at least one route for a given OD pair exists.
SUMO, Simulation of Urban MObility; see http://su... |
import logging
logger = logging.getLogger()
from piHAlibs import (my_fctname,coroutine,db2dict,tstampdev)
try:
from .rfxtrxlibs import *
except ImportError as e:
logger.critical("%s : %s", repr(e.__class__), str(e))
print ('RFXtrx modules not yet installed')
@my_fctname
@coroutine
def tremdecoder(targets... |
import math
import torch
from torch.distributions import constraints
from pyro.distributions.torch import Exponential
from pyro.distributions.torch_distribution import TorchDistribution
class TruncatedPolyaGamma(TorchDistribution):
"""
This is a PolyaGamma(1, 0) distribution truncated to have finite support... |
import os
import re
import csv
import subprocess
import time
filename = "speedtest_data.csv"
format = re.compile('\d+(?:\.\d+)?') #format to verify only numbers
_digits = re.compile('\d')
def contains_digits(d):
#check if string has digits
return bool(_digits.search(d))
def csv_writer(data, path):
'''
... |
from django.apps import AppConfig
from django.conf import settings
from django.core.checks import Error, Warning, register
DEFAULT_CONFIG = {
'NAGIOS_CACHE_URL': None,
'NAGIOS_CACHE_USER': None,
'NAGIOS_CACHE_PASSWORD': None,
'NAGIOS_CACHE_CLEANCOMMAND_DAYS': 1,
'NAGIOS_CACHE_CLEANCOMMAND_HOURS': ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from pants.backend.native.config.environment import Assembler, CCompiler, CppCompiler, Linker
from pants.engine.rules import RootRule, rule
from pants.engine.selectors import Select
from pants.subsystem.subsystem import Subsy... |
#!/usr/bin/env python
#
# setup for DLCoal library packages
#
# use the following to install:
# python setup.py install
#
from distutils.core import setup, Extension
import dlcoal
VERSION = dlcoal.PROGRAM_VERSION_TEXT
setup(
name='dlcoal',
version=VERSION,
description='Reconstruction with Duplication... |
import unittest
from enum import Enum
from airflow.utils.weekday import WeekDay
class TestWeekDay(unittest.TestCase):
def test_weekday_enum_length(self):
assert len(WeekDay) == 7
def test_weekday_name_value(self):
weekdays = "MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY"
... |
import dash
from dash.dependencies import Input, Output
from utils import get_props
from dash_table import DataTable
from dash_html_components import Div, Button
from selenium.webdriver.common.action_chains import ActionChains
import pytest
def get_app(props=dict(), special=False, clear=False):
app = dash.Dash(... |
# -*- coding: utf-8 -*-
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import csv, gzip, os
from pyqtgraph import Point
class GlassDB:
"""
Database of dispersion coefficients for Schott glasses
+ Corning 7980
"""
def __init__(self, fileName='schott_glasses.csv'):
... |
import subprocess #nosec
from django.http import HttpResponse
from django.shortcuts import render
from django.conf import settings
def index(request):
html = (
'<html><body><ul>'
'<li><a href="/health/check-system">check-system</a> - View OS health (from "top").</li>'
'<li><a href="/health... |
#!/usr/bin/env python
"""Tests the mysql data store."""
# pylint: disable=unused-import,g-bad-import-order
from grr.lib import server_plugins
# pylint: enable=unused-import,g-bad-import-order
from grr.lib import access_control
from grr.lib import config_lib
from grr.lib import data_store
from grr.lib import data_sto... |
from __future__ import absolute_import
import unittest
from telemetry.util import js_template
class JavaScriptTemplateTest(unittest.TestCase):
def testRenderSimple(self):
self.assertEquals(
js_template.Render(
'foo({{ a }}, {{ b }}, {{ c }})',
a=42, b='hello', c=['x', 'y']),
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# v0.2 by meigrafd
#
# http://www.forum-raspberrypi.de/Thread-python-python-script-funktioniert-nach-dem-start-nach-einiger-zeit-nicht-mehr?pid=134304#pid134304
#
# http://jigfoot.com/hatworshipblog/?p=60
#
import sys
from time import *
import mpd
import RPi.GPIO as GPIO
imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Shawling'
' url handlers '
import re, time, json, logging, hashlib, base64, asyncio
from PIL import Image
from aiohttp import web
import os
from coroweb import get, post
from apis import Page, APIValueError, APIResourceNotFoundError, APIPermissionError
fro... |
from unittest import TestCase
from classes.categories import Categories
class TestCategories(TestCase):
"""
This class will handle all the functions to test for the category name
"""
def setUp(self):
"""
This method defines the test fixture for all test to be undertaken
"""
... |
import sys
import zipfile
from os import environ as env, mkdir, path
from subprocess import CalledProcessError, check_call
platform = sys.platform
includes = []
if platform == 'win32':
archString = '' if (maxsize > 2 ** 32) else ' (x86)'
base = 'C:\\Program Files{}\\Assimp'.format(archString)
includePath ... |
from atomicwrite import AtomicWrite
### classe front: gestione del frontale (display e leds)
class Front:
def __init__(self):
self.leds = list("0" * 64)
print "Frontale inizializzato:", self.leds
def changeBand(self, band):
print "Cambiata banda:",band
AtomicWrite.writeFile("/tmp/band.txt",... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpRe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Interface for indexed gzipped files
@author: Manuel Koesters
"""
# Python mzML module - pymzml
# Copyright (C) 2010-2019 M. Kösters, C. Fufezan
# The MIT License (MIT)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of th... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select, WebDriverWait
class ProjectsPage(object):
path = '/projects'
page_heading_locator = (By.TAG_NAME, 'h1')
add_project_button_locator = (By.CSS_SELEC... |
import os
import stat
import shutil
from cerbero.commands import Command, register_command
from cerbero.config import CONFIG_DIR
from cerbero.utils import _, N_, shell, ArgparseArgument
import cerbero.utils.messages as m
def _onerror(func, path, exc_info):
if not os.access(path, os.W_OK):
os.chmod(path, ... |
#!/usr/bin/env python
import collections
import itertools
import os
import sys
from functools import partial
import six
from pathos.multiprocessing import Pool
import pandas as pd
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder
from PyAnalysisTools.base import get_default_argparser, default_ini... |
import numpy as np
from gpaw import debug
from gpaw.utilities import divrl, is_contiguous
import _gpaw
class Spline:
def __init__(self, l, rmax, f_g, r_g=None, beta=None, points=25):
"""Spline(l, rcut, list) -> Spline object
The integer l gives the angular momentum quantum number and
the... |
"""
concerts/management/commands/refresh_heroku.py
Flushes and re-seeds the DB from Artist, Venue, and Concert fixtures,
then runs the make_matches management commmand to populate ConcertMatch table.
This workflow is currently necessary due to being unable to scrape the
Subterranean site from Heroku. cf. concerts/buf... |
import time
import paramiko
import logging
import ast
from cfgm_common.vnc_kombu import VncKombuClient
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from issu_contrail_common import ICCassandraClient
from issu_contrail_common import ICCassandraInfo
import issu_contrail_config
class ICAmqpInfo():
def __... |
from snack import *
from configscreen import *
LIST_PAGE = 1
CONFIRM_PAGE = 2
UNDEFINE_PAGE = 3
class UndefineNetworkConfigScreen(NetworkListConfigScreen):
def __init__(self):
NetworkListConfigScreen.__init__(self, "Undefine A Network")
def get_elements_for_page(self, screen, page):
if ... |
from unittest import main
from os.path import join, exists
from os import remove
from json import loads
from qiita_pet.test.tornado_test_base import TestHandlerBase
from qiita_db.util import get_count, get_mountpoint
from qiita_db.metadata_template.prep_template import PrepTemplate
class TestPrepTemplateHandler(Test... |
import gtk
import gobject
import os
import re
import adesk.core as Core
import adesk.barconf as BarConf
import adesk.ui as ui
# position in list
ID_ICON = 0
ID_NAME = 1
ID_CMD = 2
ID_IMG = 3
class config(gtk.Frame):
def __init__(self, conf, ind):
gtk.Frame.__init__(self)
self.conf = conf
... |
import sys
import os
import dlib
import glob
from skimage import io
if len(sys.argv) != 2:
print(
"Give the path to the trained shape predictor model as the first "
"argument and then the directory containing the facial images.\n"
"For example, if you are in the python_examples folder then ... |
"""
A minimal SAX application that just prints out the document-handler events
it receives.
"""
import sys
from xml.sax import saxexts
# --- SAXtracer
class SAXtracer:
def __init__(self,objname):
self.objname=objname
self.met_name=""
def __getattr__(self,name):
self.met_name=name # ... |
import sys
from numpy import arange, concatenate
from pypower.get_reorder import get_reorder
from pypower.set_reorder import set_reorder
def i2e_data(ppc, val, oldval, ordering, dim=0):
"""Converts data from internal to external bus numbering.
For a case dict using internal indexing, this function can be
... |
import abc
import six
from tacker.api import extensions
from tacker.openstack.common import jsonutils
from tacker.vm import constants
@six.add_metaclass(abc.ABCMeta)
class DeviceMGMTAbstractDriver(extensions.PluginInterface):
@abc.abstractmethod
def get_type(self):
"""Return one of predefined type ... |
"""Generate the yearly PRISM file to hold our data """
import datetime
import sys
import os
import numpy as np
from pyiem import prism
from pyiem.util import ncopen, logger
LOG = logger()
def init_year(ts):
"""
Create a new NetCDF file for a year of our specification!
"""
fn = "/mesonet/data/prism/... |
"""Setup credentials (.env) and application variables (config.yml)"""
import os
import yaml
class Config(object):
"""All configuration for this app is loaded here"""
def __init__(self, **opts):
if (os.environ.get('ENV') != 'prod'): # We are not in Heroku
self.init_environment()
"... |
'''MMRP field and observation classes.'''
from __future__ import print_function
from maka.data.Field import Date, Decimal, Float, Integer, String, Time
from maka.data.Observation import Observation
'''
How to specify string formatting and parsing?
I like the idea of using format strings somewhat like those of... |
import datetime
import pytz
from pyramid.httpexceptions import HTTPFound
from dace.util import getSite
from dace.objectofcollaboration.principal.util import (
has_role,
grant_roles,
get_current)
from dace.processinstance.activity import (
InfiniteCardinality,
ActionType)
from ..user_management.b... |
#pylint: disable=C0111
#pylint: disable=W0621
from lettuce import world, step
from lettuce.django import django_url
from course_modes.models import CourseMode
from nose.tools import assert_equal
def create_cert_course():
world.clear_courses()
org = 'edx'
number = '999'
name = 'Certificates'
course... |
# stdlib
import math
# third party
import torch
import torch.nn as nn
import torch.nn.functional as F
class RNNModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(
self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False
):... |
"""
Tests for posting/ingetsting dflow and ripcas data to each respective model
to/from the virtual watershed.
"""
import glob
import numpy
import os
import shutil
import traceback
import unittest
import numpy as np
from click.testing import CliRunner
from netCDF4 import Dataset
from cord import (
ESRIAsc, Pol, r... |
from django.db.models import Aggregate, CharField
class BitAnd(Aggregate):
function = "BIT_AND"
name = "bitand"
class BitOr(Aggregate):
function = "BIT_OR"
name = "bitor"
class BitXor(Aggregate):
function = "BIT_XOR"
name = "bitxor"
class GroupConcat(Aggregate):
function = "GROUP_CON... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" read.py
A script to read the downloaded xls.
:copyright: Copyright (c) 2015 daisuzu
:license: MIT
"""
import argparse
import datetime
import json
from logging import (
getLogger,
Formatter,
StreamHandler,
INFO,
)
logger = getLogger(__name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.