code stringlengths 1 199k |
|---|
import logging
import logging.handlers
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
def log_setup(log_dir, log_file):
logger = logging.getLogger("bottly")
log_path = base_dir + "/" + log_dir + "/"
log = log_path + log_file
if not os.path.exists(log_path):
os.makedirs(log_path)... |
from django.conf.urls.defaults import *
from dances.models import Dance
from groups.bridge import ContentBridge
bridge = ContentBridge(Dance, 'dances')
urlpatterns = patterns('',
url(r'^add_dance$', 'dances.views.add', name="dance_add"),
url(r'^your_dances/$', 'dances.views.your_dances', name="your_dances"),
... |
"""
pitchlabeltrack.py
--
Christopher Kuech
cjkuech@gmail.com
--
Requires:
Python 2.7
Instructions:
python pitchlabelspectrogram.py [wav-file-name]
"""
from math import log
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Fig... |
from setuptools import setup
setup(
name = 'MultiColProcessor',
packages = ['MultiColProcessor'],
version = '1.0.14',
description='a simple package to process pandas categorical colomns via preprocessing in scikit-learn',
url='https://github.com/mekhod/Pandas-Multi-Colomn-Processor',
author='Mehdi Khodayari... |
import _plotly_utils.basevalidators
class CmaxValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="cmax", parent_name="histogram.marker.line", **kwargs
):
super(CmaxValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent... |
"""
Train a small multi-layer perceptron with fully connected layers on MNIST data.
This example has some command line arguments that enable different neon features.
Examples:
python examples/mnist_mlp.py -b gpu -e 10
Run the example for 10 epochs using the NervanaGPU backend
python examples/mnist_mlp.p... |
from __future__ import absolute_import
import pytest
from wrapanapi import SCVMMSystem
@pytest.fixture(scope="module")
def mgmtsys(variables):
data = variables.get("scvmm")
if data:
return SCVMMSystem(**data)
pytest.skip("scvmm variables missing")
@pytest.fixture(scope="module")
def first_vm(mgmtsys... |
from pyramid.security import Allow, Deny, Everyone, Authenticated, ALL_PERMISSIONS, principals_allowed_by_permission, effective_principals, has_permission
VIEW = 'view' # can view context
EDIT = 'edit' # can edit/rename/delete context
ADD = 'add' # can add child objects
PUBLISH = 'publish' # can perform workflow transi... |
import os
from django.utils.translation import gettext_lazy as _
DIRNAME = os.path.dirname(__file__)
PROJECT_ROOT = os.path.dirname(DIRNAME)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backe... |
from sqlalchemy import func, and_, desc
import pandas as pd
import skchem
from ..models import Session, Compound, Target, Activity
from ..utils import config
class Dataset(object):
def __init__(self, activity_filter=True, target_filter=True, compound_filter=True):
self.session = Session()
query = (s... |
from pyparsing import *
from ...functions.deff import loadFromFile, loadLinesFromFile
from decl import *
PROTECTION << CaselessLiteral("Protection")
WALK << CaselessLiteral("Walk")
BASICKEYWORD << loadLinesFromFile("oracle/ref/basic_keywords.txt")
NUMBERKEYWORD << loadLinesFromFile("oracle/ref/number_keywords.txt")
COS... |
from msrest.serialization import Model
class BgpPeerStatusListResult(Model):
"""Response for list BGP peer status API service call.
:param value: List of BGP peers
:type value: list[~azure.mgmt.network.v2017_10_01.models.BgpPeerStatus]
"""
_attribute_map = {
'value': {'key': 'value', 'type':... |
"""964. Least Operators to Express Number
https://leetcode.com/problems/least-operators-to-express-number/
Given a single positive integer x, we will write an expression of the form
x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc.
is either addition, subtraction, multiplication, or division (+, -, *, or... |
import logging
from sqlalchemy.types import BigInteger
from regenesis.core import app, engine
log = logging.getLogger(__name__)
cube_table = engine.get_table('cube')
statistic_table = engine.get_table('statistic')
dimension_table = engine.get_table('dimension')
value_table = engine.get_table('value')
reference_table = ... |
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
# using two pointer to find possibilities
maxarea = 0
area = 0
left_width, right_width = 0, len(height)-1
while left_width < right_width:
... |
"""
The MIT License (MIT)
Copyright (c) 2015 Stephen J. Butler
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, mer... |
"""Run benchmarks.
Usage:
bench.py <bench_folder> [<output_folder>]
Options:
-h --help Show this help screen.
"""
from docopt import docopt
from os import listdir, path
from sys import path as sys_path
def scan_bench_files(directory):
"""Scan a directory for existing benchmark scripts.
:param str direct... |
from django import forms
from django.contrib.auth.models import User, SiteProfileNotAvailable
from django.core.mail import EmailMultiAlternatives
from django.core.urlresolvers import reverse
from django.forms import PasswordInput, HiddenInput
from settings import ROOT_URI
from echo.models import UserProfile
class Regis... |
from torch import nn
import torch
import torch.nn.functional as F
class PreActivationBlock(nn.Module):
def __init__(self, in_channels, channels, kernel_size=3, padding=1, dropout=None):
super(PreActivationBlock, self).__init__()
self.bn = nn.BatchNorm2d(in_channels)
self.conv = nn.Conv2d(in_... |
from subprocess import PIPE, Popen, call
from .analyzers import PyTestErrorAnalyzer
import click
import os
import requests
import dateutil.parser
import pytz
import datetime
import sys
__version__ = '0.1.4'
EMOJI_SUCCESS = u'✅'
EMOJI_FAIL = u'❌'
EMOJI_QUEUE = u'⏳'
ERROR_ANALYZERS = (
PyTestErrorAnalyzer,
)
class Ci... |
from pyparsingOD import oneOf, OneOrMore, printables, StringEnd
test = "The quick brown fox named 'Aloysius' lives at 123 Main Street (and jumps over lazy dogs in his spare time)."
nonAlphas = [ c for c in printables if not c.isalpha() ]
print("Extract vowels, consonants, and special characters from this test string:")... |
"""
Code to examine factors in Transfac.
"""
import biopsy.transfac as T
def factors_by_name(factor_name):
"@return: Yields factors that have the given name or are synonymous with it."
factor_name = factor_name.upper()
for f in T.Factor.all():
if f.name.upper() == factor_name:
yield f
... |
import StringIO
import os
from django.conf import settings
class AutoSerializer:
"""
Encapsulates the logic for creation of serializers for models in an app.
This class has methods that creates stream for serializers and then write
it into a file.
"""
def __init__(self, app_models_dict):
... |
"""Pylons bootstrap environment.
Place 'pylons_config_file' into alembic.ini, and the application will
be loaded from there.
"""
from alembic import context
from paste.deploy import loadapp
from logging.config import fileConfig
from sqlalchemy.engine.base import Engine
try:
# if pylons app already in, don't create ... |
import unittest2
from mock import Mock, patch
from eve_mlp.login import *
class TestDoLogin(unittest2.TestCase):
@patch("eve_mlp.login.submit_login", Mock())
@patch("eve_mlp.login.get_launch_token", Mock(return_value="TOKEN"))
def test_do_login(self):
token = do_login("username", "password")
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('niji', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='notification',
name=... |
import re
def test_cmdline(capsys):
from timebook.cmdline import run_from_cmdline
try:
run_from_cmdline(['--help'])
except SystemExit:
pass
out, err = capsys.readouterr()
regex = re.compile(r'^Timebook time tracker.*')
assert regex.search(out) is not None |
"""
Problem Statement
ABCXYZ company has up to 100 employees.
The company decides to create a unique identification number (UID) for each
of its employees.
The company has assigned you the task of validating all the randomly
generated UIDs.
A valid UID must follow the rules below:
It must contain at least 2 uppercase E... |
import logging
import os
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Mr. Admin', 'info@domain.tld'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'site.sqlite',
},
}
SITE_... |
import unittest
from iga.core import KeyedSets
class TestKeyedSets(unittest.TestCase):
def test_emptiness(self):
ksets = KeyedSets(['a', 'b'])
self.assertFalse(ksets)
ksets['a'].add('x')
self.assertTrue(ksets)
def test_getitem(self):
ksets = KeyedSets(['a', 'b'])
... |
import os
import sys
from decimal import ROUND_HALF_UP, Decimal
def execfile(fname, _globals, _locals):
"""
Usage: execfile('path/to/file.py', globals(), locals())
"""
if os.path.exists(fname):
with open(fname) as f:
code = compile(f.read(), os.path.basename(fname), 'exec')
... |
import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from keras.util... |
import xiangcheck
import unittest
SOLDIER_MOVES = {
'legal' : [((4,6), (4,5))],
'illegal' : [((0,6), (0,4))]
}
BLIND_CHECK = [
# move a soldier illegally to block
# an opposing horse
((6,3), (1,8)),
# move a solider illegally to block an
# opposing elephant
((8,3), (5,8)),
# unsucces... |
from collections import OrderedDict
from .dynamicbinary import DynamicBinary
class BinaryStore:
def __init__(self):
self._binaries = OrderedDict()
def add_binary(self, binary, name=None):
if name is None:
name = binary.get_name()
if name in self._binaries:
raise V... |
'''
it is an autoencoder that learns a latent variable model for its input data.
So instead of letting your neural network learn an arbitrary function,
you are learning the parameters of a probability distribution modeling your data.
If you sample points from this distribution, you can generate new input data
samples: ... |
from django import forms
from bootcamp.confcreator.models import ConfCreator
class ConfCreatorForm(forms.ModelForm):
status = forms.CharField(widget=forms.HiddenInput())
name = forms.CharField(
widget=forms.TextInput(attrs={'class': 'form-control'}),
max_length=255)
# template = forms.CharFi... |
class Solution:
def minimumCost(self, N: int, connections: List[List[int]]) -> int:
parent = [i for i in range(1 + N)]
def findParent(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
connections.sort(key=la... |
import numpy as np
import chainer
import chainer.functions as F
import chainer.links as L
class Fire(chainer.Chain):
def __init__(self, in_size, s1, e1, e3):
super().__init__(
conv1=L.Convolution2D(in_size, s1, 1),
conv2=L.Convolution2D(s1, e1, 1),
conv3=L.Convolution2D(s... |
from ElementBase import ElementBase
from ElementParameter import ElementParameter
from ElementValue import ElementValue
from objc_util import *
import console
class OpenLocationinGoogleMaps(ElementBase):
def __init__(self):
self.status = 'running'
self.output = None
self.params = []
self.type = 'Standard'
s... |
"""Tests for pypackages' config object and helper functions."""
import io
import os
import json
import mock
import pytest
import tempfile
from pypackage import config
from pypackage.config import Config
def test_requires_into_extras():
"""Any x_requires param should be converted to an extras_require param."""
c... |
from unicodedata import normalize
from . import bitcoin, ecc
from .bitcoin import *
from .ecc import string_to_number, number_to_string
from .crypto import pw_decode, pw_encode
from . import constants
from .util import (PrintError, InvalidPassword, hfu, WalletFileException,
BitcoinException)
from .mn... |
"幹線と地方交通線をまたがって利用する場合の計算"
import main_line
import local_line
import utils
class MainAndLocalLine(object):
"""幹線と地方交通線をまたがる場合 """
main_line_class = main_line.MainLine
local_line_class = local_line.LocalLine;
@classmethod
def fare(cls, main_d=0, local_d=0):
if main_d == local_d == 0:
return 0
elif local_d == ... |
import ply.yacc as yacc
import ply.lex as lex
tokens = ('IMPLY', 'PREDICATENAME', 'PREDICATEVAR', 'RPAREN', 'LPAREN')
precedence = (
('left', 'IMPLY'),
('left', '|'),
('left', '&'),
('right', '~'),
)
t_ignore = ' \t'
t_IMPLY = r'=>'
t_RPAREN = r'\)'
t_LPAREN = r'\('
literals = ['|', ','... |
from .NN import * |
import os
DEBUG = True
BIND_TO_OUTSIDE_IP = False
BIND_TO_PORT = 8000
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
APP_PATH = os.path.join(ROOT_PATH, "app")
RESOURCES_PATH = os.path.join(APP_PATH, "resources")
BASE_TEMPLATE_PATH = os.path.join(APP_PATH, "views")
SESSION_PATH = os.path.join(APP_PATH, "sessions... |
import getpass
import os
import shutil
import sys
import syslog
import tempfile
from subprocess import check_call, check_output, CalledProcessError, STDOUT
BASEDIR = "/etc/dovecot/auth/"
ULINE = "{}:{}:::\n"
DOVEADM = "/usr/bin/doveadm"
DEFAULT_SCHEME = "SSHA512"
SYSLOGFAC = syslog.LOG_MAIL
MINLENGTH = 9
def hash_passw... |
import logging
from typing import Optional, Dict
from solo.vendor.old_session.old_session import get_session
from sqlalchemy import select
from solo.apps.accounts.model import Auth, User, UserType, Guest, Group, users_groups_association, Permissions
from solo.apps.accounts.providers.base_oauth2 import ProfileIntegratio... |
def ByNestedComprehnsionAlogrithm(*sets):
"""Returns a list of all element combinations from the given sets.
A combination is represented as a tuple, with the first tuple
element coming from the first set, the second tuple element
coming from the second set and so on.
A set may be any iterabl... |
def algorithm3(arr):
maxSum = 0
currentSum = 0
for i in arr:
# If the current index and subarray are positive, keep adding to the subarray
if currentSum + i > 0:
currentSum = currentSum + i
else:
currentSum = 0
if currentSum > maxSum:
maxSu... |
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 6, 500);
y = np.sin(x)
plt.style.use('ggplot')
fig = plt.figure()
plt.plot(x, y)
plt.show()
fig.savefig('sin.pdf', format='pdf') |
from __future__ import unicode_literals
from ..tags.context import DataSetter
from ..elements import Attribute
from .. import errors
from moya.compat import text_type
class ElementContainer(object):
def __init__(self, archive):
self.archive = archive
def __getitem__(self, elementid):
return self... |
print "load pack/big/__init__.py"
__all__ = ['b1', 'b3'] |
import logging
import argparse
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
error_handler = logging.FileHandler("/var/log/fylm_error.log")
error_handler.setLevel(logging.ERROR)
debug_handler = logging.FileHandler("/var/log/fylm.log")
debug_handler.setLevel(logging.DEBUG)
log = logging... |
from anki.hooks import wrap
from aqt.editor import Editor, EditorWebView
import platform
from bs4 import BeautifulSoup
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
REMOVE_ATTRIBUTES = [
'color',
'background-color',
]
def get_parser():
system = platform.system()
... |
from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
outfile):
import os
import shutil
from Betsy import bie3
from ge... |
from bs4 import BeautifulSoup
from postlist import PostList
from time import strptime
GUBA_PING_URL = 'http://guba.eastmoney.com/list,%s_%d.html'
GUBA_FA_URL = 'http://guba.eastmoney.com/list,%s,f_%d.html'
class GuBa:
def __init__(self, code, crawler, s_date, e_date, errfile, elock, s_page=100, delta=100):
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('expeditions', '0007_auto_20161108_0359'),
]
operations = [
migrations.AddField(
model_name='registration',
name='retracted',
... |
"""
Updates the live version of the MatrixStore by updating the symlink at
MATRIXSTORE_LIVE_FILE. By default it searches for the most recently built
version of the most up-to-date file in MATRIXSTORE_BUILD_DIR (as determined by
the filename). If a date is supplied it restricts its search to files whose
timestamp (in th... |
import simtk.unit as units
from intermol.decorators import accepts_compatible_units
from intermol.forces.abstract_angle_type import AbstractAngleType
class QuarticAngleType(AbstractAngleType):
__slots__ = ['theta', 'C0', 'C1', 'C2', 'C3', 'C4', 'c']
@accepts_compatible_units(None, None, None,
... |
import re
import os
import sys
import pdb
import fileinput
import unicodecsv
import pprint
from collections import OrderedDict
county = 'Lane'
outfile = '20061107__or__general__columbia__precinct.csv'
headers = ['county', 'precinct', 'office', 'district', 'party', 'candidate', 'votes']
party_prefixes = ['DEM', 'REP']
o... |
import math
class Pagination(object):
def __init__(self, page, per_page, total_count, items):
self.items = items[(page - 1) * per_page:page * per_page]
self.page = page
self.per_page = per_page
self.total_count = total_count
@property
def pages(self):
return int(math.... |
import matplotlib.image as mpimg
import numpy as np
import cv2
from skimage.feature import hog
def get_hog_features(img, orient, pix_per_cell, cell_per_block,
vis=False, feature_vec=True):
# Call with two outputs if vis==True
if vis == True:
features, hog_image = hog(img, orienta... |
settings = {
'num_iterations': 500,
'population_size': 50, # number of organisms
'stopping_criteria': 0.001,
'num_iter_stop_criteria': 100,
'number_of_dimensions': 2,
'bounds': [ # this must have 1 pair per dimension
(-1,1.5),
(-1,2)
],
'selection_cutoff': 0.4,
'mutat... |
import logging
from mock import patch, ANY, MagicMock
from six import BytesIO
from spacel.cli.secret import (handle_secret, get_plaintext, encrypt,
update_manifest)
from test import BaseSpaceAppTest, ORBIT_NAME, APP_NAME, ORBIT_REGION
from test.security.test_payload import ENCRYPTED_PAYLO... |
"""
Extensions to the ``tdda`` command line tool, to support databases.
"""
import sys
from tdda.constraints.extension import ExtensionBase
from tdda.constraints.db.drivers import applicable
from tdda.constraints.db.discover import DatabaseDiscoverer
from tdda.constraints.db.verify import DatabaseVerifier
from tdda.con... |
"""
This is an example file who's uses Flask API Manager.
"""
from os import path
from random import getrandbits
from hashlib import sha256
from datetime import datetime
from flask_api_manager import Auth
from flask import Flask, jsonify
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchem... |
from common.tools.base64 import Base64Decoder
from common.challenge import MatasanoChallenge
from common.ciphers.block.aes import AES
from common.ciphers.block.modes import CBC
class Set2Challenge10(MatasanoChallenge):
FILE = 'set2/data/10.txt'
KEY = 'YELLOW SUBMARINE'
IV = '\0' * 16
def expected_value(... |
from flask_httpauth import HTTPBasicAuth
from flask_login import user_unauthorized
from app.model import AnonymousUser, User
from app.api_1_0.errors import forbidden
from app.api_1_0 import api
from flask import jsonify, g
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(email_or_token, password):
i... |
from msrest import Serializer, Deserializer
from typing import Any, Optional
class SubscriptionClientOperationsMixin(object):
async def check_resource_name(
self,
resource_name_definition: Optional["_models.ResourceName"] = None,
**kwargs: Any
) -> "_models.CheckResourceNameResult":
... |
"""
Hello World app for running Python apps on Bluemix
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='vvs-delay-datase... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
from django.conf.urls import include
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html'), name='home'),
path('api/', include('api.urls')),
path('admin/', admin.site.urls),
pa... |
"""Tests for the models of the ``hero_slider`` app."""
from django.test import TestCase
from mixer.backend.django import mixer
class SliderItemCategoryTestCase(TestCase):
"""Tests for the ``SliderItemCategory`` model."""
longMessage = True
def test_model(self):
instance = mixer.blend('hero_slider.Sl... |
import serial
from time import sleep
class RegTran:
CMD_READ = 'r'
CMD_WRITE = 'w'
ACK = 'k'
NACK = '!'
BURST = 32
def __init__(self):
self.channel = serial.Serial()
def channelOpen(self, port, baud, timeout):
if self.channel.isOpen():
self.channel.close()
self.channel.port = port
self.channel.baudrat... |
import os
from numpy import ones, zeros
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
TRAINING_DATA_DIR_PATH = os.path.join(PROJECT_ROOT, "training_data")
SAVED_MODEL_DIR_PATH = os.path.join(PROJECT_ROOT, "models")
MAX_WORD_LENGTH = 80
MAX_SENTENCE_LENGTH = 30
IDENTITY_AUTO_ENCODER_TRAINING_DATA = os.path.j... |
import test_config as config
from simnet import Simnet
from tools import timethis
import time
import grpc
from grpc._channel import _Rendezvous
DELAY = 5
def network_up():
simnet = Simnet(address='localhost:10001', name='simnet', number_of_nodes=config.NUMBER_OF_NODES, port_forwarding_conf=20000)
simnet.simnet_... |
from msrest.serialization import Model
class VirtualMachineScaleSetOSProfile(Model):
"""Describes a virtual machine scale set OS profile.
:param computer_name_prefix: Specifies the computer name prefix for all of
the virtual machines in the scale set. Computer name prefixes must be 1 to
15 characters ... |
from string import digits
OUTPUT = '{}{}{}'.format
def pattern(n):
nums = ''.join(digits[a % 10] for a in xrange(1, n + 1))
return '\n'.join(OUTPUT(' ' * (n - a), nums, ' ' * (a - 1))
for a in xrange(1, n + 1)) |
import sys
import os.path
__version__ = '0.2'
frozen = getattr(sys, 'frozen', False)
def find_res(filename):
if frozen:
return os.path.join(os.path.dirname(sys.executable), 'res', filename)
else:
return os.path.join(os.path.dirname(__file__), 'res', filename) |
import pytest
from six import iteritems
from config import load_parameters
from utils.utils import update_parameters
def test_update_parameters():
params = load_parameters()
updates = {
'ENCODER_HIDDEN_SIZE': 0,
'BIDIRECTIONAL_ENCODER': False,
'NEW_PARAMETER': 'new_value',
'ADDIT... |
from bs4 import BeautifulSoup as bs
import requests as r
import arrow
from datetime import timedelta, date
import re
def get_url(date): # date format: YYYY-MM-DD
# gocomics rejects requests from crawler
date_path = date.strftime("%Y/%m/%d")
url = "http://www.gocomics.com/calvinandhobbes/{}".format(date_pat... |
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):56884")
for line in lines:
m = pattern.match(line)
if m is None:
continue
ip = 0
... |
from jk_ps4a import *
import time
def isWordInHand(word, hand):
"""
Returns True if word can be constructed from this hand.
Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
"""
notFail = True
scratchHand = hand.copy()
# Tes... |
from setuptools import setup, find_packages
setup(
name='set-game',
version='1.1.0',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
url='https://github.com/jaywritescode/set-game',
license='MIT',
author='jay harris',
author_email='jaywritescode@users.noreply.github.com',
d... |
import logging
logger = logging.getLogger(__name__)
class AioJsonRpcException(Exception):
pass
class InvalidRequestException(AioJsonRpcException):
pass
class CustomJsonRpcException(AioJsonRpcException):
def __init__(self, code, data):
self.code = code
self.data = data
if not (-32099 ... |
from datetime import date
try:
import simplejson as json
except ImportError:
import json
from blueberrypy_skeleton.model import *
from blueberrypy_skeleton.model import metadata
from tests.helper import orm_session, Session
from blueberrypy.testing import ControllerTestCase
@orm_session
def populate_db():
s... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='FBUser',
fields=[
('fb_id', models.BigIntegerField(serialize=False, primary_... |
""" Pulls podcasts from the web and puts them in the destination dir."""
import feedparser
import time
import subprocess
import urllib
import logging
import datetime
import os
import shutil
import argparse
import pickle
LOGFILE='./log/podfetch.log'
DESTINATIONDIR = '/mnt/NAS/Buffalo/AApods'
LASTUPDATEDFILE = './lastupd... |
"""Twiss Module."""
import numpy as _np
import mathphys as _mp
import trackcpp as _trackcpp
from .. import tracking as _tracking
from ..utils import interactive as _interactive
from .miscellaneous import OpticsException as _OpticsException
class Twiss(_np.record):
"""."""
DTYPE = '<f8'
# NOTE: This ordering... |
import types
import os
import dash
assert isinstance(dash, types.ModuleType), "dash can be imported"
this_dir = os.path.dirname(__file__)
with open(os.path.join(this_dir, "../../../dash/version.py")) as fp:
assert dash.__version__ in fp.read(), "version is consistent"
assert getattr(dash, "Dash").__name__ == "Dash"... |
from distutils.core import setup
setup(
name='PyBureau',
version='0.2.0',
license='MIT',
author='Jan Bobisud',
author_email='me@bobisjan.com',
packages=['pybureau', 'pybureau.interior'],
) |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('books', '0014_auto_20150418_1614'),
]
operations = [
migrations.RemoveField(
model_name='goodsinfo',
name='sell_time',
),... |
from normal_forms import normal_form
import sympy
import numpy as np
from for_plotting import before_and_after
def f(x, y, mu=0):
f1 = y
f2 = -mu * y - x + x * x * x
return f1, f2
h = normal_form(f, (0, 0), 3)
before_and_after(f, h, -2, 2, -2, 2) |
def decorator(F):
def new_F(a, b):
print("input", a, b)
return F(a, b)
return new_F
@decorator
def square_sum(a, b):
return a**2 + b**2
@decorator
def square_diff(a, b):
return a**2 - b**2
print(square_sum(3, 4))
print(square_diff(3, 4)) |
import os
from einops import _backends
import warnings
__author__ = 'Alex Rogozhnikov'
import logging
logging.getLogger('tensorflow').disabled = True
logging.getLogger('matplotlib').disabled = True
assert os.environ.get('EINOPS_SKIP_CUPY', '') in ['', '1', '0']
skip_cupy = os.environ.get('EINOPS_SKIP_CUPY', '') == '1'
... |
"""Trains the sentence composition model.
"""
import argparse
from pathlib import Path
import h5py
import numpy as np
import tensorflow as tf
from sklearn.metrics import average_precision_score as average_precision
import compmodel
import dataio
from metrics import mean_reciprocal_rank
EMBEDDING_SIZE = 300
EPOCHS = 3
K... |
'''
.. module:: filers
This module contains the lower level API that handles the storing to the filesystem
.. moduleauthor:: Christopher Phillippi <c_phillippi@mfe.berkeley.edu>
'''
import helpers as helpers
class BatchFiler( object ):
'''API to retrieve data from a given download batch
'''
def __init__( se... |
"""Support Vector Machine implementation.
"""
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
from qikify.helpers import standardize
class SVM(object):
"""Support Vector Machine implementation.
"""
def __init__(self, grid_search = False):
"""Support Vector Machine implementa... |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# Example:
# (r'^djangotimy/', include('djangotimy.foo.urls')),
(r'^timyweb/', include('djangotimy.timyweb.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documenta... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('invoice', '0013_auto_20171029_1347'),
]
operations = [
migrations.AlterField(
model_name='company',
name='name',
fiel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.