code stringlengths 1 199k |
|---|
from django.utils import timezone
import pytest
from django_bulk_update.helper import bulk_update
from django.db.models import DateTimeField
from osf_tests.factories import UserFactory, PreprintFactory, NodeFactory
@pytest.mark.django_db
class TestGuidAutoInclude:
guid_factories = [
UserFactory,
Pre... |
"""Functional tests for quantized operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
... |
from __future__ import division
from telemetry.core import _bitmap
def Channels(bitmap):
return bitmap.bpp
def Width(bitmap):
return bitmap.width
def Height(bitmap):
return bitmap.height
def Pixels(bitmap):
return bitmap.pixels
def GetPixelColor(bitmap, x, y):
return bitmap.GetPixelColor(x, y)
def WritePngFil... |
""" Django admin pages for student app """
from django import forms
from django.contrib.auth.models import User
from ratelimitbackend import admin
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from config_models.admin import Configu... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: syslog_json
callback_type: notification
requirements:
- whitelist in configuration
short_description: sends JSON events to syslog
version_added: "1.9"
description:
- ... |
"""Seq2seq layer operations for use in neural networks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framewor... |
__author__="Josh Montague"
__license__="MIT License"
"""
This script is designed to run inline (%run 3d-example.py) in
the corresponding IPython notebook. It generates a 3d scatter
plot using scikit-learn data generation and with a number of
samples and clusters determined by the variables near the top.
"""
import argp... |
"""
pygments.styles.default
~~~~~~~~~~~~~~~~~~~~~~~
The default highlighting style.
:copyright: 2007 by Tiberius Teng.
:copyright: 2006 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Er... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: openvswitch_bridge
version_added: 1.4
author: "David Stygstra (@s... |
import time
from datetime import datetime
from sys import version_info
__all__ = ['strptime']
if version_info[:2] <= (2, 4):
def strptime(text, dateFormat):
return datetime(*(time.strptime(text, dateFormat)[0:6]))
else:
def strptime(text, dateFormat):
return datetime.strptime(text, dateFormat) |
f0 = lambda x: hermite(0,x)
f1 = lambda x: hermite(1,x)
f2 = lambda x: hermite(2,x)
f3 = lambda x: hermite(3,x)
f4 = lambda x: hermite(4,x)
plot([f0,f1,f2,f3,f4],[-2,2],[-25,25]) |
import traceback
import os
import sys
import _gdb
if sys.version_info[0] > 2:
# Python 3 moved "reload"
from imp import reload
from _gdb import *
class _GdbFile (object):
# These two are needed in Python 3
encoding = "UTF-8"
errors = "strict"
def close(self):
# Do nothing.
return... |
for x in undefined(): # ty<caret>pe: int
pass |
from framework.routing import Rule, json_renderer
from addons.s3 import views
api_routes = {
'rules': [
Rule(
[
'/settings/s3/accounts/',
],
'post',
views.s3_add_user_account,
json_renderer,
),
Rule(
[
... |
from django.test import TestCase
from readthedocs.builds.constants import LATEST
from readthedocs.projects.models import Project
from readthedocs.restapi.views.footer_views import get_version_compare_data
class VersionCompareTests(TestCase):
fixtures = ['eric.json', 'test_data.json']
def test_not_highest(self):... |
from __future__ import unicode_literals
import frappe
@frappe.whitelist()
def get_cal_events(m_st, m_end):
# load owned events
res1 = frappe.db.sql("""select name from `tabEvent`
WHERE ifnull(event_date,'2000-01-01') between %s and %s and owner = %s
and event_type != 'Public' and event_type != 'Cancel'""",
(m_s... |
from time import sleep
class TestPyTest:
def testOne(self):
sleep(1.5) # To check duration
assert 4 == 2*2
def testTwo(self):
assert True
def testThree():
assert 4 == 2*2 |
from flask import Blueprint
auth = Blueprint('auth', __name__)
from . import views |
from collections import Sequence # noqa
import logging
from django.conf import settings
from horizon import exceptions
import six
__all__ = ('APIResourceWrapper', 'APIDictWrapper',
'get_service_from_catalog', 'url_for',)
LOG = logging.getLogger(__name__)
class APIVersionManager(object):
"""Object to sto... |
from mod_pywebsocket import handshake
from mod_pywebsocket.handshake.hybi import compute_accept
def web_socket_do_extra_handshake(request):
message = 'HTTP/1.1 101 Switching Protocols\r\n'
message += 'Upgrade: websocket\r\n'
message += 'Connection: Upgrade\r\n'
message += 'Sec-WebSocket-Accept: %s\r\n' ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: na_cdot_qtree
short_description: Manage qtrees
extends_documentatio... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: virt_pool
author: "Maciej Delmanowski (@drybjed)"
version_added... |
aiProcess_CalcTangentSpace = 0x1
aiProcess_JoinIdenticalVertices = 0x2
aiProcess_MakeLeftHanded = 0x4
aiProcess_Triangulate = 0x8
aiProcess_RemoveComponent = 0x10
aiProcess_GenNormals = 0x20
aiProcess_GenSmoothNormals = 0x40
aiProcess_SplitLargeMeshes = 0x80
aiProcess_PreTransformVertices = 0x100
aiProcess_LimitBoneWei... |
import time
from common_report_header import common_report_header
from openerp.report import report_sxw
class journal_print(report_sxw.rml_parse, common_report_header):
def __init__(self, cr, uid, name, context=None):
if context is None:
context = {}
super(journal_print, self).__init__(c... |
"""
flask.testsuite.templating
~~~~~~~~~~~~~~~~~~~~~~~~~~
Template functionality
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import flask
import unittest
from flask.testsuite import FlaskTestCase
class TemplatingTestCase(FlaskTestCase):
def test_conte... |
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
**************... |
"""
Domain Name Server
"""
import os, traceback
from twisted.python import usage
from twisted.names import dns
from twisted.application import internet, service
from twisted.names import server
from twisted.names import authority
from twisted.names import secondary
class Options(usage.Options):
optParameters = [
... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
float_or_none,
unified_strdate,
)
class PornoVoisinesIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?pornovoisines\.com/videos/show/(?P<id>\d+)/(?P<display_id>[^/.]+)'
_TEST = ... |
"""
DataSource is a wrapper for the OGR Data Source object, which provides
an interface for reading vector geometry data from many different file
formats (including ESRI shapefiles).
When instantiating a DataSource object, use the filename of a
GDAL-supported data source. For example, a SHP file or a
TIGER/Line ... |
"""Tests for initializers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import nn_ops
from te... |
"""Generate java source files from protobuf files.
This is a helper file for the genproto_java action in protoc_java.gypi.
It performs the following steps:
1. Deletes all old sources (ensures deleted classes are not part of new jars).
2. Creates source directory.
3. Generates Java files using protoc (output into either... |
"""
LucasArts Font parser.
Author: Cyril Zorin
Creation date: 1 January 2007
"""
from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (FieldSet,
UInt8, UInt16, UInt32, GenericVector)
from lib.hachoir_core.endian import LITTLE_ENDIAN
class CharData(FieldSet):
def __init__(self, chars, *args... |
"""Gets and writes the configurations of the attached devices.
This configuration is used by later build steps to determine which devices to
install to and what needs to be installed to those devices.
"""
import optparse
import sys
from util import build_utils
from util import build_device
def main(argv):
parser = op... |
"""Microsoft Internet Explorer cookie loading on Windows.
Copyright 2002-2003 Johnny Lee <typo_pl@hotmail.com> (MSIE Perl code)
Copyright 2002-2006 John J Lee <jjl@pobox.com> (The Python port)
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the fi... |
import subprocess
import re
import os
import errno
import collections
import sys
class Platform(object):
pass
sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)')
def sdkinfo(sdkname):
ret = {}
for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PIPE).stdout:
kv = l... |
from todoman import version # type: ignore
__version__ = version.version
__documentation__ = "https://todoman.rtfd.org/en/latest/" |
"""
Interface definition.
"""
from zope import interface
class IMailer(interface.Interface):
"""
An object that sends e-mail.
"""
def send(sender, recipient, content):
"""
Sends the content to the recipient as the sender.
"""
class ITemplate(interface.Interface):
"""
An e... |
import numpy as np
import ctypes as ct
import matplotlib.pyplot as plt
def set_playlist( adq_cu, adq_num, dac_id, tcstr ):
tc = {}
if (tcstr == 'basic1'):
ns = 2 # Number of items
tc["ns"] = ns
# 1 2 3 4 5 6 7 8... |
import unittest
import pytk.geo as geo
class GeoQuatTest(unittest.TestCase):
def test_shape(self):
self.assertRaises(geo.GeoException, geo.quat, [])
self.assertRaises(geo.GeoException, geo.quat, [0])
self.assertRaises(geo.GeoException, geo.quat, [0, 1])
self.assertRaises(geo.GeoExcep... |
class ParamsException(Exception):
"""Exception raised when tp, fmt and size values are wrongs"""
pass
class LineSizeException(Exception):
"""Exception raised when line size is bigger then specified"""
pass
class LineIdentifierException(Exception):
"""Exception raised when line indentifier rased from... |
import json
import numpy as np
import pandas as pd
import numbers
class NumpyAndPandasEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (np.ndarray, np.matrix)):
return [self.default(x) for x in obj]
if isinstance(obj, pd.DataFrame):
return [self.default(s... |
"""Contain common module fields."""
from __future__ import absolute_import
import re
from django.db import models
from django.core.exceptions import ValidationError
class NameField(models.CharField):
"""Item name string field.
This field is limited to 64 characters and contains the name(string).
Good exampl... |
"""Convert 3 fastq inputs (read 1, read 2, UMI) into paired inputs with UMIs in read names
Usage:
bcbio_fastq_umi_prep.py single <out basename> <read 1 fastq> <read 2 fastq> <umi fastq>
or:
bcbio_fastq_umi_prep.py autopair [<list> <of> <fastq> <files>]
Creates two fastq files with embedded UMIs: <out_basename>_R1.f... |
import collections
def read_only(self, name, val):
raise ValueError('not supported')
class SimpleObject(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.b = c
class SimpleObjectImmutable(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
... |
import os
from glob import glob
from vlpp.utils import save_json
from vlpp.qamosaic import Mosaic
def main():
# Usefull directories
os.mkdir("data")
# Informations
participant_id = "${sub.sub}"
# Images Path
try: anat = glob("${sub.anat}")[0]
except: anat = None
try: brainmask = glob("${... |
from typing import Any, Dict, Tuple, Union
__cached_defs: Dict[str, Any] = {}
def __getattr__(name: str) -> Any:
import importlib # noqa # isort:skip
if name in __cached_defs:
return __cached_defs[name]
if name == "JsonBase":
module = importlib.import_module(".json_base", "tomodachi.envelo... |
"""
example with 'calls_expected' in addtoBatch used
"""
import batchOpenMPI
def f_mult(x) :
return x*2.0
f = batchOpenMPI.batchFunction(f_mult) #creating function wrapper
batchOpenMPI.begin_MPI_loop() # both the workers and the master process run the same code up until here
f.addtoBatch(4,calls_expected=4)
batchO... |
"""
wavelet toolbox
"""
from __future__ import division, print_function, absolute_import
from .dwt import *
from .utility import *
from ._pyyawt import *
from .dwt1d import *
from .dwt2d import *
from .dwt3d import *
from .cowt import *
from .cwt import *
from .swt import *
from .denoising import *
from pyyawt.version ... |
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
def siteconf_func(apps, schema_editor):
Site = apps.get_model('sites', 'Site')
db_alias = schema_editor.connection.alias
Site.object... |
import sys
sys.path.append('..')
from bcert_pb2 import *
import binascii
cert = BitcoinCert()
cert.data.version = '0.1'
cert.data.subjectname = 'Foo Inc.'
email = cert.data.contacts.add()
email.type = email.EMAIL
email.value = 'foo@fooinc.com'
url = cert.data.contacts.add()
url.type = url.URL
url.value = 'http://www.fo... |
import sys, os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'sammy'
copyright = u'2014, ChangeMyName'
version = '0.1'
release = '0.1'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename ... |
import argparse
import cmd
import os
import shlex
import sys
from tabulate import tabulate
import time
from talus_client.cmds import TalusCmdBase
import talus_client.api
import talus_client.errors as errors
from talus_client.models import Image,Field
class ImageCmd(TalusCmdBase):
"""The Talus images command processor
... |
"""Yummly data models.
"""
from inspect import getargspec
class Storage(dict):
"""An object that is like a dict except `obj.foo` can be used in addition
to `obj['foo']`.
Raises Attribute/Key errors for missing references.
>>> o = Storage(a=1, b=2)
>>> assert(o.a == o['a'])
>>> assert(o.b == o['b... |
import scrapy
import json
import re
from locations.items import GeojsonPointItem
class McDonalsILSpider(scrapy.Spider):
name = "mcdonalds_il"
allowed_domains = ["www.mcdonalds.co.il"]
start_urls = (
'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D7%A2%D7%93%D7%94',
)
... |
class DinkyFish:
def monthsUntilCrowded(self, tankVolume, maleNum, femaleNum):
months = 0
while maleNum + femaleNum <= (tankVolume * 2):
minFishes = min(maleNum, femaleNum)
maleNum += minFishes
femaleNum += minFishes
months += 1
return months |
from mcurl.utils import monkey_patch
import zmq.green as zmq
import sys
import json
__author__ = 'chenfengyuan'
monkey_patch.dummy()
def client(port):
host = '127.0.0.1'
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://%s:%s" % (host, port))
socket.send(b'')
message... |
from os.path import expanduser
obfuscated_packages = [
'controller',
'db',
'dbdata',
'logic',
'migrations',
'platform_api',
'tests',
'view'
]
unobfuscated_folders = [
'csvlite',
'fonts',
'help',
'images', 'initial_data', 'international',
'kivygraph',
'tests',
... |
from django import template
register = template.Library()
@register.assignment_tag(takes_context=True)
def has_bookmark_permission(context, action):
"""Checks if the current user can bookmark the action item.
Returns a boolean.
Syntax::
{% has_bookmark_permission action %}
"""
request = cont... |
import sys, time
from PySide import QtGui, QtCore
from presentacion.form_abm_paciente import FormPacienteABM
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
# Create and display the splash screen
splash_pix = QtGui.QPixmap('splash.png')
splash = QtGui.QSplashScreen(splash_pix, QtCore.Qt.Wi... |
from tkinter import *
from tkinter.messagebox import *
fenetre = Tk()
fenetre.title("The Enigma Machine")
fenetre.configure(background='white')
fenetre.geometry("550x800")
class AutoScrollbar(Scrollbar):
#create a 'responsive' scrollbar
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
... |
import pytest
from pillowtalk import *
@pytest.fixture
def folder_json():
return {'count' : 59,
'created_at' : '2013-10-01T20:07:18+00:00',
'description' ... |
def topgeo ('topgeo'):
"""
Esta libreria funciona para realizar calculos topograficos.
""" |
__author__ = 'leif'
from game_models import HighScore, UserProfile
from ifind.common.utils import encode_string_to_url
from django.contrib.auth.models import User
from django.db.models import Max, Sum, Avg
class GameLeaderboard(object):
def __init__(self, top=20):
self.top = top
def get_leaderboard(self... |
"""Generate year files with news counts
Usage:
filter_news.py <directory> <output> <lang>
Options:
-h, --help
"""
from docopt import docopt
from os import listdir
from os.path import isfile, join, getsize
import datetime
from tqdm import *
import pandas as pd
def find_index(id, lis):
for i in range(0, len(lis)):
... |
"""
Tests for twisted.names.dns.
"""
from __future__ import division, absolute_import
from io import BytesIO
import struct
from zope.interface.verify import verifyClass
from twisted.python.failure import Failure
from twisted.python.util import FancyEqMixin, FancyStrMixin
from twisted.internet import address, task
from ... |
from __future__ import print_function
from time import clock
from math import ceil
import cplex
from cplex import SparsePair
from fim import apriori
import myiolib
import hcba_ext
from SetOp import *
def findMin(S):
result = []
for i in xrange(len(S)):
flag = True
for j in xrange(len(S)):
... |
"""Exponential and Quaternion code for Lab 6.
Course: EE 106, Fall 2015
Author: Victor Shia, 9/24/15
This Python file is a code skeleton Lab 6 which calculates the rigid body transform
given a rotation / translation and computes the twist from rigid body transform.
When you think you have the methods implemented correc... |
from struct import pack
from sqlite3 import Binary
def pts(c):
return ["dd",[c.X,c.Y]]
def pt4mp(c):
return ["Bidd",[1,1,c.X,c.Y]]
def mp(coordinates):
partCount=coordinates.partCount
i=0
out = ["I",[0]]
while i<partCount:
pt = coordinates.getPart(i)
[ptrn,c]=pt4mp(pt)
ou... |
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamCloudPath, SteamGamesPath
class CogsPlugin(BasePlugin):
Name = "Cogs"
support_os = ["Windows"]
def backup(self, _):
_.add_folder('Data', os.path.join(SteamCloudPath, '26500'), 'remote')
def restore(self, _):
_.re... |
debug = True # Set to False for no data display
window_on = False # Set to True displays opencv windows (GUI desktop reqd)
diff_window_on = False # Show OpenCV image difference window
thresh_window_on = False # Show OpenCV image Threshold window
SHOW_CIRCLE = True # show a circle otherwise show bounding rec... |
import unittest
import doctest
import spiralx.fileproc
def load_tests(loader, tests, ignore):
fileprocTestSuite = unittest.TestSuite()
fileprocTestSuite.addTests(doctest.DocTestSuite(spiralx.fileproc))
return fileprocTestSuite |
"""
The MIT License (MIT)
Copyright (c) 2015 Robert Hodgen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, ... |
import warnings
from apification.utils import Noninstantiable, NoninstantiableMeta
def test_noninstantiable():
e, o = None, None
try:
o = Noninstantiable()
except TypeError as e: pass
assert o is None
assert isinstance(e, TypeError)
def test_noninstantiable_keyword_self_check_invalid():
... |
import configparser
import requests
import re
import sys
import time
import pymongo
import random
from datetime import datetime, timedelta
from hracing.db import parse_racesheet
from hracing.db import mongo_insert_race
from hracing.tools import delay_scraping
from hracing.tools import shuffle_ids
def download_list_of_r... |
from algorithms.sorting.selection_sort import *
from __prototype__ import *
if __name__ == '__main__':
test_all(selection_sort) |
"""A basic implementation of a Neural Network
by following the tutorial by Andrew Trask
http://iamtrask.github.io/2015/07/12/basic-python-network/
"""
import numpy as np
def nonlin(x, deriv=False):
if deriv==True:
return x * (1-x)
return 1 / (1 + np.exp(-x))
x = np.array([[0, 0, 1],
[0, ... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('iiits', '0025_auto_20160425_1937'),
]
operations = [
migrations.CreateModel(
name='Staff',
field... |
import pygtk
pygtk.require('2.0')
import gtk
import os
import getpass
import time
class i3_exit:
def disable_buttons(self):
self.cancel.set_sensitive(False)
self.logout.set_sensitive(False)
self.suspend.set_sensitive(False)
self.reboot.set_sensitive(False)
self.shutdown.set_s... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))
import files
import graphs
def main(argv):
k, Gs = files.read_graphs(argv[0])
sinks = []
for G in Gs:
n, m = G[:2]
edges = G[2]
nodes = [n for n in xrange(1, n + 1)]
sinks.append(graphs... |
"""
@file
@brief Link to data from `Gutenberg <http://www.gutenberg.org/>`_,
provides an automated way to get the data from this website.
Some data may be replicated here to unit test notebooks.
"""
import os
import urllib.request
from urllib.error import URLError
def gutenberg_name(name="condamne", local=False, load=F... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('backend', '0005_organization_registered'),
]
operations = [
migrations.RemoveField(
model_name='organization',
name='lobbyists_wi... |
from django.db import models
from linda_app.models import DatasourceDescription
class EndpointTest(models.Model):
execution_time = models.DateTimeField(auto_now_add=True) # test timestamp
datasource = models.ForeignKey(DatasourceDescription) # tested datasource
up = models.BooleanField(default=False) # w... |
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.ofproto import ether
from ryu.lib.packet import packet
from ryu.lib.packet import ethern... |
class OWL:
def __init__(self):
pass |
from bin.dazer_methods import Dazer
from bin.lib.ssp_functions.ssp_synthesis_tools import ssp_fitter
import sys
import numpy as np
from numpy import float_, absolute as abs, random as ran
import time
import ssp_Hector_Fit3D_tools as ssp
import pyfits as pyf
from pyfits import getheader as ghead, getdata as gdata, write... |
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to ma... |
from bpy.types import Operator
class SCENE_OT_jewelcraft_scene_units_set(Operator):
bl_label = "Set Units"
bl_description = "Set optimal unit settings for jewelry modelling"
bl_idname = "scene.jewelcraft_scene_units_set"
bl_options = {"REGISTER", "UNDO", "INTERNAL"}
def execute(self, context):
... |
from datetime import datetime, timedelta
from django.db import models
from django.db.models import Max, Min
from tinymce.models import HTMLField
class Company(models.Model):
name = models.CharField(max_length=75, blank=True, null=True)
symbol = models.CharField(max_length=10, blank=True, null=True)
descript... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import slugify
from mptt.models import MPTTModel, TreeForeignKey
class ForumCategory(MPTTModel):
parent = TreeForeignKey(
'self', blank=True, null=True, related_name... |
from app.schema_validation.definitions import https_url, uuid
create_service_callback_api_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST service callback/inbound api schema",
"type": "object",
"title": "Create service callback/inbound api",
"properties": {
... |
from eventEngine import *
from ctpGateway import CtpGateway
class MainEngine(object):
"""主引擎"""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
# 创建事件引擎
self.eventEngine = EventEngine()
self.eventEngine.start()
... |
import pytest
from fnapy.fnapy_manager import FnapyManager
def test_manager_raises_TypeError_with_invalid_connection():
"""FnapyManager should raise a TypeError when the connection is not a FnapyConnection"""
with pytest.raises(TypeError):
connection = {'partner_id': 'XXX', 'shop_id': 'XXX', 'key': 'XXX... |
import math
import string
lookup_map = {}
def memcache_read(n):
global lookup_map
if lookup_map.has_key(n):
return lookup_map[n]
else:
return None
def memcache_write(n, value):
global lookup_map
lookup_map[n] = value
def get_chain_length(n):
# check cache
cache = memcache_read(n)
if cache != Non... |
def insertsort(lst):
for i in range(1, len(lst)):
value = lst[i]
j = i
while j > 0 and value < lst[j - 1]:
lst[j] = lst[j - 1]
j -= 1
lst[j] = value
ary = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
print(ary)
insertsort(ary)
print(ary) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pdfapp', '0010_auto_20170225_0034'),
]
operations = [
migrations.AddField(
model_name='document',
name='html_text_string',
... |
"""
@author : 'Muhammad Arslan <rslnrkmt2552@gmail.com>'
"""
import re
import zlib
import cv2
from scapy.all import *
pics = "pictues"
faces_dir = "faces"
pcap_file = "bhp.pcap"
def get_http_headers(http_payload):
try:
headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2]
headers = dict(re.f... |
import json
import logging
import boto3
import hashlib
import jsonpatch
from dart.context.locator import injectable
from dart.model.trigger import TriggerType, TriggerState
from dart.message.call import TriggerCall
from dart.trigger.base import TriggerProcessor, execute_trigger
from dart.model.exception import DartVali... |
import os
from locust import HttpUser, TaskSet, task, between
from locust.clients import HttpSession
class MultipleHostsUser(HttpUser):
abstract = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.api_client = HttpSession(base_url=os.environ["API_HOST"])
class User... |
import cgi
import json
import os
import re
import SimpleHTTPServer
import SocketServer
import subprocess
import sys
import threading
VERSION = 'v0.14.6'
hostname = ''
try:
command = "bash -c '[[ $(dig +short $HOSTNAME) ]] && echo $HOSTNAME || wget -q -O - icanhazip.com'"
hostname = subprocess.check_output(comma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.