code stringlengths 1 199k |
|---|
import json
from datetime import datetime, timedelta
from flask import redirect, render_template
from backend.common.decorators import cached_public
from backend.common.models.event import Event
from backend.common.models.team import Team
from backend.common.queries.event_query import TeamYearEventsQuery
from backend.c... |
import csv
import re
from beer_search_v2.models import Product, ContainerType, ProductType
from beer_search_v2.utils import get_alcohol_category_instance
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand
from datetime import date
class Command(BaseCommand):
de... |
from .util import encode_id
def calculate_rating(datum):
# See
# https://github.com/alphagov/spotlight/blob/ca291ffcc86a5397003be340ec263a2466b72cfe/app/common/collections/user-satisfaction.js # noqa
if not datum['total:sum']:
return None
min_score = 1
max_score = 5
score = 0
for ra... |
from SimpleCV import *
from libardrone import libardrone
import time
def takeoff(drone):
print "Taking off"
drone.takeoff()
drone.hover()
drone.speed = 0.1
bat = drone.navdata.get(0, dict()).get('battery', 0)
print bat
def main():
display = SimpleCV.Display()
cam = Kinect()
ts = []
... |
from kivy.app import App
from kivy.uix.bubble import Bubble
from kivy.animation import Animation
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.clock import Clock
from electrum_arg_gui.kivy.i18n import _
Builder.load_string('''
<MenuItem@Button>
... |
import os
import os.path
import ConfigParser
from pymongo import Connection
import datetime
import logging
import logging.config
import sys
import time
from email.utils import parsedate_tz
import glob
import simplejson
import hashlib
import string
from collections import defaultdict
import re
import traceback
import sh... |
import unittest
import sys
sys.path.append("..")
from cache import ProductCache
class CacheTestCase(unittest.TestCase):
def setUp(self):
self.p0 = ProductCache()
self.p1 = ProductCache()
def test_singleton_0(self):
self.assertTrue(id(self.p0) == id(self.p1))
def test_singleton_1(self... |
from peewee import *
from model.base_entity import BaseEntity
class Feed(BaseEntity):
url = TextField(unique=True)
last_update = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
summary = BooleanField(default=False)
preview = BooleanField(default=False)
class Meta:
db_table = 'f... |
app_key = u'6be9204c30b9473e87bad4dc'
master_secret = u'e62664ad421b67270e5c9d5b' |
"""
Django settings for woit project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import... |
class Solution(object):
def buddyStrings(self, A, B):
# If the lengths are not equal, then its not possible.
if len(A) != len(B):
return False
# If the both are equal, then we need to swap the same characters.
# Also A=ab ; B=ab will fail, so we need additional conditiona... |
from layers.organisms import OrganismsLayer
from layers.food import FoodLayer
from layers.background import BackgroundLayer
from organism.organism import Organism
from layers.console import ConsoleLayer
from world.world import Map
import settings
import cocos
import time
import random
import pygame
import pyglet
class ... |
import re
from events import events
from settings import DEFAULT_RESPONSE
class EventHandler(object):
def __init__(self):
self.events = [(re.compile(pattern), callback) for pattern, callback in events]
def route(self, update):
msg = update.message.text
for event, callback in self.events:... |
from .reduce import reduce |
"""
Written by Nathan Fritz and Lance Stout. Copyright 2011 by &yet, LLC.
Released under the terms of the MIT License
"""
from pubsub import Thoonk
from pubsub import Thoonk as Pubsub
__version__ = '1.0.0rc1'
__version_info__ = (1, 0, 0, 'rc1', 0) |
import os
import uuid
from osipkd.tools import row2dict, xls_reader
from datetime import datetime
from sqlalchemy import not_, func
from pyramid.view import (
view_config,
)
from pyramid.httpexceptions import (
HTTPFound,
)
import colander
from deform import (
Form,
widget,
ValidationFailure... |
from minervashadow.utils.exceptions import InvalidUsername
from getpass import getpass
import sys
import os
def get_user_credentials():
"""Gets the user credentials from the commandline.
Asks the user for his McGill email address and password.
Args:
None
Returns:
An array containing the ... |
def get(id):
if id == 0: # Empty bytearray
return bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x... |
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
from builtins import range, map, zip, filter
from io import open
import six
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import ... |
from decimal import Decimal
from test_framework.test_framework import BitcoinTestFramework
from test_framework.authproxy import JSONRPCException
from test_framework.util import (
initialize_chain,
assert_equal,
assert_raises,
assert_is_hex_string,
assert_is_hash_string,
start_nodes,
connect_... |
"""This example shows how you can copy, save and load a space using pickle.
"""
import pickle
import pygame
import pymunk
import pymunk.pygame_util
from pymunk import Vec2d
width, height = 800, 600
def main():
pygame.init()
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
fo... |
from distutils.core import setup
setup(
name='zhseg',
version='0.01',
description='chinese word segment',
author='Kaiqiang Duan',
url='https://github.com/anphy/ChineseWordSegmentation',
license="MIT",
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :... |
"""Hoverable Behaviour (changing when the mouse is on the widget by O. Poyen.
License: LGPL
"""
__author__ = 'Olivier POYEN'
from kivy.properties import BooleanProperty, ObjectProperty
from kivy.core.window import Window
class HoverBehavior(object):
"""Hover behavior.
:Events:
`on_enter`
Fir... |
from tests.compiler import compile_snippet, A_ID, B_ID, SELF_ID, VAL1_ID, VAL2_ID, INST_ID, INNER_ID, INNER1_ID, \
INNER2_ID, STATIC_START, internal_call, LST_ID, CONTAINER
from thinglang.compiler.opcodes import OpcodeAssignStatic, OpcodeAssignLocal, OpcodePushMember, OpcodePopLocal, \
OpcodeDereference, Opcode... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "infratabtask.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import ttsutil
import os.path
import urllib
import json
import untangle
import argparse
import shutil
import PIL.Image
cards={}
debug=True
def make_filename(image):
return ttsutil.make_cache_filename(image,"ANR")
def make_cache_dir():
ttsutil.make_cache_dir("ANR")
def build_chest_file(deck,base_url):
chest=ttsuti... |
from os import path
import subprocess
THIS_FOLDER = path.dirname(path.abspath(__file__))
def reset_database(host):
subprocess.check_call(
['fab', 'reset_database', '--host={}'.format(host)],
cwd=THIS_FOLDER
)
def create_session_on_server(host, email):
return subprocess.check_output(
... |
from __future__ import unicode_literals
"""
Boot session from cache or build
Session bootstraps info needed by common client side activities including
permission, homepage, default variables, system defaults etc
"""
import frappe, json
from frappe import _
import frappe.utils
from frappe.utils import cint, cstr
import ... |
c = c # pylint:disable=undefined-variable,self-assigning-variable # ALT: # noqa: F821
config = config # pylint:disable=undefined-variable,self-assigning-variable
config.load_autoconfig(True)
c.colors.prompts.fg = "lime" # @me
c.colors.statusbar.url.fg = "lime" # @me
c.completion.cmd_history_max_items = 1000 # @me... |
import rocrand
import numpy as np
interactive = True
if not interactive:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
figsize = None
if not interactive:
figsize = (30, 20)
plt.figure(1, figsize=figsize)
plt.suptitle("Estimating Pi using Monte Carlo method")
n = 10000
cols = 3
for ... |
"""
Hardtree URLs
"""
from coffin.conf.urls import *
from django.conf.urls import patterns, url, include
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodis... |
import sys
import mechanize
import re
import json
import time
import urllib
import dogcatcher
import HTMLParser
import os
h = HTMLParser.HTMLParser()
cdir = os.path.dirname(os.path.abspath(__file__)) + "/"
tmpdir = cdir + "tmp/"
voter_state = "PA"
source = "State"
result = [("authory_name", "first_name", "last_name", "... |
"""Define tests for restriction endpoints."""
import datetime
import aiohttp
import pytest
from regenmaschine import Client
from .common import TEST_HOST, TEST_PASSWORD, TEST_PORT, load_fixture
@pytest.mark.asyncio
async def test_watering_log_details(aresponses, authenticated_local_client):
"""Test getting watering... |
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import telestream_cloud_qc
from telestream_cloud_qc.models.partition... |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import admin
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth import get_user_model
from authtools.admin import NamedUserAdmin
from reachapp.forms import UserCreationForm
from reachapp.models... |
import os
import unittest
import arff
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
OBJ = {
'description': '\nXOR Dataset\n\n\n',
'relation': 'XOR',
'attributes': [
('input1', 'REAL'),
('input2', 'REAL'),
('y', 'REAL'),
],
'data': [
... |
from Utils import *
from math import *
def step(a, b, c):
x = (sqrt(a) + b) / c
m = floor(x)
d = b - m * c
f = -d
e = (a - d ** 2) / c
return (m, (a, f, e))
def continuedFractionsOfSquareRootOf(a):
a = a
b = 0
c = 1
ms = []
(_, (firstA, firstB, _)) = step(a, b, c)
# print... |
import parselogic, sys
from parselogic import t_col
def u_netdict(f_in, dir_in=None, u_dict=None, delimit='\t', keywords=[]):
if not u_dict:
u_dict = {}
if not dir_in:
indir = ''
included = 0
excluded = 0
def kwmatch(lc, keywords=keywords):
text = ' '+lc[t_col('t_text')]+' '+... |
from flask import jsonify, request, current_app, url_for
from . import api
from ..models import User, Post
@api.route('/users/<int:id>')
def get_user(id):
user = User.query.get_or_404(id)
return jsonify(user.to_json())
@api.route('/users/<int:id>/posts/')
def get_user_posts(id):
user = User.query.get_or_404... |
import argparse
import warnings
import py
import six
from _pytest.config.exceptions import UsageError
FILE_OR_DIR = "file_or_dir"
class Parser(object):
""" Parser for command line arguments and ini-file values.
:ivar extra_info: dict of generic param -> value to display in case
there's an error processi... |
import unittest
from d_largest_palindrome_product import *
class TestLargestPalindromeProduct(unittest.TestCase):
def test_palindrome(self):
self.assertTrue(is_palindrome(10101))
self.assertTrue(is_palindrome(1001))
self.assertFalse(is_palindrome(12))
self.assertFalse(is_palindrome(1... |
text = """Line 20 (10:11:37):: Command From [5002:3:1]-[$03$0D$0A$1B[1GDGX_SHELL>$1B[11Gshow$0D$0AVersion Info:$0D$0AMCPU$0D$0A BTL: 3.8.0 $09HW_ID 0x0 $09Targ_ID 0x0 $09SysRevID 0x1 $09FW_ID 0x500$0D$0A APP: 2.6.2.2 R $09Nov 15 2014 20:35:43$0D$0A SRM: 1.0.5.1$0D$0ABCPU1 DxLink_input$0D$0A... |
import json, urllib2
import pandas as pd
response = urllib2.urlopen('http://glottolog.org/resourcemap.json?rsc=language')
data = json.load(response)
nres = len(data['resources'])
print "\n-----\nNumber of rows in resources list: ", nres
counter = 0 # count languoids with lat/long coordinates
IDs = []; NAMEs = []; TYPE... |
from lacuna.bc import LacunaObject
from lacuna.building import MyBuilding
class thedillonforge(MyBuilding):
path = 'thedillonforge'
def __init__( self, client, body_id:int = 0, building_id:int = 0 ):
super().__init__( client, body_id, building_id )
def _marshal_view(self, rv):
""" Multiple m... |
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import seaborn as sns
import tensorflow as tf
from matplotlib import pyplot as plt
from odin import visual as vs
from odin.bay.vi import discretizing
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['TF_FORCE_GPU_ALLOW_GROW... |
from .linked_service import LinkedService
class AzureSqlDWLinkedService(LinkedService):
"""Azure SQL Data Warehouse linked service.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param connect_via:... |
from django.db import models
from django.contrib.auth.models import User
from cellcounter.main.models import CellType
class Keyboard(models.Model):
"""Represents a Keyboard mapping between users and keys"""
user = models.ForeignKey(User, on_delete=models.CASCADE)
label = models.CharField(max_length=25)
... |
"""
WSGI config for oknesset project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... |
'''
Created on Feb 20, 2013
@author: Maribel Acosta
@author: Fabian Floeck
@author: Andriy Rodchenko
'''
from wmf import dump
from difflib import Differ
from time import time
from structures.Revision import Revision
from structures.Paragraph import Paragraph
from structures.Sentence import Sentence
from structures.Word... |
import argparse
import sys
import re
import json
import requests
from models import auth
import pprint
def create(config, args):
pp = pprint.PrettyPrinter()
url = config['url'] + "/api/serveroverload/"
data = {
"name": args['name'],
"description": args['description'],
"function": {
... |
from typing import List, Optional, Union
from azure.core.exceptions import HttpResponseError
import msrest.serialization
from ._subscription_client_enums import *
class AvailabilityZonePeers(msrest.serialization.Model):
"""List of availability zones shared by the subscriptions.
Variables are only populated by t... |
from cardinal.decorators import event
class InviteJoinPlugin(object):
"""Simple plugin that joins a channel if an invite is given."""
@event('irc.invite')
def join_channel(self, cardinal, user, channel):
"""Callback for irc.invite that joins a channel"""
cardinal.join(channel)
def setup(card... |
"""
Chuckchi_Winds_NARR_model_prep.py
Retrieve NARR winds for one locations
Icy Cape Line, Ckip2
Latitude = 70.8401 Longitude = 163.2054
Filter NARR winds with a triangular filter (1/4, 1/2, 1/4) and output every 3hrs
Provide U, V
Save in EPIC NetCDF standard
"""
import datetime
import argparse
import numpy as n... |
from django.db import models
from django.contrib.auth.models import User
class ConfigTemplate(models.Model):
class Meta:
verbose_name = 'Config Template'
verbose_name_plural = 'Config Templates'
def __str__(self):
return self.template_name
template_name = models.CharField(
ma... |
import os
import sys
import traceback
from turing.runtime.state import UserState, InitialMixin, FinalMixin, \
StateRegister
from turing.runtime.machine import Turing, TerminateException
from turing.tape import TapeError, TapeIsOverException, Tape
from turing.const import Move, Action
_states = set()
class DoesNotEn... |
from myspider.echo import Echo
echo_screen = Echo('screen')
echo_file = Echo('file')
echo_xls = Echo('xls')
text = 'Hello World'
def test_screen(text):
echo_screen.echo(text)
def test_file(text):
echo_file.echo_to_file(text)
test_screen(text)
test_file(text) |
"""
Created on Thu Apr 2 16:33:34 2015
@author: ajaver
"""
import json
import multiprocessing as mp
import os
from functools import partial
import cv2
import numpy as np
import skimage.filters as skf
import skimage.morphology as skm
import tables
from tierpsy.analysis.compress.BackgroundSubtractor import BackgroundSub... |
"""
Module that contains all the resolvers.
A resolver is a class that is able to retrieve a dependency to inject.
"""
import builtins
import inspect
import typing
from pyjection.reference import Reference
class BaseResolver(object):
"""
Base class for the resolvers
"""
def resolve(self, method_paramete... |
import os
from flask import Flask
from views.home import home_blueprint
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.register_blueprint(home_blueprint)
if __name__ == '__main__':
app.run(debug=True) |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-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 ri... |
'''
Created on 9 Jan 2015
@author: chris
'''
def main():
most_northerly_coords = extract_most_notherly_point()
for m in most_northerly_coords:
print m
def extract_most_notherly_point():
import pickle
with open('/tmp/fusion_op.p','rb') as f:
dets = pickle.load(f)
import numpy as np
... |
from django.contrib.auth.models import User
from rest_framework.serializers import ModelSerializer
from danibraz.bookings.models import Booking
class BookingCreateUpdateSerializer(ModelSerializer):
# user = serializers.PrimaryKeyRelatedField(
# read_only=False,
# queryset=User.objects.all()
# )
... |
import sys
from functools import reduce
def multiples_of_a_divisors_of_b(lcm, gcd):
result = []
multiplyer = 1
while (lcm * multiplyer <= gcd):
if (gcd % (lcm * multiplyer) == 0):
result.append(lcm * multiplyer)
multiplyer += 1
return result
def gcd(*numbers):
"""Return t... |
import logging
import os
import sys
logging.basicConfig(level=logging.INFO)
basename = os.path.splitext(os.path.basename(__file__))[0]
def rel(*path):
return os.path.abspath(
os.path.join(os.path.dirname(__file__), *path)
).replace("\\", "/")
sys.path.append(rel('..'))
DEBUG = True
SECRET_KEY = 'none'
T... |
'''
Bremerton Weak Lensing Round Trip Module for CosmoSIS
ATTRIBUTION: CFHTLens
because this is a copy of the CFHTLens module with some minor modifications.
'''
import numpy as np
import os,sys
import scipy.interpolate as interpolate
n_z_bin = 1
n_theta = 5
n_z_pair = n_z_bin*(n_z_bin+1)/2
n_tot = n_z_pair*n_theta*2
di... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.http import require_safe
from tools.forms import HashForm, RotForm, BaseConversionForm, XORForm, URLQuoteForm, URLUnquoteForm
@login_required
... |
import sqlite3
conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()
cur.execute('SELECT * FROM Twitter')
count = 0
for row in cur :
print(row)
count = count + 1
print(count, 'rows.')
cur.close() |
class Validator:
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super(PyroValidator, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def valid_int(): pass
def valid_decimal(): pass
def valid_float(): pass
def ... |
"""Plot to demonstrate the qualitative2 colormap.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from typhon.plots import (figsize, cmap2rgba)
markers = (m for m in Line2D.filled_markers)
fig, ax = plt.subplots(figsize=figsize(10))
ax.set_prop_cycle(color=cmap2rgba('qualitati... |
import urllib.parse
import webbrowser
import json
from xml.etree import ElementTree
import sublime
import SublimeHaskell.sublime_haskell_common as Common
import SublimeHaskell.internals.logging as Logging
import SublimeHaskell.internals.utils as Utils
import SublimeHaskell.internals.unicode_opers as UnicodeOpers
import... |
from setuptools import setup, find_packages
setup(
name="Slack Shogi",
version="0.1",
packages=find_packages(),
test_suite="test",
install_requires=[
"slackbot",
"slacker",
"websocket-client",
],
) |
from models import jointvae
from data import JointStratifiedMNIST, ColouredStratifiedMNIST
from training import train_joint, Results
experiment_name = 'discrete_colored_final'
models = [
jointvae.JointVAE
]
models = {x.__name__: x for x in models}
parms = {
# options
'type': "cnn", # fc, cnn
... |
import os
import urllib3
from urllib3.exceptions import HTTPError, TimeoutError, MaxRetryError
import requests
import re
import datetime
import pytz
from bs4 import BeautifulSoup
from models import TheaterChain, Theater, Movie
import tools
import title_except
class MovieCrawler(object):
"""docstring for Cine"""
... |
"""
Django settings for myCommServer project.
Generated by 'django-admin startproject' using Django 1.8.13.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
... |
import pygame, sys
from pygame.locals import *
pygame.init()
print pygame.version.ver
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
... |
"""Main module."""
from logzero import logger as log
import pandas as pd
from munch import Munch, unmunchify
import ruamel.yaml as yaml
import pygraphviz as pgv
from easygv.cli.config import process_config
def update_pgv_element(element_attr_obj, attrs):
"""Update a graph element's attribute object.
Args:
... |
"""
Created on Mon Nov 28 12:51:47 2016
MIT License
Copyright (c) 2016 Zeke Barge
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... |
class Exchange:
def __init__(self, exchange_name):
self.exchange_name = exchange_name
self.queues = [] |
from django.conf.urls import patterns, include, url
from web import views
urlpatterns = patterns(
'',
url(r'^index$', views.index, name='index'),
url(r'^search$', views.search, name='search'),
url(r'^answerlist$', views.answerlist, name='answerlist'),
url(r'^createUser$', views.create_user, name='createUser'),
... |
import pickle as pkl
from collections import Iterable
import os
import logging
import io
import numpy as np
try:
xrange
except NameError: # python3
xrange = range
logger = logging.getLogger('LineCache')
class LineCache(object):
'''
LineCache caches the line position of a file in the memory. Everytime i... |
"""takeout_inspector/talk.py
Defines classes and methods used to generate graphs for Google Talk data (based on a Google Mail takeout file).
Copyright (c) 2016 Christopher Charbonneau Wells
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (... |
import sqlite3
from dateutil import parser
conn = sqlite3.connect("folding-stats.db")
conn.text_factory = str
c = conn.cursor()
data_user = "data/diff_user.txt"
data_team = "data/diff_team.txt"
data = [line.split('\t') for line in open(data_user)]
data_date = parser.parse(str(data[:1][0])[2:-4])
for a in data[1:]:
c.e... |
import sys
import time
import optparse
import general
import numpy
import fasta
import metrn
import modencode
import bed
import os
import copy
import pdb
import re
import network
from Bio import Motif
print "Command:", " ".join(sys.argv)
print "Timestamp:", time.asctime(time.localtime())
""" define classes and function... |
import time
import threading
from pprint import pprint
import ipset_wrapper
MAX_TIMEOUT = 2
class GreenConnection(object):
"""
运行时链接状态
"""
def __init__(self):
self.pool = {}
self.banlist = []
def track_ip(self, ipaddress, connect_id, connect_state):
if ipaddress in self.b... |
import math
import logging
import string
import scipy
from nltk.stem.porter import *
import numpy as np
import os
import sys
import keyphrase.config as config
from keyphrase.dataset import dataset_utils
import keyphrase.config
config = keyphrase.config.setup_keyphrase_baseline() # load settings.
def load_phrase(file_p... |
'''
See: http://www.careercup.com/question?id=24532662
The Question
------------
> You are given two array, first array contain integer which represent heights of
> persons and second array contain how many persons in front of him are standing
> who are greater than him in term of height and forming a queue. Ex
> A: 3 ... |
import snap
from sets import Set
import matplotlib.pyplot as plt
import random
import collections
import numpy as np
import itertools
SUFFIX = "bk-comp"
COLORS = itertools.cycle(["r", "b", "g", "c", "m", "y", "k", "w"])
GRAPH_LIST = [("MAL-recommendation", "mal-rec-graph"), ("brightkite", "Brightkite_edges.txt")]
DATA_... |
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0008_remove_location_user'),
]
operations = [
... |
from Settings import *
from Constants import *
from psychopy.event import xydist
import numpy as np
import random, os, pickle, commands
class RandomAgent():
def __init__(self,nrframes,dispSize,pos,pdc,sd,moveRange):
self.offset=pos
self.ds=dispSize
self.nrframes=nrframes
self.traj=np... |
import factory
from credentials.models import SshKeyPair
public_key = """ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTx+Q1k+3Rej6giYUQtZ9rgqqz0/crkyVaKOUL1h/lr6ORmjAABy6iCVDY1jvIBHv2//a7eOW/Na86p6UtYO+vHF5S0EC+Fl6pQoXmAiPVp6MqyA8psj2b6YaNW9CKmp2OtzFvpmnzQxYfafBejlNIKhfHofW7e9UjL2FVzlAgnNeDv8u2K1bPFO7ikiwYdMmNPDvYK82N9+JXo8O... |
import pytest
from capybara.tests.helpers import extract_results
class TestWithTable:
@pytest.fixture(autouse=True)
def setup_session(self, session):
session.visit("/tables")
def test_restricts_scope_to_a_table_given_by_id(self, session):
with session.table("girl_table"):
session... |
import rpclib
import sys
import auth
from debug import *
class AuthRpcServer(rpclib.RpcServer):
## Fill in RPC methods here.
def rpc_register(self, username, password):
return auth.register(username, password)
def rpc_login(self, username, password):
return auth.login(username, password)
... |
"""
Watts-Strogatz model
--------------------
This module contains functions for constructing
a random graph following the Watts-Strogatz model.
"""
import os, sys
import graph
import numpy as np
def watts_strogatz(n, k, beta, seed=1):
"""
Creates a random graph following Watts-Strogatz model.
:param n: (in... |
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer, SpacegroupOperations, PointGroupAnalyzer
from pymatgen.util.coord import coord_list_mapping_pbc, coord_list_mapping
from pymatgen import Lattice, Structure, Composition, Molecule
from bsym import SpaceGroup, SymmetryOperation, ConfigurationSpace, PointGroup
fro... |
import sys
from itertools import chain, combinations
start = (1, ((1,1), (1,1), (2,3), (2,2), (2,2), (1,1), (1, 1)))
goal = (4, tuple((4,4) for _ in range(len(start[1]))))
def tuple2list(state):
return [state[0], [list(i) for i in state[1]]]
def list2tuple(state):
return (state[0], tuple(tuple(i) for i in stat... |
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.pyplot import GridSpec
import seaborn as sns
import mpld3
import numpy as np
import pandas as pd
import os, sys
import warnings
fig, ax = plt.subplots()
np.random.seed(0)
x, y = np.random.normal(size=(2, 200))
color, size = np.random.random((... |
import web
from lib.utils import render, etherpad, memcache
from lib.validate import valid_login
class HomePage:
def GET(self):
# Checks if db's password matches cookie's
if valid_login():
return render('index.html')
# User does not have access to content
# Or user has be... |
import asyncio
import collections
import io
import struct
from .._tl import TLRequest
from ..types._core import MessageContainer, TLMessage
class MessagePacker:
"""
This class packs `RequestState` as outgoing `TLMessages`.
The purpose of this class is to support putting N `RequestState` into a
queue, an... |
re.sub('ROAD$', 'RD.', s)
s[:-4] + s[-4:].replace('ROAD', 'RD.')
str, unicode, list, tuple, bytearray, buffer, xrange
s + t # the concatenation of s and t (6)
s * n, n * sn # shallow copies of s concatenated (2)
s[i] # i'th item of s, origin 0 (3)
s[i:j] # slice of s from i... |
import math
def brute_force():
a = 600851475143
largest_prime_factor = 0
i=(600851475143/2)+1
while (i>2):
i-=1
# check if its a factor
if (a%i==0):
# check if its prime
flag = 0
for j in range(2,int(math.sqrt(i))+1):
if (i%j==0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.