text stringlengths 17 737k |
|---|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn, Tensor
from typing import List, Optional, Dict
from .image_list import ImageList
class AnchorGenerator(nn.Module):
"""
Module that generates anchors for a set of feature maps and
image sizes.
T... |
import sys
import re
import time as sleeper
import operator
from datetime import date, datetime, time
from threading import Thread, Event
from hydeengine import url
from hydeengine.file_system import File, Folder
class SiteResource(object):
def __init__(self, a_file, node):
super(SiteResource, self).__in... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2005 Edgewall Software
# Copyright (C) 2003-2005 Jonas Borgström <jonas@edgewall.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at htt... |
"""Entry point."""
import argparse
import msvcrt
import sys
from src import pytorch_impl as pyti
from src import tensorflow_impl as tfi
def training_prompt():
"""
Prompts the user with a warning message about overwriting the saved model.
"""
print('WARNING: Training will overwrite the saved model (i... |
# -*- coding: utf-8 -*-
# Author: trummerjo
# Module: MSLHttpRequestHandler
# Created on: 26.01.2017
# License: MIT https://goo.gl/5bMj3H
"""Proxy service to convert manifest and provide license data"""
from __future__ import unicode_literals
import re
import zlib
import json
import time
import base64
from functools i... |
import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController
from pySDC.core.Lagrange import LagrangeApproximation
class SwitchEstimator(ConvergenceController):
"""
Method to estimate a discrete event (switch)
"""
def setup(self, controller, params, description):
... |
import argparse
import cgi
import ipaddress
import socket
import urllib
import wsgiref
import prometheus_client
import igd
def main():
'''
You are here.
'''
parser = argparse.ArgumentParser()
parser.add_argument('--bind-address', type=ipaddress.ip_address, default='::', help='IPv6 or IPv4 address... |
'''
Generate Master TSNR ensemble DFLUX files. See doc. 4723. Note: in this
instance, ensemble avg. of flux is written, in order to efficiently generate
tile depths.
'''
import os
import sys
import argparse
import numpy as np
from pkg_resources import resource_filename
import astropy.io.fits as fits
from astropy.tab... |
#!/usr/bin/env python
'''
CRISPResso - Luca Pinello 2015
Software pipeline for the analysis of CRISPR-Cas9 genome editing outcomes from deep sequencing data
https://github.com/lucapinello/CRISPResso
'''
__version__ = "0.7.0"
import sys
import os
import subprocess as sb
import argparse
import re
import gzip
import cPi... |
"""
Classes that provide adjusting to the ImgDataset.
These preprocess data but the name preprocessor is not used to avoid
confusion with pylearn2 preprocessors.
"""
__authors__ = "Nicu Tofan"
__copyright__ = "Copyright 2015, Nicu Tofan"
__credits__ = ["Nicu Tofan"]
__license__ = "3-clause BSD"
__maintainer__ = "Nicu ... |
import logging
import asyncio
import random
import datetime
import discord
import wolframalpha
import pyowm
from discord.ext import commands
from .common import Cog
log = logging.getLogger(__name__)
W_CLEAR_SKY = ':sunny:'
W_FEW_CLOUDS = ':white_sun_small_cloud:'
W_SCATTERED_CLOUDS = ':partly... |
"""Plugin Framework Extension"""
import os
import sys
import glob
import imp
from ..core import backend, handler, plugin, exc
from ..utils.misc import is_true, minimal_logger
from ..utils.fs import abspath
LOG = minimal_logger(__name__)
# FIX ME: This is a redundant name... ?
class CementPluginHandler(plugin.Cemen... |
#!/usr/bin/env python3
from __future__ import print_function
import os
from os import environ, chmod
import json
import hashlib
import logging
import requests
from types import GeneratorType
from collections import Counter, defaultdict
try:
from urllib.parse import urlencode
except ImportError:
from urllib imp... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Simple command line interface o trac.
It provides high level interactions with the trac to make automatic task be
quick.
TracCmd may be used as is, however, it should be inherited from to add commands
specific to your projects.
"""
import xmlrpclib
import ConfigParser... |
#!/usr/bin/env python
import os
import re
import urllib
import csv
import datetime
import time
from string import Template
from optparse import OptionParser
last_tag_pattern = 'EMPATHY_3_7*'
upload_server = 'master.gnome.org'
template = '''\
$name $version is now available for download from:
$download
$md5sums
What... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Inverted index utilities for YakDB.
"""
from YakDB.Utils import YakDBUtils
from YakDB.ConnectionBase import YakDBConnectionBase
from YakDB.Iterators import KeyValueIterator
import itertools
class InvertedIndex(object):
"""
An inverted index wrapper for YakDB t... |
# A Segment is the building block of Sequence Class. They are responsible
# for resolving pulse timing, Z gates, generating trigger pulses and adding
# charge compensation
#
# author: Michael Kerschbaum
# created: 4/2019
import numpy as np
import math
import logging
import datetime
from pycqed.utilities.timer import ... |
import warnings
import pytest
import numpy as np
from scipy import sparse
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.base import clone
from sklearn.preprocessing import maxabs_scale
from sklearn.preprocessing import minmax_scale
from sklearn.preprocessi... |
from __future__ import division, print_function
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patches as patches
import numpy as np
from array import array
import pygame
import plots
import time
UNINITIALIZED = 0
INITIALIZED = 1
EXIT = 2
FINISHED = 3
class Cursor(o... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.agent import agent
from lib.core.common import arrayizeValue
from lib.core.common import Backend
from lib.core.common import filterPairValues
from lib... |
"""
Admin configuration for ``icekit_events`` app.
"""
# Define `list_display`, `list_filter` and `search_fields` for each model.
# These go a long way to making the admin more usable.
from datetime import timedelta
from dateutil import rrule
import datetime
import json
import logging
import six
from django.contrib ... |
# -*- coding: utf-8 -*-
"""This is the part that connects the logic of the tractome
functionalities to the GUI.
Copyright (c) 2012-2014, Emanuele Olivetti and Eleftherios Garyfallidis
Distributed under the BSD 3-clause license. See COPYING.txt.
"""
import pyglet
debug = False
pyglet.options['debug_gl'] = debug
pygl... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012-2013 IBM Corp.
# All Rights Reserved.
#
# 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 Li... |
from flask.ext.script import Command, Option
from flask import current_app
from skylines.model import db, Flight
from skylines.worker import tasks
from selector import selector_options, select
class FindMeetings(Command):
""" Find meetings points between flights """
option_list = selector_options + (
... |
#!/usr/bin/env python
# vim: ts=4:sw=4:et:sts=4:ai:tw=80
from utils import StringContext,krb_wrapper
import nagiosplugin
import argparse
import subprocess,os,re
import ast
def parser():
version="0.1"
parser = argparse.ArgumentParser(description="Check zookeeper znodes existence and content")
parser.add_arg... |
import unittest
import cvxpy as cp
import numpy as np
import numpy.random as npr
import torch
from torch.autograd import grad
from cvxpylayers.torch import CvxpyLayer
import diffcp
def set_seed(x):
npr.seed(x)
torch.manual_seed(x)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
class TestCvxpyLayer(unit... |
import unittest
import numpy as np
import tensorflow as tf
from GPflow.tf_wraps import vec_to_tri, tri_to_vec
from tensorflow.python.ops.gradient_checker import compute_gradient_error
def np_vec_to_tri(vec):
ml = None
for svec in vec:
n = int(np.floor((vec.shape[1] * 8 + 1) ** 0.5 / 2.0 - 0.5))
... |
# Copyright 2021 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, ... |
"""Pytest configuration module.
Contains fixtures, which are tightly bound to the Cheroot framework
itself, useless for end-users' app testing.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import threading
import time
import pytest
from ..server import Gateway, HTTPServ... |
#!/usr/bin/env python
import sys, os, time, socket
PORT = 1337
def server():
print "server"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", PORT))
s.listen(1)
while 1:
conn, addr = s.accept()
print "connected by", addr
while 1:
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2016 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
#
# Authors: Aric Hagberg <aric.hagberg@gmail.com>
# Sérgio Nery Simões <sergionery@gmail.com>
"""
Co... |
from __future__ import print_function
from __future__ import unicode_literals
import io
import logging
import os
import random
import subprocess
import re
import tempfile
import threading
import sys
import shutil
from imagemounter import util, FILE_SYSTEM_TYPES
logger = logging.getLogger(__name__)
FILE_SYSTEM_GUID... |
#
# Copyright 2018 Analytics Zoo Authors.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
from thinglang.compiler.buffer import CompilationBuffer
from thinglang.lexer.lexical_definitions import REVERSE_OPERATORS
from thinglang.lexer.operators.binary import LexicalAddition, LexicalSubtraction, LexicalMultiplication, \
LexicalDivision, SecondOrderLexicalBinaryOperation, FirstOrderLexicalBinaryOperation
fr... |
#!/usr/bin/env python
"""Parse and print the list of logs, after validating signature."""
import base64
import datetime
import hashlib
import json
import math
import os
import sys
import gflags
import jsonschema
import M2Crypto
FLAGS = gflags.FLAGS
gflags.DEFINE_string("log_list", None, "Logs list file to parse an... |
# -*- coding: utf-8 -*-
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
import ssl
import xmlrpc
from datetime import datetime
from functools import reduce
from odoo import api, models, fields
_logger = logging.getLogger(__n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" ff - Easily search and process files.
http://mysz.github.io/ff
Author: Marcin Sztolcman (marcin@urzenia.net)
Get help with: ff --help
Information about version: ff --version
"""
from __future__ import print_function, unicode_literals
import argparse
... |
# -*- coding: utf-8 -*-
from Chessnut import Game
from test_helpers import heuristic_gen, get_successors
from node import Node
import heuristics
class Test_Engine():
def __init__(self):
self.game = Game()
self.computer = AI(self.game, 3)
def prompt_user(self):
self.computer.print_boar... |
ATTRIBUTES = ('font_name',
'font_size',
'font_color',
'bold',
'italic',
'font_script',
'num_format',
'text_v_align',
'text_h_align',
'text_wrap',
'bg_color',
... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
################################################################################
##
## Copyright (C) 2012 Typhos
##
## This Source Code Form is subject to the terms of the Mozilla Public
## License, v. 2.0. If a copy of the MPL was not distributed with this
## file, You can... |
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either... |
#! /usr/bin/python3
# vim: set expandtab tabstop=4 shiftwidth=4 :
"""Module to retrieve webcomics"""
from comic_abstract import GenericComic, get_date_for_comic
import re
from datetime import date, timedelta
import datetime
from urlfunctions import get_soup_at_url, urljoin_wrapper,\
convert_iri_to_plain_ascii_uri,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Licen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" filter points on a vertical section
command line parameters: input_file, x1, y1, x2, y2, tolerance
vertical plain is defined by (x1,y1) and (x2,y2)
"""
import sys
from math import hypot
import numpy as np
if len(sys.argv) < 7:
print("usage: {} file x1 y1 x2... |
import os
import gzip
import json
import time
import errno
import random
import urllib
from datetime import datetime
import idiokit
from idiokit.xmpp.jid import JID
from abusehelper.core import bot, events, taskfarm, utils
def ensure_dir(dir_name):
"""
Ensure that the directory exists (create if necessary) ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import threading
import Queue
_QUEUE = Queue.Queue()
run_on_main_thread = _QUEUE.put
_THREAD = threading.current_thread()
def run_one(timeout=None):
assert threading.current_thread() is _THREAD
while True:
try:
_QUEUE.g... |
################################################################################
# Copyright (C) 2016-2019 Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... |
#!/usr/bin/env python3
# For various reasons we need the contents of certain files to be
# duplicated in two places, for example stdlib/2and3/builtins.pyi and
# stdlib/2/__builtin__.pyi must be identical. In the past we used
# symlinks but that doesn't always work on Windows, so now you must
# manually update both fi... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules
~~~~~~~~~~~~
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import pygogo as gogo
from functools import partial, wraps
from itertools import chain
from builtins import iter, len, list, map, next, sum as... |
import socket
import idiokit
import urlparse
from abusehelper.core import utils, bot, events
FEED_URL = "http://vxvault.siri-urz.net/URL_List.php"
def i_am_a_name(string):
for addr_type in (socket.AF_INET, socket.AF_INET6):
try:
socket.inet_ntop(addr_type, socket.inet_pton(addr_type, string)... |
#!/usr/bin/python
import os
from optparse import OptionParser
from core.core import TvRenamr
from core.errors import *
parser = OptionParser()
parser.add_option('-e', '--episode', dest='episode', help='Set the episode number. Currently this will cause errors when working with more than one file')
parser.add_option('... |
"""
The String() class provided in this library allows a more object-oriented usage pattern and adds
several convenience methods that are not available in the standard library. String() inherits from
str and overrides all of its methods that return strings, so that the return value is itself a
String(), which en... |
import re
import sys
import datetime
from pandajedi.jediconfig import jedi_config
from pandajedi.jedicore.MsgWrapper import MsgWrapper
from pandajedi.jedicore.SiteCandidate import SiteCandidate
from pandajedi.jedicore import Interaction
from pandajedi.jedicore import JediCoreUtils
from JobBrokerBase import JobBrokerBa... |
from __future__ import division
from __future__ import print_function
import csv
import pickle
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import data_dirs
DATADIR = data_dirs.gtsrb
NUM_LABELS = 43
IMAGE_SHAPE = [40, 40, 3]
def get_data(name):
"""Utility for convenient data loadi... |
import time
import os
import platform
print("Restarting in 3 seconds...")
time.sleep(3)
print("Restarting...")
if(platform.system() == "Linux"):
os.system("python3 nabbot.py")
else:
os.system("python nabbot.py")
|
from __future__ import absolute_import
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
import math
import numpy
import wx
import time
from Cura.util import meshLoader
from Cura.util import util3d
from Cura.util import profile
from Cura.util.resources import getPathForMesh... |
# global imports
import cython
import logging
import itertools
from collections import Counter
import re
# local imports
# Assume that OB is not installed by default
INSTALLED_BACKENDS = {
'OB': False,
}
try:
import openbabel
INSTALLED_BACKENDS['OB'] = True
except :
pass
from rdkit import Chem
fro... |
#!/usr/bin/env python
"""Python daemonization lib
"""
from daemonize import Daemonize
import argparse
import sys
import os
import analysis.datafetch.twitter_fetch as tw
import logging
import logging.config
import json
import settings
LOG = logging.getLogger(__name__)
class Twitterd(object):
""" Twitter Daemon Cla... |
# -*- coding: utf-8 -*-
from random import randint
from django.core import mail
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from faker import Faker
from symposion.proposals.models import AdditionalSpeaker
from symposion.schedule.tests.factories import (
ProposalKindFacto... |
#!/usr/bin/env python3
from collections import OrderedDict
import json
import os
import sys
def is_ref(node):
return isinstance(node, type({})) and list(node.keys()) == ['$ref']
def frag_unesc(s):
return s\
.replace('~1', '/')\
.replace('~0', '~')
def frag_parse(s):
if s == '':
r... |
from .syllables import count_syllables
from .utils import line_iter, filter_line, prune_dict
from .sorting import Coupler, Rhymer, Haikuer, Limericker
import filters
|
#!/usr/bin/env python3
# pylint: disable=missing-docstring,not-an-iterable,too-many-locals,too-many-arguments,too-many-branches,invalid-name,duplicate-code,too-many-statements
import datetime
import collections
import itertools
from itertools import dropwhile
import copy
import pendulum
import pymysql
import singer... |
from google.appengine.ext import db
from google.appengine.api.users import User
from freetalks import models
import datetime
def clear_type(obj_type):
obj_list = obj_type.all()
for obj in obj_list:
obj.delete()
def put_list(obj_list):
for obj in obj_list:
obj.put()
def clear():
clear_... |
import urllib2
import socket
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter, MONDAY, FRIDAY
def init_plot():
ax = plt.gca()
ax.set_xmargin(0.02)
ax.set_ymargin(0.02)
def show_plot():
#days = WeekdayLocator(MONDAY)
days = WeekdayLocator(FRI... |
import requests, json
from time import sleep
def bmctest():
idtypes = ["doi"]
size = 1000
wait = False
# get some records from the OCC corpus
# http://test.cottagelabs.com:9200
addr = 'http://test.cottagelabs.com:9200/occ/record/_search?q=identifier.id:*10.1186*%20AND%20identifier.type.exact... |
import esp
class FlashBdev:
SEC_SIZE = 4096
START_SEC = 0x89000 // SEC_SIZE
NUM_BLK = 0x73
def __init__(self, blocks=NUM_BLK):
self.blocks = blocks
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
esp.flash_read((n + self.START_SEC) ... |
import ConfigParser
import re
from functools import total_ordering
import sys
import clg
import os
import glob
import yaml
import yamlordereddictloader
from cli import exceptions
from cli import logger
from cli import utils
LOG = logger.LOG
SPEC_EXTENSION = '.spec'
@total_ordering
class ValueArgument(object):
... |
#!/usr/bin/env python3
import ctypes
import json
import os
import sys
from ctypes.util import find_library
from time import sleep
assert("linux" in sys.platform)
x11 = ctypes.cdll.LoadLibrary(find_library("X11"))
display = x11.XOpenDisplay(None)
# This contains the keyboard state.
# 32 bytes, with each bit represe... |
from tapiriik.database import db, cachedb
from tapiriik.services import Service, ServiceRecord, APIAuthorizationException, APIExcludeActivity, ServiceException, ServiceWarning
from datetime import datetime, timedelta
import sys
import os
import traceback
import pprint
import copy
import pytz
import random
d... |
"""
@brief test log(time=40s)
"""
import sys
import os
import unittest
import shutil
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if path not i... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""Define a class for creating the jailed context."""
import os
import shutil
import stat
from pathlib import Path
from retry.api import retry_call
import framework.utils as utils
import framework.defs as de... |
# Common stuff for the pyWWA ingestors...
from twisted.internet import reactor
from twisted.words.xish import domish
from twisted.python import log
from twisted.mail import smtp
from twisted.web import client
import twisted.web.error as weberror
from twisted.words.xish.xmlstream import STREAM_END_EVENT
from twisted.in... |
import glob, imp, os, traceback, time, shelve
minlevel = 1
arguments = ["self", "info", "world"]
keyword = "PRIVMSG"
def main(self, info, world) :
"""This is the essentials"""
"""Is executed when sonicbot receives the PRIVMSG command"""
if info["message"] == "\x01VERSION\x01" :
self.notice(info["sen... |
from tkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename
import csv
import sys, traceback
import tableau
import tour
import fou
import cavalier
import pion
import roi
import reine
from piece import piece
from chess_interface import chessInterface
import queue
import time
class chess_tki... |
import os
import sys
from django.conf import global_settings as defaults
from django.template.loader import add_to_builtins
class SitesAllowedHosts(object):
"""
This is a fallback for Django 1.5's ALLOWED_HOSTS setting
which is required when DEBUG is False. It looks up the
``Site`` model and uses an... |
from tapiriik.database import db, cachedb, redis
from tapiriik.messagequeue import mq
from tapiriik.services import Service, ServiceRecord, APIExcludeActivity, ServiceException, ServiceExceptionScope, ServiceWarning, UserException, UserExceptionType
from tapiriik.settings import USER_SYNC_LOGS, DISABLED_SERVICES, WI... |
import string
_accessstrings = {0: "", 1: "readonly", 2: "executeonly", 3: "noaccess"}
class ps_object:
literal = 1
access = 0
value = None
def __init__(self, value):
self.value = value
self.type = self.__class__.__name__[3:] + "type"
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__[3... |
#
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# Thi... |
#!/usr/bin/env python
from __future__ import print_function
# png.py - PNG encoder/decoder in pure Python
#
# Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org>
# Portions Copyright (C) 2009 David Jones <drj@pobox.com>
# And probably portions Copyright (C) 2006 Nicko van Someren <nicko@nicko.org>
#
# Orig... |
# -*- coding: utf-8 -*-
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
"""Django settings for Pontoon."""
import os
import socket
from django.utils.functional import lazy
import dj_database_url
_dirname = os.path.dirname
ROOT = _dirname(_dirname(_dirname(os.path.abspath(__file__))))
def path(*args):
return os.path.join(ROOT, *args)
# Environment-dependent settings. These are ... |
import unittest
import mock
from tests.test_app.sqlalchemy import create_app as create_sql_app
from tests.test_app.mongoengine import create_app as create_mongo_app
from tests.test_app.peewee_app import create_app as create_peewee_app
def get_mock_twitter_response():
return {
'oauth_token_secret': 'the_... |
import struct
import logging
import pymongo as mongo
from ofinterface import *
import rflib.ipc.IPC as IPC
import rflib.ipc.MongoIPC as MongoIPC
from rflib.ipc.RFProtocol import *
from rflib.ipc.RFProtocolFactory import RFProtocolFactory
from rflib.defs import *
from ryu.base import app_manager
from ryu.controller ... |
#! /usr/bin/env python
from common.util.pdbwrap import *
global cls_reg
cls_reg = {}
global _gensym_ctr
_gensym_ctr=0
print "_gensym_ctr is",_gensym_ctr
def gensym():
global _gensym_ctr
ret = '_G' + `_gensym_ctr`
_gensym_ctr += 1
return ret
class cls_decl(object):
def __init__(self,
... |
#!/usr/bin/env python
# $URL$
# $Rev$
# png.py - PNG encoder/decoder in pure Python
#
# Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org>
# Portions Copyright (C) 2009 David Jones <drj@pobox.com>
# And probably portions Copyright (C) 2006 Nicko van Someren <nicko@nicko.org>
#
# Original concept by Johann... |
"""
JSON API for the Order app
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url, include
from django.db.models import Q, F
from django_filters import rest_framework as rest_filters
from rest_framework import generics
from rest_framework import filters, status
from ... |
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this module, see PEP 324.
#
# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
#
# Licensed to PSF under a Contributor Agreement.
# See http://www.python.org/2.4/license for licensing details.
r"""subprocess - Subpr... |
import logging
import os
import sys
import time
from keystoneclient.v3 import client as keystoneclient
from neutronclient.neutron import client as neutronclient
from novaclient import client as novaclient
from novaclient import exceptions as nova_exceptions
from keystoneclient import session as ksc_session
from keyst... |
"""Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engin... |
from discord.ext import commands
from .utils import checks, db, fuzzy, cache, time
import asyncio
import discord
import re
import zlib
import io
import os
import lxml.etree as etree
from collections import Counter
DISCORD_API_ID = 81384788765712384
DISCORD_BOTS_ID = 110373943822540800
USER_BOTS_ROLE = 17855825... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutStringManipulation(Koan):
def test_use_format_to_interpolate_variables(self):
value1 = 'one'
value2 = 2
string = "The values are {0} and {1}".format(value1, value2)
self.assertEqual("The values are ... |
from django.contrib import admin
from aspc.senate.models import Position, Appointment, Document
class PositionAdmin(admin.ModelAdmin):
list_display = ("title", "description", "sort_order",)
class DocumentAdmin(admin.ModelAdmin):
def public_url(self, obj):
return obj.file.url
public_url.short_desc... |
import csv
import mimetypes
import tempfile
import time
from collections import defaultdict
from enum import Enum
from gi.repository import Gtk, GObject, Pango, Gdk, Gio
class Results(Gtk.Notebook):
def __init__(self, worksheet):
super(Results, self).__init__()
self.win = worksheet.win
s... |
# multi.py
# Ronald L. Rivest
# June 15, 2017
# python3
"""
Prototype code for auditing an election having both multiple contests and
multiple paper ballot collections (e.g. multiple jurisdictions).
Relevant to Colorado state-wide post-election audits in 2017.
"""
"""
Assumes each paper ballot collection is 'pure' in... |
import data, utility, metrics
import time
import numpy as np
from math import sqrt, exp, log, ceil
from scipy.stats.stats import pearsonr
from sklearn.metrics import roc_auc_score
import db.db as db
import visualization
from config import config as cc
import yaml
import socket
# not used to relieve MetaCentrum of ... |
"""Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for ... |
from numpy import array, prod
from nibabel import load
from nibabel.trackvis import aff_to_hdr, empty_header, write
from dipy.reconst.dti import Tensor
from dipy.io.bvectxt import read_bvec_file
from dipy.tracking.fact_tracking import seeds_from_mask, track_tensor
img = load('E8885S6I1.nii.gz')
hdr = img.get_header()
... |
import sys, os
import wx
import numpy
import time
import copy
import math
import string
from sans.guiframe.utils import format_number,check_float
from sans.guicomm.events import StatusEvent
import pagestate
from pagestate import PageState
(PageInfoEvent, EVT_PAGE_INFO) = wx.lib.newevent.NewEvent()
(Pre... |
import datetime
import requests
import load_config
from discord import utils
from discord.ext import commands
from discord.ext.commands import bot
from config.server_config import ServerConfig
def is_gss():
return commands.check(lambda ctx: ctx.guild.id == 393764974444675073)
def is_not_nsfw_disabled():
def predic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.