content stringlengths 4 20k |
|---|
import sys
from os.path import basename
from img import (
FormatOptions, ImageFileReader, create_geotiff, DT2GDT, DEF_GEOTIFF_FOPT,
)
from img.cli import error
def usage():
"""Print a short command usage help."""
exename = basename(sys.argv[0])
print >>sys.stderr, (
"USAGE: %s <master> <output>... |
"""Configuration file for eruption scenario
Tephra modelling validation worksheet
Scenario Name: Mount Merapi 2009 (Fictious scenario VEI5)
Run Date:
Run number:R1 ... |
class UaStateGeneric(object):
sname = 'Generic'
ua = None
connected = False
dead = False
def __init__(self, ua):
self.ua = ua
def recvRequest(self, req):
return None
def recvResponse(self, resp):
return None
def recvEvent(self, event):
return None
... |
# -*- coding:utf-8 -*-
# This code is automatically transpiled by Saklient Translator
import six
from ...errors.saklientexception import SaklientException
from ..client import Client
from .resource import Resource
from ..enums.escope import EScope
from ...util import Util
import saklient
str = six.text_type
# module... |
import datetime, string
from packer import Packer
from datatypes import serial, timestamp, RangedSet, Struct, UUID
from ops import Compound, PRIMITIVE, COMPOUND
class CodecException(Exception): pass
def direct(t):
return lambda x: t
def map_str(s):
for c in s:
if ord(c) >= 0x80:
return "vbin16"
retur... |
from .utils import NamespacedClient, query_params, _make_path
class CatClient(NamespacedClient):
@query_params('h', 'help', 'local', 'master_timeout', 'v')
def aliases(self, name=None, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cat-alias.html>`_
... |
#Swami skel module for the Swami Control Panel
LightDMConf = "/etc/lightdm/lightdm.conf"
XsessionsDir = "/usr/share/xsessions"
import esudo.esudo as esudo
from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL
from efl import elementary
from efl.elementary.button import Button
from efl.elementary.box import Box
from ... |
"""
A general purpose asynchronous framework, supporting the asynchronous
primitives (async/await) introduced in Python 3.5.
The original goal was to serve http, and while this capability is still
built-in (see growler.http), the structure of Growler allows for a
larger set of capabilities.
To get started, import `Gr... |
import logging
import luigi
import sciluigi as sl
import os
import six.moves as s
import time
import unittest
TESTFILE_PATH = '/tmp/test.out'
log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)
class MultiInOutWf(sl.WorkflowTask):
def workflow(self):
mo = self.new_task('mout', Mul... |
import pytest
from distributed import Worker, WorkerPlugin
from distributed.utils_test import gen_cluster
class MyPlugin(WorkerPlugin):
name = "MyPlugin"
def __init__(self, data, expected_transitions=None):
self.data = data
self.expected_transitions = expected_transitions
def setup(self... |
import enum
from http11 import c
def _element_callback(func):
def inner(buf, length):
try:
func(c.ffi.buffer(buf, length)[:])
except:
# TODO: Do we really want this to be a bare except?
return c.lib.EERROR
else:
return 0
return inner
d... |
import sys
sys.path.append('/root/darkflow')
from net.build import TFNet
from basecomponent import BaseComponent
from annotator import annotate
class DeepDetector(BaseComponent):
'''
A DeepDetector uses a YOLOv2 convolutional neural network model for
object detection.
'''
def __init__(self, c... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'measurement.ui'
#
# Created by: PyQt5 UI code generator 5.7.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Measurement(object):
def setupUi(self, Measurement):
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_traffic_selector
short_description: Manage IPSec Traf... |
"""
Mock unit tests for the NetApp block storage 7-mode library
"""
from lxml import etree
import mock
from cinder import exception
from cinder import test
import cinder.tests.volume.drivers.netapp.dataontap.fakes as fake
import cinder.tests.volume.drivers.netapp.fakes as na_fakes
from cinder.volume.drivers.netapp.d... |
import numpy as np
import theano.tensor as T
from mozi.datasets.voc import VOC
from mozi.model import Sequential
from mozi.layers.alexnet import Alexnet
from mozi.log import Log
from mozi.train_object import TrainObject
from mozi.cost import error, entropy
from mozi.learning_method import SGD
from mozi.env import set... |
from qingcloud.cli.misc.utils import explode_array
from qingcloud.cli.iaas_client.actions.base import BaseAction
class UpdateRoutersAction(BaseAction):
action = 'UpdateRouters'
command = 'update-routers'
usage = '%(prog)s -r "router_id, ..." [-f <conf_file>]'
@classmethod
def add_ext_arguments(cl... |
# coding: utf-8
from __future__ import division, print_function
__author__ = "adrn <<EMAIL>>"
# Third-party
import astropy.units as u
from ..parse import parse_unit, convert_unit_tweet, alternate_units
convert_tweets = ["Convert 15 lightyears to parsecs",
"Convert 15 km/s to pc/Myr"]
expected_con... |
from datetime import timedelta
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Series
import pandas._testing as tm
from pandas.core.indexes.timedeltas import timedelta_range
def test_asfreq_bug():
df = DataFrame(data=[1, 3], index=[timedelta(), timedelta(minutes=3)])
resul... |
"""Import core names of TensorFlow.
Programs that want to build TensorFlow Ops and Graphs without having to import
the constructors and utilities individually can import this file:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
"""... |
import abc
import pandas as pd
from six import with_metaclass
from zipline.errors import (
AccountControlViolation,
TradingControlViolation,
)
class TradingControl(with_metaclass(abc.ABCMeta)):
"""
Abstract base class representing a fail-safe control on the behavior of any
algorithm.
"""
... |
from msrest.serialization import Model
class PoolPatchOptions(Model):
"""Additional parameters for the Pool_patch operation.
:param timeout: The maximum time that the server can spend processing the
request, in seconds. The default is 30 seconds. Default value: 30 .
:type timeout: int
:param cli... |
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Text, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from audiostash.common.utils import utc_now
Base = declarative_base()
USERLE... |
from django.db import models
from bitfield import BitField
# Create your models here.
class FoodType(models.Model): #vegan
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class FoodCategory(models.Model): #steamed, fried, boiled
name = models.CharField(max_length=200... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
import itertools
from oslo import messaging
from neutron.common import rpc as n_rpc
from neutron.common import topics
from neutron.openstack.common import log as logging
from neutron.openstack.common import timeutils
LOG = logging.getLogger(__name__)
def create_consumers(endpoints, prefix, topic_details):
"""... |
"""
Tests to be run for tutoring
"""
from tutoring.tests.unit import *
from tutoring.tests.functional import *
__all__ = []
def __fill_all():
import tutoring.tests.unit
import tutoring.tests.functional
__all__.extend(tutoring.tests.unit.__all__)
__all__.extend(tutoring.tests.functional.__all__) |
from setuptools import setup
version = '0.1dev'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django',
'django-celery',
'django-extensions',
'django-nose',
'django-filter',
'django-cors-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The TeeworldsMapLib is a python tool which makes it possible to read,
modify and write teeworlds map files easily without using the original
teeworlds client, allowing to built teewor on top of it
:copyright: 2010-2011 by the TML Team, see AUTHORS for m... |
from __future__ import print_function
import re
import time
from botocore.exceptions import ClientError
from . import aws, config, errors, ssh
def _send_command(instance_ids):
document_name = config.get('ssm.document.name')
parameters = config.get('ssm.parameters')
print('[ssha] ssm send {document} t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This code demonstrates how to use dedupe with a comma separated values
(CSV) file. All operations are performed in memory, so will run very
quickly on datasets up to ~10,000 rows.
We start with a CSV file containing our messy data. In this example,
it is listings of early ... |
"""
Created on Oct 14, 2015
Mock class for testing.
@author: Patrik Dufresne <<EMAIL>>
"""
import json
import os
import shutil
import subprocess
import tempfile
import unittest
import cherrypy
from cherrypy.test import helper
import pkg_resources
from rdiffweb.core.config import parse_args
from rdiffweb.core.store ... |
import random
import unittest
from SDWLE.agents.basic_agents import RandomAgent
from SDWLE.cards import GoldshireFootman, MurlocRaider, BloodfenRaptor, FrostwolfGrunt, RiverCrocolisk, \
IronfurGrizzly, MagmaRager, SilverbackPatriarch, ChillwindYeti, SenjinShieldmasta, BootyBayBodyguard, \
FenCreeper, Boulderfis... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Attachment.mimetype'
db.add_column('odk_logger_attachment', 'mimetype', self.gf('django.db... |
import math
import time
t1 = time.time()
# N = 3
# rd = [0,0,0,1,0,1,1,1]
# rc = [0,1,10,101,11,111,110,100]
# rv = [0,1,2,5,3,7,6,4]
# rvf = [0,0,1,2,1,3,3,2] (//2)
# rvl = [0,1,2,1,3,3,2,0] (%4)
N = 5
tp = [1,2,4,8,16,32]
def foo(n):
M = tp[n]
b = tp[n-1]
test = [[0,1]]
ntest = []
r = []
w... |
'''
Set description property of Unique Value legend items from a lookup table. Enables having a legend with lengthy descriptions as well as the record values.
Example:
[SB] Black Spruce Black spruce diagnostic and dominant in sparse tree and
shrub overstory; shrub birch, willow and low ericaceous shru... |
import github
class Stargazer(github.GithubObject.NonCompletableGithubObject):
"""
This class represents Stargazers. The reference can be found here https://developer.github.com/v3/activity/starring/#alternative-response-with-star-creation-timestamps
"""
def __repr__(self):
return self.get__r... |
import os
from PyQt4 import QtGui
from dialogboxes import showMessageBox
from peeroptionsui import Ui_MainWindow
class PeerOptionsUi(QtGui.QMainWindow):
def __init__(self, parent, peer, communicator):
super(PeerOptionsUi, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(sel... |
from odoo import api, exceptions, fields, models, _
class StockWarehouse(models.Model):
_inherit = 'stock.warehouse'
manufacture_to_resupply = fields.Boolean(
'Manufacture in this Warehouse', default=True,
help="When products are manufactured, they can be manufactured in this warehouse.")
... |
# Django settings for JMS project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'JM... |
"""
ZMQ example using python3's asyncio
Ion should be started with the command line arguments:
iond -testnet -daemon \
-zmqpubhashblock=tcp://127.0.0.1:12705 \
-zmqpubrawtx=tcp://127.0.0.1:12705 \
-zmqpubhashtx=tcp://127.0.0.1:12705 \
-zmq... |
from __future__ import absolute_import
from __future__ import division
import itertools
import os
import sys
from os import path
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path.append(os.path.join(curr_path, '../python/common/'))
sys.path.append(os.path.join(curr_path, '../python/uni... |
# __author__ = 'trananhdung'
from openerp import fields, models, api, exceptions
from openerp.tools.translate import _
from openerp.exceptions import ValidationError
from openerp.api import Environment
from threading import Thread
from datetime import datetime
import logging
_logger = logging.getLogger(__na... |
"""
Given:
(1) a file supertagged words (OpenCCC file output format
as produced by, e.g., WordAndPOSDictionaryLabellingStrategy),
(2) a list (as a string) of tagging ambiguity levels (e.g.,
"1.4 1.6 1.8...") that represent the desired tag/word levels
(rounded off at the hundredths place to <=1.41, <=1.61, etc.),
(3)... |
"""SCons.Tool.rpcgen
Tool-specific initialization for RPCGEN tools.
Three normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
... |
import os
def print_info(label, value):
if(value): print '%s: %s' % (label, value)
# Remove a prefix string from another string. This is usefull for removing
# the absolute paths from sub-paths)
def remove_prefix(str, prefix):
str_len = len(str)
prefix_len = len(prefix)
return str[prefix_len+1:str_len]
# Ex... |
# -*- coding: UTF-8 -*-
"""
Based on ``behave tutorial``
Feature: Step Result Table
Scenario: Unordered Result Table Comparison (RowFixture Table)
Given a set of specific users
| name | department |
| Alice | Beer Cans |
| Bob | Beer Cans |
| Charly | Sil... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preorder(bt):
"A preorder traversal of a binary tree"
children = [bt]
while children:
n = children.pop()
if n.right:
children.append(n.right)
if n.lef... |
#!/usr/local/bin/python
''' Save samples from each month to facilitate testing methods '''
import os, sys, glob, re
import datetime
from matplotlib.dates import date2num, num2date
import numpy as np
from calendar import monthrange
import h5py
from sklearn import decomposition
sys.path.insert(0,'/home/wu-jung/code_git... |
"""Update the PATH environment variable to reflect the value of BCBIOPATH.
"""
from __future__ import print_function
import contextlib
import os
from bcbio import utils
def _prepend(original, to_prepend):
"""Prepend paths in a string representing a list of paths to another.
original and to_prepend are expec... |
"""
The NeuralAgent class wraps a deep Q-network for training and testing
in the Arcade learning environment.
Author: Nathan Sprague
"""
import os
import cPickle
import time
import logging
import random
import numpy as np
import ale_data_set
import sys
sys.setrecursionlimit(10000)
class NeuralAgent(object):
... |
from django.conf.urls import include, url
from sapl.protocoloadm.views import (AcompanhamentoDocumentoView,
AcompanhamentoConfirmarView,
AcompanhamentoExcluirView,
AnularProtocoloAdmView,
... |
from django.core.exceptions import ValidationError
from django.test import TestCase
from eventex.core.models import Talk
from eventex.core.models import Course
from eventex.core.managers import PeriodManager
class TalkModelTest(TestCase):
def setUp(self):
self.talk = Talk.objects.create(
tit... |
#!/usr/bin/env python
from datetime import datetime, timedelta
import time
import dns
from dnsdisttests import DNSDistTest
class TestResponseRuleNXDelayed(DNSDistTest):
_config_template = """
newServer{address="127.0.0.1:%s"}
addResponseAction(RCodeRule(dnsdist.NXDOMAIN), DelayResponseAction(1000))
""... |
import math
import sys
base = -2.0
result = ""
number = int(sys.argv[1])
print "converting number " + str(number) + " to negabinary value:"
while number != 0:
ceilOfDivision = int(math.ceil(number / base))
reminder = int(number % base)
result = result + str(int(math.fabs(reminder)))
number = ceilOfDivi... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
import paddle.fluid as fluid
import math
__all__ = ["ResNet", "ResNet50", "ResNet101", "ResNet152"]
train_parameters = {
"input_size": [3, 224, 224],
"input_mean": [0.485, 0.456, 0.406],
... |
"""Part of Lask, the Web Lab Task management system.
Handlers for the LASK HTTP server.
"""
import webapp2
from default_handler import DefaultHandler
from lask.core.model import *
#####################################################################
#
# These handlers allow RESTful interaction with Worker objects
... |
"""
shared options and groups
The principle here is to define options once, but *not* instantiate them
globally. One reason being that options with action='append' can carry state
between parses. pip parse's general options twice internally, and shouldn't
pass on state. To be consistent, all options will follow this d... |
import os.path
import urllib
import duplicity.backend
from duplicity import globals
from duplicity import log
from duplicity.errors import * #@UnusedWildImport
from duplicity import tempdir
class FTPBackend(duplicity.backend.Backend):
"""Connect to remote store using File Transfer Protocol"""
def __init__(sel... |
# coding=utf-8
from random import randint
from locale import bind_textdomain_codeset
import logging
import ipaddress
from socket import inet_aton, inet_ntoa
from blueman.Constants import *
from blueman.Functions import have, mask_ip4_address
from _blueman import get_net_interfaces, get_net_address, get_net_netmask
fro... |
from spack import *
class Nco(AutotoolsPackage):
"""The NCO toolkit manipulates and analyzes data stored in
netCDF-accessible formats"""
homepage = "http://nco.sourceforge.net/"
url = "https://github.com/nco/nco/archive/4.6.7.tar.gz"
version('4.6.7', 'b04c92aa715d3fad3ebebd1fd178ce32')
... |
import requests
from random import choice
from lib.utils import throttle
class Fourchan(object):
def fourchanboards(self):
boardlist = 'https://a.4cdn.org/boards.json'
try:
boards = requests.get(boardlist).json()['boards']
resboards = [board['board'] for board in boards]
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 14 15:54:56 2017
crnn
@@ model url https://github.com/bgshih/crnn and https://github.com/meijieru/crnn.pytorch
author = {Baoguang Shi and
Xiang Bai and
Cong Yao},
title = {An End-to-End Train... |
from google.net.proto import ProtocolBuffer
import array
import dummy_thread as thread
if hasattr(ProtocolBuffer, 'ExtendableProtocolMessage'):
_extension_runtime = True
_ExtendableProtocolMessage = ProtocolBuffer.ExtendableProtocolMessage
else:
_extension_runtime = False
_ExtendableProtocolMessage = ProtocolB... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Attempt to solve the task from facebook interview."""
import argparse
import logging
from pathlib import Path
import pdb
import re
import sys
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
class Trie(object):
"""Trie of x option * (char, trie) list.""... |
import math
from PIL import Image, ImageDraw
import animation
images = []
frames = 63
def circle(draw, center, radius, **options):
draw.chord((center[0]-radius, center[1] - radius, center[0]+radius, center[1] + radius), 0, 359, **options)
size = 800
circle_radius = 20
dot_radius = 3
distance_between_centers = 2... |
from sanic.utils import sanic_endpoint_test
import json
# ------------------------------------------------------------ #
# GET
# ------------------------------------------------------------ #
def test_get_collection_resource(app):
request, response = sanic_endpoint_test(app, uri='/job', method='get')
expect... |
from pageobjects.base import PageObject
from pageobjects.settings import SettingsFooter
from selenium.webdriver.support.select import Select
class InterfacesSettings(PageObject, SettingsFooter):
@property
def interfaces(self):
elements = self.parent.\
find_elements_by_css_selector('.physi... |
from __future__ import print_function
import os.path
import re
import sys
import tarfile
import time
from datetime import datetime
# pylint: disable=unused-import,g-bad-import-order
import tensorflow.python.platform
from six.moves import urllib
import numpy as np
import tensorflow as tf
# pylint: enable=unused-import,... |
# -*- coding: utf-8 -*-
"""
"""
from __future__ import absolute_import
from ._utils import _cd
from ..unitquantity import UnitConstant
m_alpha = alpha_particle_mass = UnitConstant(
'alpha_particle_mass',
_cd('alpha particle mass'),
symbol='m_alpha',
u_symbol='m_α'
)
alpha_particle_mass_energy_equival... |
#!/usr/bin/python
try:
import autotest.common as common
except ImportError:
import common
import sys
import os
import shutil
import errno
import optparse
import logging
from autotest.client.shared import error, utils
from autotest.client.shared import logging_config, logging_manager
"""
Compile All Autotest GWT... |
from django.db import models
from django.contrib.auth.models import User
class DreamSaying(models.Model):
title = models.CharField(max_length = 32, verbose_name = '标题')
content = models.TextField(verbose_name = '内容')
tags = models.IntegerField(null = True, verbose_name = '标签')
time = models.DateTimeFie... |
import pyrap.tables as pt
import pyrap.quanta as qa
import pyrap.measures as pm
from numpy import pi
"""
Provides getAteamList, a function that returns a comma-separated list of the Ateam sources that have to be demixed.
Inputs:
* MSname (the measurement set name)
* innerDistance is the minimum distance (degrees) bet... |
from __future__ import absolute_import
from mcpi.vec3 import Vec3
class BlockEvent:
"""An Event related to blocks (e.g. placed, removed, hit)"""
HIT = 0
def __init__(self, type, x, y, z, face, entityId):
self.type = type
self.pos = Vec3(x, y, z)
self.face = face
... |
# -*- coding: utf-8 -*-
import os,math
from qgis.core import NULL
from mole3 import oeq_global
from mole3.project import config
from mole3.extensions import OeQExtension
from mole3.stat_corr import rb_present_roof_uvalue_AVG_by_building_age_lookup, nrb_present_roof_uvalue_by_building_age_lookup
def calculation(self=N... |
"""Common time zone acronyms/abbreviations for use with the datetime_tz module.
*WARNING*: There are lots of caveats when using this module which are listed
below.
CAVEAT 1: The acronyms/abbreviations are not globally unique, they are not even
unique within a region. For example, EST can mean any of,
Eastern Standa... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
"""
Creates permissions for all installed apps that need permissions.
"""
from __future__ import unicode_literals
import getpass
import locale
import unicodedata
from django.contrib.auth import models as auth_app
from django.db.models import get_models, signals
from django.contrib.auth.models import User
def _get_pe... |
""" This is a test of the chain
ReportsClient -> ReportsGeneratorHandler -> AccountingDB
It supposes that the DB is present, and that the service is running.
Also the service DataStore has to be up and running.
this is pytest!
"""
# pylint: disable=invalid-name,wrong-import-position
import datetime
... |
import os
import numpy as np
from montepython.likelihood_class import Likelihood
class sn(Likelihood):
# initialization routine
def __init__(self, path, data, command_line):
Likelihood.__init__(self, path, data, command_line)
# define array for values of z and data points
self.z = ... |
# -*- coding: utf-8 -*-
from datetime import timedelta, tzinfo, datetime
import re
try:
# Try to use pytz if it exists
from pytz import utc
except ImportError:
# Fallback to simple UTC implementation
class _UtcOffset(tzinfo):
"""
Simple UTC tzinfo
"""
def __init__(... |
# -*- coding: utf-8 -*-
import re
import urllib
from module.plugins.internal.misc import json
from module.plugins.internal.Hoster import Hoster
def clean_json(json_expr):
json_expr = re.sub('[\n\r]', '', json_expr)
json_expr = re.sub(' +', '', json_expr)
json_expr = re.sub('\'', '"', json_expr)
ret... |
from __future__ import print_function
import os
import shutil
import sys
assert sys.argv[1] == '-frontend'
primaryFile = sys.argv[sys.argv.index('-primary-file') + 1]
if (os.path.basename(primaryFile) == 'bad.swift' or
os.path.basename(primaryFile) == 'crash.swift'):
print("Handled", os.path.basename(pr... |
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QAction, QMainWindow, QMenu, QWidget
appsDict = {}
class AbstractApp:
def __init__(self, name: str, icon: QIcon, mainWindow: QMainWindow):
self.name = name
self.canonicalName = name.lower()
self.mainWindow = mainWindow
if ... |
from opus_core.variables.variable import Variable, ln_bounded
from variable_functions import my_attribute_label
class ln_home_access_to_population_DDD(Variable):
"""Bounded natural log of the home_access_to_population for this gridcell"""
_return_type="float32"
def __init__(self, number... |
"""
Coded this quickly during the lecture describing it.
Divide and conquer algorithm.
Merge sort improves over: selection, insertion, bubble sort, three other sorting algorithms.
Note: I've used a lot of iterator logic that is not pythonic.
This algorithm was implemented with the intention of being as
close to t... |
"""
Internal client library for making calls directly to the servers rather than
through the proxy.
"""
import os
import socket
from httplib import HTTPException
from time import time
from urllib import quote as _quote
from eventlet import sleep, Timeout
from swift.common.bufferedhttp import http_connect
from swiftc... |
import theano.tensor as t
import theano
from nn.net import TrainerNetwork, ClassifierNetwork
from dataset.shared import isShared
class DistilleryClassifier(ClassifierNetwork) :
'''The ClassifierNetwork object allows the user to build multi-layer neural
networks of various topologies easily. This class prov... |
import time, config
from tweepy import OAuthHandler
from tweepy import API
# SETTINGS
retweet_threshold = 0
max_tweets_per_hour = 720
save_at = 100
safety_buffer_sec = 0.02
wait_per_request = 3600.0 / max_tweets_per_hour + safety_buffer_sec
# TWITTER CONFIG
auth = OAuthHandler(config.twitter_consumer_key, config.twit... |
'''Gaussian cube file format'''
import numpy as np
from horton.cext import Cell
from horton.grid.cext import UniformGrid
__all__ = ['load_cube', 'dump_cube']
def _read_cube_header(f):
# Read the title
title = f.readline().strip()
# skip the second line
f.readline()
def read_grid_line(line):
... |
import sys
import unittest
from mooseutils import message
class TestMooseMessage(unittest.TestCase):
"""
Tests the usage of the various messages functions in message package.
"""
def testMooseMessageDefault(self):
"""
Test the default message with a string and a number supplied.
... |
{
'name': 'Website SEO',
'category': 'website',
'summary': 'Website SEO improvements',
'version': '0.1',
'description': """
Website SEO improvements
""",
'author': 'Trey',
'depends': [
'website',
],
'data': [
'views/layout.xml',
],
'demo': [
],
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'frmTUT4Online.ui'
#
# by: PyQt4 UI code generator 4.5.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_frmTUT4Online(object):
def setupUi(self, frmTUT4Online):
... |
# coding=utf-8
from __future__ import with_statement
import os
import re
from django.conf import settings
from django_extensions.management.utils import signalcommand
from django_extensions.compat import CompatibilityBaseCommand as BaseCommand
ANNOTATION_RE = re.compile("\{?#[\s]*?(TODO|FIXME|BUG|HACK|WARNING|NOTE|... |
'''
Convenience wrapper around FLANN to do kNN searches.
'''
from .utils import is_integer
import numpy as np
from cyflann import FLANNIndex
def default_min_dist(dim):
return min(1e-2, 1e-100 ** (1.0 / dim))
def pick_flann_algorithm(dim):
return 'linear' if dim > 5 else 'kdtree_single'
def knn_search(K,... |
import sys, os
import pyopenmv
import argparse
from time import sleep
from random import randint
def main():
# CMD args parser
parser = argparse.ArgumentParser(description='openmv stress test')
parser.add_argument("-j", "--disable_fb", action = "store_true", help = "Disable FB JPEG compression")
parse... |
'''
This is a simplified correlation filter implementation used to locate eyes
using ASEF correlation filters. This file contains two classes:
OpenCVFilterEyeLocator and FilterEyeLocator. The first is the bare minimum
required to locate eye and only requires opencv. The second need is a wrapper
that includes a nic... |
import json
import struct
import re
import base64
import httplib
import sys
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
class VirtaCoinRPC:
OBJID = 1
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
s... |
import __builtin__
import maps
import mock
from mock import patch
import pytest
from tendrl.commons.utils import ansible_module_runner
from tendrl.commons.utils.ssh.generate_key import GenerateKey
def ansible_run(*args):
if args[0]:
return {"ssh_private_key": "test_ssh_private_key"}, ""
elif not args... |
import scrapy
from collector.items import CollectorItem
class AdafruitSpider(scrapy.Spider):
name = 'adafruit'
allowed_domains = ['adafruit.com']
start_urls = [
'https://www.adafruit.com/category/8',
'https://www.adafruit.com/category/17',
'https://www.adafruit.com/category/33',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.