code stringlengths 1 199k |
|---|
from __future__ import absolute_import
from __future__ import print_function
import sys
import glob
import time
import numpy as np
import pandas as pd
import os.path
import time
import datetime
import re
from keras.preprocessing import sequence
from keras.optimizers import SGD, RMSprop, Adagrad
from keras.utils import ... |
from sklearn.linear_model import Lasso
def get_lasso_prediction(train_data, train_truth, test_data, test_truth, alpha=1.0, iter_id=0):
clf = Lasso(alpha=alpha)
clf.fit(train_data, train_truth)
predicted = clf.predict(test_data)
return predicted.ravel() |
import sqlite3
from typing import List
from pyspatial.cs import CoordinatesSystem, Axis, CoordinatesSystemType, AxisOrientation, AxisType
from pyspatial.uom import UnitOfMeasure
from . import db, EPSGException, make_id, parse_id
from .uom import get_unit
def get_coordinates_system(uid: str) -> CoordinatesSystem:
""... |
from datetime import datetime
import webapp2
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from models import Email, Subscriber
from google.appengine.api import mail
class LogSenderHandler(InboundMailHandler):
def receive(self, message):
# Rebu... |
from model import User
from geo.geomodel import geotypes
def get(handler, response):
lat1 = handler.request.get('lat1')
lon1 = handler.request.get('lng1')
lat2 = handler.request.get('lat2')
lon2 = handler.request.get('lng2')
response.users = User.bounding_box_fetch(
User.all(),
geotypes.Box(float(lat1... |
"""
Dummy conftest.py for graph_stix.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
from __future__ import print_function, absolute_import, division
import pytest |
from io import BytesIO
from itertools import groupby
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import make_response, render_template, abort
from webapp import app
from webapp.evaluation import *
from web... |
import logging
from django.core.management.base import BaseCommand
from notifications.engine import send_all
class Command(BaseCommand):
help = "Emit queued notices."
def handle(self, *args, **options):
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
logging.info("-" * 72)
... |
from __future__ import annotations
import abc
import shutil
import functools
from pathlib import Path
import urllib.parse
from typing import (
Callable, Any, TypeVar, cast, Tuple, Dict, Optional,
Union, Hashable,
)
import logging
from edgar_code.types import PathLike, Serializer, UserDict
from edgar_code.util.p... |
"""
A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a
procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative
process.
"""
from operator import lt, sub, add, mul
def f_recursive(n):
if l... |
from __future__ import absolute_import, division, print_function
import os
from idaskins import UI_DIR
from PyQt5 import uic
from PyQt5.Qt import qApp
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor, QFont, QKeySequence
from PyQt5.QtWidgets import QShortcut, QWidget
Ui_ObjectInspector, ObjectInspectorBase =... |
import sys, os
import sys
class Mock(object):
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return Mock()
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
elif name[0] == name[0].... |
from app.core.helper import create_app
from app.core.db import db
from app.core.json import json_respon
from app.user.views import user_views
from app.user.models import*
from app.user.loginmanager import login_manager
from app.hotel.views import hotel_views
from app.hotel.models import*
from app.reservation.views impo... |
"""Support to interface with the Plex API."""
from __future__ import annotations
from functools import wraps
import json
import logging
import plexapi.exceptions
import requests.exceptions
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, MediaPlayerEntity
from homeassistant.components.media_player... |
'''
Tests of output_plots.py module
'''
import pytest
import os
import numpy as np
import matplotlib.image as mpimg
from ogusa import utils, output_plots
CUR_PATH = os.path.abspath(os.path.dirname(__file__))
base_ss = utils.safe_read_pickle(
os.path.join(CUR_PATH, 'test_io_data', 'SS_vars_baseline.pkl'))
base_tpi =... |
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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, pu... |
from __future__ import print_function
import datetime
import os
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from keras.engine.training import Model
from keras.initializers import RandomUniform
from keras.layers import Convolution1D, MaxPooling1D
from keras.layers import Dense, Dropout,... |
"Utility functions for the tests."
import json
def get_settings(**defaults):
"Update the default settings by the contents of the 'settings.json' file."
result = defaults.copy()
with open("settings.json", "rb") as infile:
data = json.load(infile)
for key in result:
try:
result... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myinventory.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import numpy as np
import os
import random
import threading
import time
import traceback
from util import cmudict, textinput
from util.infolog import log
import chainer
_batches_per_group = 32
_p_cmudict = 0.5
_pad = 0
class PreprocessedDataset(chainer.dataset.DatasetMixin):
def __init__(self, metadata_filename, hp... |
from typing import Dict
from urllib.parse import quote
def request_path(env: Dict):
return quote('/' + env.get('PATH_INFO', '').lstrip('/')) |
from django.contrib import admin
from .models import Organization
admin.site.register(Organization) |
import sys
import argparse
import regrws
import regrws.method.org
try:
from apikey import APIKEY
except ImportError:
APIKEY = None
epilog = 'API key can be omitted if APIKEY is defined in apikey.py'
parser = argparse.ArgumentParser(epilog=epilog)
parser.add_argument('-k', '--key', help='ARIN API key',
... |
from test_framework.test_framework import AureusTestFramework
from test_framework.util import *
import base64
try:
import http.client as httplib
except ImportError:
import httplib
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
class HTTPBasicsTest (AureusTestFramework):
def... |
import argparse
import os
import random
from math import floor, trunc
_word_list_file = 'video_game_names.txt'
_word_list = []
def _build_list(word_list=_word_list_file):
try:
f = open(word_list, 'r')
words = []
for line in f:
line = line.strip('\n')
if line == "----"... |
from glob import glob
from io import open
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
options =... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('photos', '0003_rover'),
]
operations = [
migrations.AddField(
model_name='photo',
name='rover',
... |
import os
import sys
import argparse
import requests
import subprocess
import shutil
class bcolors:
HEADER = '\033[90m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
class Console:
def __init__(self):
self.verbose = False
def log... |
"""
Decorators
"""
from __future__ import unicode_literals
from functools import wraps
from django.http import HttpResponseBadRequest
from django.utils.decorators import available_attrs
from django_ajax.shortcuts import render_to_json
def ajax(function=None, mandatory=True, **ajax_kwargs):
"""
Decorator who gue... |
import pla
import numpy as np
def read_data(filename):
with open(filename, 'r') as infile:
X = []
y = []
for line in infile:
fields = line.strip().split()
X.append([float(x) for x in fields[:-1]])
y.append(0 if fields[-1] == '-1' else 1)
return np.arra... |
"""
PynamoDB Connection classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from typing import Any, Dict, Mapping, Optional, Sequence
from pynamodb.connection.base import Connection, MetaTable, OperationSettings
from pynamodb.constants import DEFAULT_BILLING_MODE, KEY
from pynamodb.expressions.condition import Condition
from pynam... |
__revision__ = "test/SWIG/SWIGOUTDIR.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Verify that use of the $SWIGOUTDIR variable causes SCons to recognize
that Java files are created in the specified output directory.
"""
import TestSCons
test = TestSCons.TestSCons()
swig = test.where_is('swig')
if not... |
import re
from unittest import TestCase
def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_p... |
import os
import math
def GA_settings():
"""Provides the view for the user setting of the GA experiments and returns the settings set"""
options = {}
os.system("clear")
print('===== OPTIONS =====\n')
preset = int(raw_input(
"PRESET\n"
"Use preset ?\n"
"\n\n-> 1: Source based ... |
import pygame
from pygame.locals import *
from Constants import Constants
from FadeTransition import FadeTransition
from Menu import Menu
from GW_Label import GW_Label
from GuiWidgetManager import GuiWidgetManager
from xml.sax import make_parser
from Localization import Localization
import os
class ExitMenu(Menu):
"Ex... |
"""
Classes for char-to-int mapping and int-to-int mapping.
:Author: James Taylor (james@bx.psu.edu)
The char-to-int mapping can be used to translate a list of strings
over some alphabet to a single int array (example for encoding a multiple
sequence alignment).
The int-to-int mapping is particularly useful for creatin... |
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
An Eulerer
"""
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Specials.Simulaters.Populater"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer"
SYS.setSubModule(globals())
import numpy as np
@D... |
import os
import signal
import subprocess
import beanstalkc
import time
import pexpect
try:
import unittest2 as unittest
except ImportError:
import unittest
from beanstalkctl.util import BeanstalkdMixin
class BaseSpec(unittest.TestCase, BeanstalkdMixin):
beanstalkd_instance = None
beanstalkd_host = '127... |
from pyvisdk.thirdparty import Enum
HostDiskPartitionInfoPartitionFormat = Enum(
'gpt',
'mbr',
'unknown',
) |
"""Status effect data."""
from components.status_effect import StatusEffect
from status_effect_functions import damage_of_time
STATUS_EFFECT_CATALOG = {
'POISONED':
{
'name': 'poisoned',
'tile_path': 'status_effect/poisoned.png',
'color': 'green',
'tick_function': damage_of_time,... |
text = '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 \
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 \
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 \
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 \
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 \
24... |
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='MKS',
version='0.1.0',
description="A unit system based on meter, kilo, and second",
author='Roderic Day',
author_email='roderic.day@gmail.com',
url='www.permanentsign... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("capture", ["capture.pyx"])]
) |
from django.db import migrations
def forwards(apps, schema_editor):
"""
Change all DancePiece objects into Work objects, and their associated
data into WorkRole and WorkSelection models, then delete the DancePiece.
"""
DancePiece = apps.get_model("spectator_events", "DancePiece")
Work = apps.get... |
from __future__ import division
from __future__ import print_function
import numpy as np
import numpy.testing as npt
import pandas as pd
from deepcpg.data import annotations as annos
def test_join_overlapping():
f = annos.join_overlapping
s, e = f([], [])
assert len(s) == 0
assert len(e) == 0
s = [1... |
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root@localhost:3306/microblog'
SQLALCHEMY_TRACK_MODIFICATIONS = False
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
DEBUG = False |
from distantio.DistantIO import DistantIO
from distantio.DistantIOProtocol import distantio_protocol
from distantio.SerialPort import SerialPort
from distantio.crc import crc16 |
import datetime
import logging
from unittest.mock import patch
from django.test import TestCase
from django.test.utils import override_settings
from konfera import models
from payments import utils
from payments.models import ProcessedTransaction
def make_payment(new_data):
data = {
'date': datetime.date(20... |
"""
Django settings for news_project project.
Generated by 'django-admin startproject' using Django 1.10.5.
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 o... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2014-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... |
import random, sys
if len(sys.argv)!= 2:
print "Usage: python generate.py <how many instructions you want>"
sys.exit()
choices = ("(", ")")
output = ""
for x in range(int(sys.argv[1])):
output += random.choice(choices)
f = open("randout", "w")
f.write(output)
f.close
print "Created an instruction set that i... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0013_merge'),
]
operations = [
migrations.AlterField(
model_name='user',
name='public',
field=models.BooleanF... |
import subprocess
import sys
import signal
import datetime
import argparse
import requests
import calendar
import json
import zlib
import time
def get_median (values):
sv = sorted(values)
if len(sv) % 2 == 1:
return sv[(len(sv) + 1) / 2 - 1]
else:
lower = sv[len(sv) / 2 - 1]
upper = sv[len(sv) / 2]
return fl... |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class ContactsAppConfig(AppConfig):
name = 'apps.contacts'
verbose_name = _('Contacts') |
import importlib.util
import logging
import os
import warnings
from os import getenv
from typing import Any, Optional, Mapping, ClassVar
log = logging.getLogger(__name__)
default_settings_dict = {
'connect_timeout_seconds': 15,
'read_timeout_seconds': 30,
'max_retry_attempts': 3,
'base_backoff_ms': 25,
... |
"""
envois.test
~~~~~~~~~~~~
nosetests for the envois pkg
:copyright: (c) 2012 by Mek
:license: BSD, see LICENSE for more details.
"""
import os
import json
import unittest
from envois import invoice
jsn = {"seller": {"name": "Lambda Labs, Inc.", "address": {"street": "857 Clay St. Suite 206", "city... |
import torch
from torch.nn import Parameter
from functools import wraps
class WeightDrop(torch.nn.Module):
def __init__(self, module, weights, dropout=0, variational=False):
super(WeightDrop, self).__init__()
self.module = module
self.weights = weights
self.dropout = dropout
... |
"""
Created on Thu Apr 27 12:16:26 2017
@author: Anand A Joshi, Divya Varadarajan
"""
import glob
from os.path import isfile, split
import configparser
config_file = u'/big_disk/ajoshi/ABIDE2/study.cfg'
Config = configparser.ConfigParser()
Config.read(config_file)
Config.sections()
STUDY_DIR = Config.get('CSESVREG', 'S... |
import json
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.utils import timezone
from django.shortcuts import render_to_response
from cir.models import *
import claim_views
from cir.phase_control import PHASE_CONTROL
import utils
def get_statement_comment_list(reque... |
from setuptools import setup
def readme():
with open('README.md','r') as fr:
return fr.read()
setup(name='docker_machinator',
version='0.1',
description='A tool for managing docker machines from multiple'
'workstations',
long_description=readme(),
entry_points={
... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Message'
db.create_table('firstclass_message', (
('key', self.gf('django... |
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
import tensorflo... |
from flask import Flask
from flask import render_template
from .. import app
@app.route('/')
def index():
user = {'first_name': 'Lance', 'last_name': 'Anderson'}
return render_template('index.html', user=user)
@app.route('/user/<user_id>/board/<board_id>')
@app.route('/new_board')
def board(user_id=None, board_... |
raise NotImplementedError("getopt is not yet implemented in Skulpt") |
import os
from ctypes import CDLL, c_char_p, c_int, c_void_p, c_uint, c_double, byref, Structure, get_errno,\
POINTER, c_short, c_size_t, create_string_buffer
from ctypes.util import find_library
from psistats.libsensors.lib import stdc
version_info = (0, 0, 3)
__version__ = '.'.join(map(str, version_info))
__date_... |
import re
records = [
'April 13, 2013 Cyberdyne Systems $4,000.00 18144 El Camino '
'Real, Sunnyvale, CA 94087 (408) 555-1234 info@cyberdyne.com '
'December 2, 2018 December 14, 2018',
'May 4, 2013 Sam Fuzz, Inc. $6,850.50 939 Walnut St, San '
'Carlos, CA 94070 (408) 55... |
import daphne_context.utils
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('daphne_context', '0010_userinformation_mycroft_c... |
import matplotlib.transforms
import numpy
def has_legend(axes):
return axes.get_legend() is not None
def get_legend_text(obj):
"""Check if line is in legend."""
leg = obj.axes.get_legend()
if leg is None:
return None
keys = [h.get_label() for h in leg.legendHandles if h is not None]
valu... |
import functools
from time import strftime
import tensorflow as tf
def lazy_property(function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
return... |
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
p = len(B[0])
C = [[0 for _ in xrange(p)] for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(... |
"""
This is a doctest example with Numpy arrays.
For more information about doctest, see
https://docs.python.org/3/library/doctest.html (reference)
and
www.fil.univ-lille1.fr/~L1S2API/CoursTP/tp_doctest.html (nice examples in
French).
To run doctest, execute this script (thanks to the
`if __name__ == "__main__": import... |
import matplotlib.pyplot as plt #import modules
import matplotlib.patches as mpatches
import numpy as np
water = [0,2,2,3,1.5,1.5,3,2,2,2,2,2.5,2] #arrange data from lab
alc = [0,2.5,2.5,2.5,2.5,3,2.5,2.5]
weight = [20.9+(0.41*5*x) for x in range(0,13)] #generate weight array, based on mass of paper clips, in grams
act... |
from __future__ import with_statement
from cuisine import *
from fabric.api import env
from fabric.colors import *
from fabric.utils import puts
from fabric.context_managers import cd, settings, prefix
from flabric import ApplicationContext as AppContext
from flabric.ubuntu import UbuntuServer
import os, flabric
class ... |
import json_creator
class Message:
def __init__(self, sent_to, sent_from, text):
self.sent_from = sent_from
self.text = text
self.sent_to = sent_to
def parse_message(self, message_dict):
self.sent_from = json_creator.get_message_sendfrom(message_dict)
self.sent_to = json_... |
"""
Settings for testing the application.
"""
import os
DEBUG = True
DJANGO_RDFLIB_DEVELOP = True
DB_PATH = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'rdflib_django.db'))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_PATH,
'USER': '',
'P... |
import Image
import json
south = 51.416;
north = 51.623;
west = -0.415;
east = 0.179;
if __name__ == "__main__":
x = Image.fromstring("RGBA", (2668,1494), open("output_pixel_data").read())
x.save("lit-map.png", "PNG") |
import threading
server = None
web_server_ip = "0.0.0.0"
web_server_port = "8000"
web_server_template = "www"
def initialize_web_server(config):
'''
Setup the web server, retrieving the configuration parameters
and starting the web server thread
'''
global web_server_ip, web_server_port, web_server_... |
""" Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """
import os
import re
import sys
def fixhtml(folder):
changed = 0
for dirpath, _, filenames in os.walk(folder):
for file in filenames:
name, ext = os.path.splitext(file)
if ext != '.html':
cont... |
import subprocess
import sys
import shutil
import os
import os.path
import unittest
import json
import getpass
import requests
import zipfile
import argparse
import io
import tempfile
import time
import lark
from osspeak import version
OSSPEAK_MAIN_PATH = os.path.join('osspeak', 'main.py')
OSSPEAK_SRC_FOLDER = 'osspeak... |
T = int(raw_input())
for test in xrange(T):
N = int(raw_input())
a, b, result = 0, 1, 0
c = a+b
while c < N:
if c%2 == 0:
result += c
a,b = b,c
c = a+b
print result |
import numbers
import warnings
from functools import wraps, partial
from typing import List, Callable
import logging
import numpy as np
import jax
import jax.numpy as jnp
import jax.scipy as scipy
from jax.core import Tracer
from jax.interpreters.xla import DeviceArray
from jax.scipy.sparse.linalg import cg
from jax im... |
def urepr(x):
import re, unicodedata
def toname(m):
try:
return r"\N{%s}" % unicodedata.name(unichr(int(m.group(1), 16)))
except ValueError:
return m.group(0)
return re.sub(
r"\\[xu]((?<=x)[0-9a-f]{2}|(?<=u)[0-9a-f]{4})",
toname,
repr(x)
)
... |
def no_extreme(listed):
"""
Takes a list and chops off extreme ends
"""
del listed[0]
del listed[-1:]
return listed
def better_no_extreme(listed):
"""
why better ? For starters , does not modify original list
"""
return listed[1:-1]
t = ['a','b','c']
print t
print '\n'
print 'pop any element : by t.pop(1) or ... |
import os, sys
import random
import time
import feedparser
import itertools
import HTMLParser
from feed import Feed
if os.getcwd().rstrip(os.sep).endswith('feeds'):
os.chdir('..')
sys.path.insert(0, os.getcwd())
from gui_client import new_rpc
import web
import reddit
class RSSFeed(Feed):
def __init__(self):... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mat", type=str, help="mat file with observations X and side info", required=True)
parser.add_argument("--epochs", type=int, help="number of epochs", default = 2000)
parser.add_argument("--hsize", type=int, help="size of the hidden layer", ... |
import os.path
import subprocess
import pkg_resources
import setuptools # pylint: disable=unused-import
def get_package_revision(package_name):
# type: (str) -> str
"""Determine the Git commit hash for the Shopify package.
If the package is installed in "develop" mode the SHA is retrieved using Git. Otherw... |
from setuptools import setup
setup(
name='SecFS',
version='0.1.0',
description='6.858 final project --- an encrypted and authenticated file system',
long_description= open('README.md', 'r').read(),
author='Jon Gjengset',
author_email='jon@thesquareplanet.com',
maintainer='MIT PDOS',
main... |
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^view$', views.archive),
url(r'^$', views.welcome),
url(r'^create', views.create_blogpost),
] |
"""Helper to handle a set of topics to subscribe to."""
from __future__ import annotations
from collections import deque
from collections.abc import Callable
import datetime as dt
from functools import wraps
from typing import Any
import attr
from homeassistant.core import HomeAssistant
from homeassistant.helpers impor... |
def is_palindrome(data):
if isinstance(data, list):
data = ''.join(c.lower() for c in ''.join(data) if c.isalpha())
if isinstance(data, str):
return "Palindrome" if data == data[::-1] else "Not a palindrome"
else:
return "Invalid input"
if __name__ == "__main__":
with open("input... |
from typing import Any, Dict, List, Sequence, Tuple
from gym3.types import ValType
class Env:
"""
An interface for reinforcement learning environments.
:param ob_space: ValType representing the valid observations generated by the environment
:param ac_space: ValType representing the valid actions that a... |
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1440369075.543512
_enable_loop = True
_template_filename = u'themes/monospace/templates/index.tmpl'
_template_uri = u'index.tmpl'
_source_encoding = 'utf-8'
_exp... |
import csv
import os
baseline_csv = r"baseline.csv"
new_csv = r"cleaned_csv.csv"
baseline_as_rows = []
new_as_rows = []
if not os.path.exists(baseline_csv):
quit("The baseline log csv file is not found - please check your filename '{}'".format(baseline_csv))
if not os.path.exists(new_csv):
quit("Your local log csv fi... |
import sys
import os
import shlex
sys.path.insert(0, os.path.abspath('../../src'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'feeluown'
copyright = '2015, cosven'
author = 'cosven'
version = '1.0'
release =... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.forms.models import modelformset_factory
from django.forms.formsets import formset_factory
from formsettesthelpers import *
from formsettesthelpers.test_app.forms import (
UserFo... |
"""
Computes and compares nilsimsa codes.
A nilsimsa code is something like a hash, but unlike hashes, a small
change in the message results in a small change in the nilsimsa
code. Such a function is called a locality-sensitive hash.
Python port of ruby version that was inspired by a perl version:
http://ixazon.dyni... |
"""
graph.py
-------------
Deal with graph operations. Primarily deal with graphs in (n, 2)
edge list form, and abstract the backend graph library being used.
Currently uses networkx or scipy.sparse.csgraph backend.
"""
import numpy as np
import collections
from . import util
from . import grouping
from . import except... |
"""
FILE: datalake_samples_access_control_recursive_async.py
DESCRIPTION:
This sample demonstrates recursive set/get access control on directories.
USAGE:
python datalake_samples_access_control_recursive_async.py
Set the environment variables with your own values before running the sample:
1) STORAGE_AC... |
maxcats = 15
import warnings
warnings.filterwarnings("ignore")
true = True; TRUE = True
false = False; FALSE = False
import pip
def install(package): pip.main(['install', package])
try:
import pandas as pd, numpy as np, scipy, sklearn as sk, seaborn as sb
from copy import copy
from jupyterthemes import jtpl... |
'''
Creates a Gene Wiki protein box template around a gene specified by
the first argument passed to it on the command line.
Usage: `python create_template.py <entrez_id>`
'''
import sys
from genewiki.mygeneinfo import parse
if len(sys.argv[1]) > 1:
entrez = sys.argv[1]
try: int(entrez)
except ValueEr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.