code stringlengths 1 199k |
|---|
import os
import sys
import re
import subprocess
import json
VCC_PATH = 'C:/Program Files/Side Effects Software/Houdini 16.0.600/bin/vcc.exe'
SYN_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
COMP_PATH = os.path.join(SYN_PATH, 'VEX.sublime-completions')
FUNC_PATH = os.path.join(os.path.join(SY... |
"""XTF viewer (and converter)"""
import os
import csv
import webbrowser
import re
import sys
from functools import partial
import numpy
from GUI import Application, ScrollableView, Document, Window, Globals, rgb
from GUI import Image, Frame, Font, Model, Label, Menu, Grid, CheckBox, Button
from GUI import BaseAlert, Mo... |
class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
m = len(matrix)
n = 0 if m == 0 else len(matrix[0])
for i in range(m):
for j in range(n):
if i == 0 and ... |
from django.shortcuts import render
from django.http import HttpResponse
from rango.models import Category
from rango.models import Page
from rango.forms import CategoryForm
from rango.forms import PageForm
def index(request):
# Query the database for a list of ALL categories currently stored.
# Order the categ... |
from IPython import embed
import cv2
import numpy as np
import scipy.ndimage.filters
import math
class Tracker(object):
def __init__(self, **kwargs):
"""Set configuration attributes and create tracked objects.
Objects are instances of inner class _Object. This method creates these
instances using the pass... |
__counter__=159
__release__=''
__version__='0.1.%03d'%__counter__+__release__ |
from __future__ import absolute_import, division, print_function, unicode_literals
from itertools import chain
from nose.tools import eq_, raises
from six.moves import xrange
from smarkets.streaming_api.framing import (
frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode,
)
test_data =... |
"""Codec for quoted-printable encoding.
Like base64 and rot13, this returns Python strings, not Unicode.
"""
import codecs, quopri
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def quopri_encode(input, errors='strict'):
"""Encode the input, returning a tuple (output o... |
from ..core import Provider
from ..core import Response
from ..exceptions import NotifierException
from ..utils import requests
class Zulip(Provider):
"""Send Zulip notifications"""
name = "zulip"
site_url = "https://zulipchat.com/api/"
api_endpoint = "/api/v1/messages"
base_url = "https://{domain}.... |
import json
from handlers.exceptions import HandlerError
from handlers.base import BaseHandler
from models.users import ContactModel
class Contacts(BaseHandler):
model = ContactModel()
def post(self):
try:
search_payload = json.loads(self.request.body) if self.request.body else None
... |
from django.shortcuts import render, get_object_or_404,redirect
from django.views import View, generic
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from star_ra... |
import numpy
def test(p, parameters):
qc = numpy.zeros(p.n_levels(), dtype=bool)
# this spike test only makes sense for 3 or more levels
if p.n_levels() < 3:
return qc
t = p.t()
for i in range(2, p.n_levels()-2):
qc[i] = spike(t[i-2:i+3])
qc[1] = spike(t[0:3])
qc[-2] = spike(... |
class KerviPlugin(object):
def __init__(self, name, config, manager):
from kervi.config.configuration import _Configuration
self._config = _Configuration()
from kervi.config import Configuration
self._global_config = Configuration
plugin_config = {}
if config:
... |
class Dummy:
"""
Implements a dummy class that is completely inert.
"""
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, item):
return self.dummy_function
def __setattr__(self, key, value):
pass
def dummy_function(*args, **kwargs):
pass |
"""
Application settings module.
"""
import os
from xdg import XDG_CACHE_HOME
from bootstrap import PROJECT_NAME
OS_IMAGES = {
'raspbian-lite': 'https://downloads.raspberrypi.org/raspbian_lite_latest',
}
CACHE = os.path.join(XDG_CACHE_HOME, PROJECT_NAME) |
from datetime import datetime
import os
import sys
if (len(sys.argv) != 2):
print "usage: <log file>"
exit()
pattern = '%Y-%m-%d %H:%M:%S,%f'
def parseCommand(command):
return command.split(" ")[0]
command_timing = {}
indent = 0
start_time = None
for ext in [".5", ".4", ".3", ".2", ".1", ""]:
if not os.... |
"""
Streaming server
Accept incoming data from the streaming clients,
and store the data in Db
"""
class StreamingServer(object):
""" Streaming server class """
def __init__(self):
pass
def run(self):
pass |
from . import tag
from .exif import ExifReader
from .projection import rectify
__all__ = ['ExifReader', 'rectify', 'tag'] |
import getpass
import tempfile
from datetime import datetime
from unittest.mock import call
import pytest
from dateutil.tz import tzutc
from typer.testing import CliRunner
from cli.webapp import app
runner = CliRunner()
@pytest.fixture
def mock_webapp(mocker):
mock_webapp = mocker.patch("cli.webapp.Webapp")
moc... |
'''
Created on 19 March 2012
@author: tcezard
'''
import sys, os
from utils import utils_logging, utils_commands,\
longest_common_substr_from_start, utils_param, sort_bam_file_per_coordinate
import logging, threading, re
from optparse import OptionParser
from glob import glob
import command_runner
from utils.Fasta... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('iiits', '0005_auto_20160228_1200'),
]
operations = [
migrations.CreateModel(
name='News',
fields=[
('id', models.... |
from django.core.urlresolvers import reverse
from django.shortcuts import Http404, HttpResponseRedirect
from django.views.generic import CreateView, UpdateView, DeleteView, \
ListView
from django_tables2 import SingleTableMixin
from core.views import LoginRequiredMixin
from ..forms import MetricForm
from ..models i... |
import os
import logging
import logging.config
import sqlalchemy as sa
from alembic import context
from wuffi.conf import settings
from wuffi.core.db import DEFAULT_DATABASE_ALIAS
__all__ = (
'target_url',
'target_metadata',
'run',
'run_offline',
'run_online',
)
MIGRATIONS_LOGGING = {
'version':... |
"""aiohttp request argument parsing module.
Example: ::
import asyncio
from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import use_args
hello_args = {
'name': fields.Str(required=True)
}
@asyncio.coroutine
@use_args(hello_args)
def index(request, ... |
import ViewPresenter as vp
import ui
import shelve
class ItemError(Exception):
pass
class Item(object):
def __init__(self, name:string, amount:float, units:string):
self.name = name
self.amount = amount
self.units = units
return
def __eq__(self, other):
return self.na... |
"""
meetbot.py - Willie meeting logger module
Copyright © 2012, Elad Alfassa, <elad@fedoraproject.org>
Licensed under the Eiffel Forum License 2.
This module is an attempt to implement at least some of the functionallity of Debian's meetbot
"""
from __future__ import unicode_literals
import time
import os
from willie.w... |
from . import *
SECRET_KEY = env.str('KOBRA_SECRET_KEY',
'Unsafe_development_key._Never_use_in_production.')
DEBUG = env.bool('KOBRA_DEBUG_MODE', True)
DATABASES = {
'default': env.db_url('KOBRA_DATABASE_URL', 'sqlite:///db.sqlite3')
} |
class Counter:
"""
Counts up to a limit, and signals if that limit is reached.
"""
def __init__(self):
self.limit = None
self.counter = 0
def increment(self, amt=1):
self.counter += amt
return self.limit is not None and self.counter >= self.limit |
import idiokit
from .. import handlers
from . import Transformation
class TransformationBot(Transformation):
handler = handlers.HandlerParam()
def __init__(self, *args, **keys):
Transformation.__init__(self, *args, **keys)
self.handler = handlers.load_handler(self.handler)
@idiokit.stream
... |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from cribs.models import Crib
from cribs.models ... |
from .default import DefaultPool
from .interruptible import InterruptiblePool
from .jl import JoblibPool
__all__ = ["DefaultPool", "InterruptiblePool", "JoblibPool"] |
from __future__ import absolute_import, unicode_literals
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django_executor import settings as de_settings
class ExecutorConfig(AppConfig):
name = 'django_executor'
verbose_name = _("Django Executor")
def ready(self)... |
import sys
import json
from httplib import HTTPConnection
from optparse import OptionParser
def fetchMetrics(host, port, url):
connection = HTTPConnection(host, port)
connection.request("GET", url)
response = connection.getresponse()
if response.status == 200:
try:
data = response.re... |
def minimum_reductions(s):
n = len(s)
count = 0
for i in range(n // 2):
left = ord(s[i])
right = ord(s[(n - 1) - i])
if left != right:
if left > right:
count += left - right
else:
count += right - left
return count
T = int(input())
for _ in range(T):
s = input()
print(minimum_reductions(s)) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('treatment_sheets', '0006_auto_20160324_0247'),
]
operations = [
migrations.AlterField(
model_name='txitem',
name='dose',
... |
"""
Implementation of paper: Deep Recurrent Attentive Writer (DRAW) network architecture introduced by
K. Gregor, I. Danihelka, A. Graves and D. Wierstra. The original paper can be found at:
http://arxiv.org/pdf/1502.04623
Reference implementations on GitHub:
1. https://github.com/jbornschein/draw
2. https://github.com... |
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np
import serial
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 50
camera.hflip = True
rawCapture = PiRGBArray(camera, size=(640, 480))
time.sleep(0.1)
for frame in camera.capture_continuous... |
"""
compute_accuracy.py
Usage:
compute_accuracy.py model.joblib
where model.joblib is a file created by cleverhans.serial.save containing
a picklable cleverhans.model.Model instance.
This script will run the model on a variety of types of data and print out
the accuracy for each data type.
clean : Clean data
... |
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import AppPlatformManagementClientConf... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404
from django.core.urlresolvers import reverse, reverse_lazy, resolve
from django.core.exceptions import PermissionDenied
from django.template import RequestContext
from layeri... |
import time,os,sys
from time import gmtime, strftime
class buffer(object):
def __init__(self):
self.lines = {0:"" ,1:"" ,2:"" ,3:"" ,4:"" ,5:"" ,6:"" ,7:"" ,8:"" }
def print_lines(self):
for i in self.lines:
print(self.lines[i])
def clean(self):
for i in self.lines:
self.lines[i] = ""
class large_number:... |
__author__ = 'adrian'
import sys
import web
import logging
from parking import parking
urls = (
'/parking', 'parking',
'/parking/car', 'carWithdraw'
)
def init_loggers():
# set up logging for the example
logger = logging.getLogger('CylindricalParking')
logger.setLevel(logging.DEBUG)
consoleHandl... |
import mock
import unittest
from webtest import TestApp
from webtest.debugapp import debug_app
from raygun4py.middleware.wsgi import Provider
class TestWSGIMiddleware(unittest.TestCase):
def setUp(self):
self.test_middleware = ExceptionMiddleware(debug_app)
self.raygun_middleware = Provider(self.tes... |
from __future__ import unicode_literals
import re
import sys
import willie.tools
if sys.version_info.major >= 3:
unicode = str
basestring = str
class PreTrigger(object):
"""A parsed message from the server, which has not been matched against
any rules."""
component_regex = re.compile(r'([^!]*)!?([^@... |
'''Partial class to handle Vultr Regions API calls'''
from .utils import VultrBase, update_params
class VultrRegions(VultrBase):
'''Handles Vultr Regions API calls'''
def __init__(self, api_key):
VultrBase.__init__(self, api_key)
def availability(self, dcid, params=None):
''' /v1/regions/ava... |
"""graphics primitives"""
__authors__ = ["Ole Herman Schumacher Elgesem"]
__license__ = "MIT"
try:
import pyglet
from pyglet.text import Label
from pyglet.resource import image
except:
print("Warning: could not import pyglet.")
print("This is acceptable for tests, but rendering will not work."... |
from ast import literal_eval
import os.path
import unittest
from antlr4 import CommonTokenStream, ParseTreeWalker
from antlr4.InputStream import InputStream
from json_database.parser.parser import CommandParser
from json_database.recognizer.DatabaseLexer import DatabaseLexer
from json_database.recognizer.DatabaseParser... |
import random
import numpy as np
import torch
import torch.utils.data
from torch.utils.data.dataset import Dataset
from os.path import join
import torch.utils.data as data
from PIL import Image
from torchvision import transforms
import os
IMG_EXTENSIONS = [
'.jpg',
'png'
]
def default_loader(input_path):
in... |
from django.views.generic import View, ListView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from .forms import CodeRunForm
from .services import run_code
from .models import CodeRun
class ReplIndexView(LoginRequiredMixin, ListView):
template_name = 're... |
import glob
import os
from setuptools import setup
import offlinecdn
github_url = 'https://github.com/gabegaster/django-offlinecdn'
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.readlines()
long_description = "\n".join(read("README.rst"))
dependencies = []
filenam... |
import zipfile
import optparse
from threading import Thread
def crackIt(zFile, pw, i):
try:
zFile.extractall(pwd=pw)
print '[+] Password Found: '+pw
except Exception, e:
print str(i)+' Failed: '+pw
pass
def main():
parser = optparse.OptionParser("ZipCrack usage method. zipcracker.py -f <zipfile> -d <dictiona... |
"""
Reformat links and page references
Created by Rui Carmo on 2006-09-12.
Published under the MIT license.
"""
import os
import logging
log = logging.getLogger()
import urlparse
import posixpath
from config import settings
from controllers.wiki import WikiController as wc
from utils.core import Singleton
from utils.ti... |
import argparse
import os
import pandas as pd
import cPickle as pickle
from sklearn.preprocessing import LabelEncoder
if __name__ == '__main__':
parser = argparse.ArgumentParser()
args = parser.parse_args()
df = pd.read_csv('data/train.csv')
df['whaleID'] = df['whaleID'].apply(lambda x: x.split('_')[1])... |
from collections import namedtuple
""" A container for transitions. """
Transition = namedtuple('Transition',
('id', 'state', 'action', 'reward', 'state_', 'done')) |
from functools import partial
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from tsfresh import defaults
from tsfresh.feature_extraction.settings import from_columns
from tsfresh.transformers.feature_augmenter import FeatureAugmenter
from tsfresh.transformers.feature_selector import Featu... |
class GradientDecent:
"""
Adapt the weights in the opposite direction of the gradient to reduce the
error.
"""
def __call__(self, weights, gradient, learning_rate=0.1):
return weights - learning_rate * gradient
class Momentum:
"""
Slow down changes of direction in the gradient by agg... |
'''
Les URL de l'application enseignants
@author: hal
'''
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='base.html')),
) |
import matplotlib
matplotlib.use('TkAgg') # THIS MAKES IT FAST!
import numpy
import scipy
import struct
import pyaudio
import threading
import pylab
import struct
class SwhRecorder:
"""Simple, cross-platform class to record from the microphone."""
def __init__(self):
"""minimal garb is executed when cla... |
import os
import sys
import numpy as np
from collections import Counter
from tqdm import tqdm
from moviepy.video.io.ffmpeg_reader import ffmpeg_read_image
from moviepy.video.io.ffmpeg_writer import ffmpeg_write_image
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.fx.resize import resize
PAR... |
from skimage.transform.pyramids import pyramid_laplacian,resize
def multiscale_saliency(image, method, min_image_area=10000):
'''
Runs any saliency method as a multiscale method.
method is run for each image downsized until its area is lower than min_image_area.
The final result is an image with the sam... |
from flask import request
import redis
import config
import datetime
import json
redis_client = redis.StrictRedis(host=config.redis_config["host"], port=config.redis_config["port"])
def handle_app_install(request):
print "Handling app install", request.json
userID = request.json["userId"]
token = request.js... |
import inspect
import json
import traceback
import os
import types
'''
This print the full stack trace from the current point in the code
(from where "stack = inspect.stack()", below, is called).
It can be useful, e.g., to understand code that makes many calls
or to get information for debugging exceptions.
'''
def pri... |
import binascii
from lbryum.hashing import Hash
from lbryum.errors import InvalidProofError
def height_to_vch(n):
r = [0 for i in range(8)]
r[4] = n >> 24
r[5] = n >> 16
r[6] = n >> 8
r[7] = n % 256
# need to reset each value mod 256 because for values like 67784
# 67784 >> 8 = 264, which is... |
from django import forms
from apps.hypervisor.models import Hypervisor
class HypervisorForm(forms.ModelForm):
class Meta:
model = Hypervisor
exclude = ('status',) |
""" Recording modules
"""
import sys
import wave
import datetime as dt
import pyaudio
from scipy.io import wavfile as wav
RATE = 48000
CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
if sys.platform == 'darwin':
CHANNELS = 1
def time_now():
""" Get current time
"""
return dt.datetime.now().strftime("%Y%... |
import copy
import itertools
import re
SET_ORDERING_RE = re.compile(r'''
\s*
(?P<order>[\d\s,-]+)\)
\s*
''', re.X)
SET_RE = re.compile(r'''
(\[(?P<rest>\d+)\])?
\s*
((?P<work>\d+) \s* x \s*)?
\s*
(?P<reps>\d+)
''', re.X)
class Set:
def __init__(self,
work=0,
... |
t = int(raw_input())
for tt in range(t):
n, m = map(int, raw_input().split())
mice = [int(x) for x in raw_input().split(' ')]
holes = [int(x) for x in raw_input().split(' ')]
ret = -1
mice.sort()
holes.sort()
for m, h in zip(mice, holes):
ret = max(ret, abs(m - h))
print ret |
from lampost.gameops.script import Scriptable
from lampmud.comm.broadcast import BroadcastMap
from lampost.meta.auto import TemplateField
from lampost.db.dbofield import DBOField, DBOTField
from lampmud.model.article import Article, ArticleTemplate
from lampmud.mud.action import mud_action
class ArticleTemplateLP(Artic... |
import argparse
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from LinearKalmanFilter import *
def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return vals[order], vecs[:,orde... |
import json
import glob, os, sys
try:
import xlsxwriter
except:
print("This software requires XlsxWriter package. Install it with 'sudo pip install XlsxWriter', see http://xlsxwriter.readthedocs.io/")
sys.exit(1)
import datetime
import argparse
import re
def parseDateAndRun(filename):
m=re.match( r'.*pr... |
from board import Board
from board.move import Move
from util import input_parser
import util.printer as printer
from util.enums import Player
if __name__ == '__main__':
# get desired player or None for two player
player = input_parser.player()
# load and print initial board
board = Board(True)
unic... |
import pynmea2
import sys
import re
def checksum(data):
res = 0
data = data.split('$')[1]
for c in data:
res ^= ord(c)
return hex(res)
if __name__ == '__main__':
gpgga = '$GPGGA,102154.552,4308.0718,N,14114.9862,E,1,03,19.8,48.4,M,29.5,M,,0000'
altdata = 100
time = 101114
for i ,... |
def xuniqueCombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xuniqueCombinations(items[i+1:],n-1):
yield [items[i]]+cc
def xcombinations(items, n):
from operator import itemgetter
if n==0: yield []
else:
for i in xrange... |
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from model.year import Year
from model.wave import Wave
from model.config import Config
from model.profile import Profile
from model.user import User
from model.article import Article
from model.achievement import Achievement
from model.t... |
from hid import enumerate
from ba63.simple_hid import SimpleHID
from ba63.constant import SEQUENCE_MARQUEUR_DEBUT, SEQUENCES_CURSEUR, SEQUENCE_NETTOYAGE, SEQUENCE_SET_CHARSET, TAILLE_MESSAGE_MAX, NOMBRE_CARACTERES_PAR_LIGNE
from unidecode import unidecode
class FormatDonneesInvalideBA63(Exception):
pass
class Taill... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def reverse_between(head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
1 ≤ m ≤ n ≤ length of list.
"""
if not head:
return None
# pp: pointer to prev... |
"""snmp_interface: module called to generate SNMP monitoring data formatted for use with StatusBoard iPad App
"""
from pysnmp.entity.rfc3413.oneliner import cmdgen
import time
import json
import logging.config
from credentials import SNMP_COMMUNITY
__author__ = 'scott@flakshack.com (Scott Vintinner)'
MAX_DATAPOINTS = 3... |
from app.models import NnTrainingResult
def fetch_from_patch(patch):
return NnTrainingResult.objects.filter(patch=patch).order_by('-end_time') |
"""
Settings package is acting exactly like settings module in standard django projects.
However, settings combines two distinct things:
(1) General project configuration, which is property of the project
(like which application to use, URL configuration, authentication backends...)
(2) Machine-specific environ... |
import sys
if sys.version_info[0] == 2:
from ConfigParser import RawConfigParser
if sys.version_info[0] >= 3:
from configparser import RawConfigParser
import json
import requests
config_file_name = "usermanagement.config"
config = RawConfigParser()
config.read(config_file_name)
host = config.get("server", "host... |
import socket
import os
import sys
SPECIAL_COMMANDS = ["snapshot", "speak", "vibrate"]
def toString(array):
new = ""
for item in array:
new += item+" "
return new
def snapshot(s, cam_id, output_file): # Where "cam" is either 0 or 1.
os.system("termux-camera-photo -c " + str(cam_id) + " " + outpu... |
'''
@author: Michael Eddington
@version: $Id$
'''
import path, rand, sequencial
__all__ = ["path", "rand", "sequencial"] |
"""
Last Edited By: Kevin Flathers
Date Las Edited: 06/07/2017
Author: Kevin Flathers
Date Created: 05/27/2017
Purpose:
"""
from .Tgml import *
class Arc(Tgml):
DEFAULT_PROPERTIES = {}
SUPPORTED_CHILDREN = {}
def __init__(self, *args, input_type='blank', **kwargs):
super().__init__(*args, input_type=input_type, **... |
import logging
import os
from jobs.job import Job
from lib.jobstatus import JobStatus
from lib.filemanager import FileStatus
from lib.util import get_climo_output_files, print_line
from lib.slurm import Slurm
class Climo(Job):
def __init__(self, *args, **kwargs):
super(Climo, self).__init__(*args, **kwargs)... |
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {boolean}
def containsNearbyDuplicate(self, nums, k):
window = set()
left = 0
for right in range(len(nums)):
if nums[right] in window:
return True
if k and len(window)... |
import Broker
from time import time
destination = '/netflix/work'
kind = 'QUEUE'
broker = Broker.Client('localhost', 3322)
msg = Broker.Message(payload='este é o payload', destination=destination)
def produce(n):
for id in xrange(n):
broker.produce(msg, kind)
while True:
n = 1000
t = time()
prod... |
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from astropy import units
from galpy.orbit import Orbit
from FerrersPotential import FerrersPotential as FP
def allorbits(x,y):
xo = [x[2*i] for i in range(int(len(x)/2))]
xo1 = [x[2*i+1] for i in range(int(len(x)/2))]
... |
def gray_to_binary(gray,bits=4):
"""converts a given gray code to its binary number"""
mask = 1 << (bits - 1)
binary = gray & mask
for i in xrange(bits-1):
bmask = 1 << (bits - i-1)
gmask = bmask >> 1
if (binary & bmask) ^ ((gray & gmask) << 1):
binary = binary | gmas... |
ADDRESS = "";
PORT = 1337;
import http.server as hs;
from modules.Tunnel import tunnel;
import json;
class CustomRequestHandler(hs.BaseHTTPRequestHandler):
data={"user":""};
def do_GET(self):
print("\n\n");
self.send_response(200);
self.send_header("Content-Type","text/JSON");
self.send_header("Content-Encodi... |
from datetime import datetime
from elasticsearch import Elasticsearch
import redis
tskey = "pytsbench"
es = Elasticsearch(["localhost:9200"])
elastic_5_0 = True
client = redis.Redis()
rsize = int(client.info("memory")['used_memory'])
num_entries = 3
def info():
'''
Data:
storage_used
pages_visited
u... |
class autoconf(Wig):
git_uri = 'git://git.sv.gnu.org/autoconf'
tarball_uri = 'http://ftp.gnu.org/gnu/autoconf/autoconf-{RELEASE_VERSION}.tar.gz'
last_release_version = '2.69' |
"""
CombinatoricalMediaSimulations.py
Simulates all possible minimal media compositions consisting of unique carbon,
nitrogen, sulfate, phosphate sources. If a single compound provides multiple
elemental sources it serves a the solely source for them. # TODO: Reformulate this
KO analyses of genes and reactions are opti... |
import datetime
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('desecapi', '0009_token_allowed_subnets'),
]
operations = [
migrations.AddField(
model_name='token',
name='max_age',
... |
import _plotly_utils.basevalidators
class TickprefixValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="tickprefix", parent_name="heatmap.colorbar", **kwargs
):
super(TickprefixValidator, self).__init__(
plotly_name=plotly_name,
paren... |
"""Define Rotest's core models.
The Django infrastructure expects a models.py file containing all the models
definitions for each application. This folder is a workaround used in order
to separate the different core application models into different files
"""
from .run_data import RunData
from .case_data import CaseDat... |
def tnuml(n):
o = []
for _ in n:
_ = float(_)
o.append(_)
return o
def configr(vars, filename, section):
import configparser
c = configparser.ConfigParser()
c.read(filename)
r = []
for _ in vars:
a = c.get(section, _)
r.append(a)
return r
def writer (f... |
from typing import (
Callable,
Iterator,
TypeVar,
)
def exists(it: Iterator) -> bool:
try:
next(it)
except StopIteration:
return False
return True
T = TypeVar('T')
def and_(*args: Callable[[T], bool]) -> Callable[[T], bool]:
def _inner(x: T) -> bool:
for fn in args:
... |
import os, sys
module = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, module)
from netkiller.kubernetes import *
namespace = Namespace()
namespace.metadata.name('development')
namespace.metadata.namespace('development')
service = Service()
service.metadata().name('... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(frame,13)
#result is dilated f... |
"""Filter design.
"""
from __future__ import division, print_function, absolute_import
import math
import warnings
import numpy
import numpy as np
from numpy import (atleast_1d, poly, polyval, roots, real, asarray,
resize, pi, absolute, logspace, r_, sqrt, tan, log10,
arctan, arcsi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.