code stringlengths 1 199k |
|---|
"""foodcalc URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
class InstructionType:
load = 1
store = 2
jump = 3
branch_if_equal = 4
jump_and_link = 5
return_ = 6
add = 7
subtract = 8
add_immediate = 9
nand = 10
multiply = 11
halt = 12 |
"""website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
'''
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
'''
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
board = [['.' for j in range(n)] for i in range(n)]
... |
from nltk.tag import StanfordPOSTagger
import utility as util
import sys
import os
import re
import properties
import gensim
import string as mstring
reload(sys)
sys.setdefaultencoding('utf-8')
tagger = properties.tagger
taggerJARPath = properties.taggerJARPath
st = StanfordPOSTagger(tagger,taggerJARPath)
chunkFile = p... |
from __future__ import unicode_literals
import unittest
from textwrap import dedent
from calmjs.parse import es5
from calmjs.parse.asttypes import Node
from calmjs.parse.asttypes import Identifier
from calmjs.parse.asttypes import Catch
from calmjs.parse.ruletypes import Attr
from calmjs.parse.ruletypes import Resolve
... |
import os
import logging
_logger = logging.getLogger(__name__)
def parse_args():
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('path', help='path to dumped cProfiles')
parser.add_argument('--outdir', help='output directory', default='.')
args, _ = parser.parse... |
import asyncio
from decimal import Decimal
import threading
from typing import TYPE_CHECKING, List, Optional, Dict, Any
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.uix.recycleview import Recycle... |
import sys
import random
from nose.tools import *
from mock import patch
from docopt import docopt, DocoptExit
from schema import Schema, SchemaError, And, Or, Use
import randfilter
def make_docdict(f, n, p, u, i, h, v):
return {
'-n':n,
'-p':p,
'--unorder':u,
'--ignore-empty':i,
... |
"""Django settings for djangoreactredux project."""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) # remove /sswmain/settings to get base folder
SECRET_KEY = 'ajsdgas7&*kosdsa21[]jaksdhlka-;kmcv8l$#diepsm8&ah^'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['localhost']
INSTALLED... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('carts', '0007_merge'),
]
operations = [
migrations.AlterField(
model_name='cart',
name='subtotal',
field=models.Decim... |
import unittest
import re
import os
from urllib.request import urlopen
import ssl
from themis.modules.general import regex_base_url, get_looker_instance, format_output
class GeneralTestCase(unittest.TestCase):
base_url = os.environ.get('LOOKERSDK_BASE_URL')
def test_legacy_instance_url(self):
self.asser... |
"""Izzo's algorithm for Lambert's problem
"""
import numpy as np
from numpy import pi
from astropy import units as u
from poliastro.jit import jit
from poliastro.util import norm
from poliastro.hyper import hyp2f1b
def lambert(k, r0, r, tof, M=0, numiter=35, rtol=1e-8):
"""Solves the Lambert problem using the Izzo ... |
s = float(input("Digite seu salário: "))
if s > 1250:
aumento = 0.10
else:
aumento = 0.15
aumentoReais = s * aumento
print("Seu aumento foi de {}%, que equivale a R$:{:.2f} e com isso seu salário será de R$:{:.2f}.".format(aumento * 100, aumentoReais, s + aumentoReais)) |
def __load():
import imp, os, sys
ext = 'CoreFoundation/_CoreFoundation.so'
for path in sys.path:
if not path.endswith('lib-dynload'):
continue
ext_path = os.path.join(path, ext)
if os.path.exists(ext_path):
mod = imp.load_dynamic(__name__, ext_path)
... |
import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import scipy.stats
import numpy.ma
import Stats
import Histogram
from CGATReport.Tracker import *
from cpgReport import *
class IntervalList(cpgTracker):
'''list of intervals.'''
nresults = 20
mColumnsF... |
import os
import numpy as np
def text2vector(filename):
x = np.ones((1, 1025))
fr = open(filename)
for i in range(32):
l = fr.readline()
for j in range(32):
x[0, 32 * i + j + 1] = int(l[j])
return x
def loadData(filedir):
filelist = os.listdir(filedir)
m = len(filelis... |
from db import Base, Session
from sqlalchemy import *
from sqlalchemy.orm import relation, sessionmaker, relationship
from sqlalchemy import ForeignKey
from sqlalchemy import Enum
from enums import NeighborhoodsEnum
class VolunteerNeighborhoods(Base):
__tablename__ = 'volunteerNeighborhoods'
id = Column(Integer... |
from .. import redis
def set_user_state(openid, state):
"""设置用户状态"""
redis.hset('wechat:user:' + openid, 'state', state)
return None
def get_user_state(openid):
"""获取用户状态"""
return redis.hget('wechat:user:' + openid, 'state')
def set_user_last_interact_time(openid, timestamp):
"""保存最后一次交互时间"""
... |
'''
This module serves not purpose besides being a testing crutch for me
as I develop popen.
'''
from . import Sh
from StringIO import StringIO
if __name__ == '__main__':
# This is a test
Sh.debug = True
print Sh('w')
if Sh('ls') | 'sort':
print "OK"
if Sh('make').include_stderr | 'wc':
... |
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_SimOrganization_Organization_Default', [dirname(__file__)])
except ImportError:... |
import time
from django.test import LiveServerTestCase
from websocket import create_connection
from ws4redis.django_runserver import application
class WebsocketTests(LiveServerTestCase):
fixtures = ['data.json']
@classmethod
def setUpClass(cls):
super(WebsocketTests, cls).setUpClass()
cls.se... |
import os
from xml.etree.ElementTree import parse
import re
import sys
os.chdir(r'.')
files = os.listdir('.')
target = ""
domre = re.compile('')
csrfre = re.compile('csrf', re.I)
if len(sys.argv) == 2:
tree = parse(sys.argv[1])
else:
sys.exit(0)
class HeaderDict(object):
def __init__(self, allow_multiple=Fa... |
"""Test multisig RPCs"""
from test_framework.descriptors import descsum_create
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_raises_rpc_error,
assert_equal,
)
from test_framework.key import ECPubKey
import binascii
import decimal
import itertools
import ... |
import operator
import sys
import types
import unittest
import py
import six
def test_add_doc():
def f():
"""Icky doc"""
pass
six._add_doc(f, """New doc""")
assert f.__doc__ == "New doc"
def test_import_module():
from logging import handlers
m = six._import_module("logging.handlers")... |
import os
import sys
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
) # noqa: E402
import fabulist # noqa: F401 |
from enum import Enum
from utils import Singleton
class Color(Enum):
white = 1
black = 2
class Piece():
def __init__(self, color):
self.color = color
def flip(self):
self.color = Color.white if self.color == Color.black else Color.black
class Board():
def __init__(self, rows, columns... |
import inspect
import json
from collections import OrderedDict
from pathlib import Path
import random
import pandas as pd
import hashlib
import numpy as np
from keras.utils import np_utils
from scipy.stats.mstats import gmean
import xgboost as xgb
from sklearn import model_selection
from sklearn.ensemble import RandomF... |
from math import pi
rawfile, average, counter, timeing = open("/Users/jack.sarick/Desktop/Program/Python/pi/pianswer.txt").read().split("\n"), 0, 0, 0
for i in rawfile:
if (list(str(i))[0] == "3"):
average += float(i.split(",")[0])
timeing += float(i.split(",")[1])
counter += 1
print "Pi = " + str(average/counte... |
import os, sys, random
from collections import defaultdict
inFilePath = sys.argv[1]
queryMetric = sys.argv[2]
outFilePath = sys.argv[3]
resultsDict = defaultdict(lambda: {})
for line in file(inFilePath):
lineItems = line.rstrip().split("\t")
metric = lineItems[2]
if metric != queryMetric:
continue
... |
from ctypes import *
from ctypes.wintypes import *
import os, sys
kernel32 = windll.kernel32
ntdll = windll.ntdll
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
NULL = 0x0
OPEN_EXISTING = 0x3
PROCESS_VM_WRITE = 0x0020
PROCESS_VM_READ ... |
import pyglet;
from itertools import chain;
from victor.vector import *;
__all__ = ['MovementGrid'];
scales = (1, 5, 10, 20, 40, 80);
class MovementGrid(object):
def __init__(self, width, height, color = (127, 127, 127 , 127)):
self.color = color;
self.width = width;
self.height = height;
... |
import time
import onionGpio
gpioNum = 1
gpioObj = onionGpio.OnionGpio(gpioNum)
status = gpioObj.setOutputDirection(0) # initialize the GPIO to 0 (LOW)
loop = 1
value = 0
while loop == 1:
# reverse the value
if value == 0:
value = 1
else:
value = 0
# set the new value
status = gpioObj.setValue(value)
pri... |
from migration.migration import Migration
import asyncio
loop = asyncio.get_event_loop()
host = "127.0.0.1"
port = 2003
directory = '/Users/yunx/Documents/PROJECTS/metrics-migration/examples'
async def go():
migration_worker = Migration(directory, host, port, loop=loop)
await migration_worker.connect_to_graphit... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.contrib.postgres.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoF... |
import lightning
from enum import Enum
class ChannelState(Enum):
START = 0
REFUND_ESTABLISHED = 1
ANCHOR_POSTED = 2
class ChannelParams:
def __init__(self, anchor_txid, sats_per_update):
# Anchor txid hash
self.anchor_txid = anchor_txid
# Channel updates happen this many satoshis at a time
self.... |
__author__ = 'steven'
DEBUG = False
BASE_DIR = ""
PASSWORD_FILE = "" |
from __future__ import unicode_literals
import os
import sys
os.environ['PYTHONPATH'] = os.path.dirname(__file__)
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'
def runtests():
from django.conf import settings
from django.test.utils import get_runner
test_runner = get_runner(settings)()
... |
import subprocess
subprocess.Popen(['sh', '../Switches/Switch3_Off.sh']) |
"""Disk And Execution MONitor (Daemon)
Configurable daemon behaviors:
1.) The current working directory set to the "/" directory.
2.) The current file creation mode mask set to 0.
3.) Close all open files (1024).
4.) Redirect standard I/O streams to "/dev/null".
A failed call to fork() now raises an excepti... |
"""copie de fichiers sur une clé USB"""
import re # pour les expressions régulières
import os # pour les fichiers et répertoires
import os.path # pour les noms de fichiers et noms de répertoires
import copy
import shutil # pour la copie de fichiers
class copie_usb (object):
"""recopie des fichiers su... |
print("This is a python script running ...") |
import serial
import sys
def hookup(port="/dev/ttyUSB0", rate=115200, tout=0):
return serial.Serial(port=port, baudrate=rate, timeout=tout)
def getkeys():
print("type a letter: ")
return raw_input()
def flushread(con=None):
if not con:
return None
inflo = {}
if con.isOpen():
chat... |
from __future__ import print_function
import numpy as np
from csb.bio.utils import radius_of_gyration, rmsd
from .utils import kmeans
from .params import Parameters
from .features import LJPotentialFast
from .likelihood import Likelihood, KDLikelihood
from .posterior import PosteriorX, PosteriorZ, PosteriorS, Posterior... |
import pywikibot
site = pywikibot.Site('en', 'wikipedia')
import pandas as pd
import numpy as np
import seaborn as sns
import pickle
"""
select page_id, page_title, rd_title from redirect
inner join page on rd_from = page_id
where rd_namespace = 0 and rd_title LIKE '%–%'
"""
redirects_df = pd.read_csv("enwiki-redirects... |
from rest_framework.reverse import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class RollTests(APITestCase):
def test_blank_roll_endpoint(self):
"""
Ensure `GET /roll/` returns a sample roll to make.
"""
url = reverse("roll-list")
res... |
from indico.util.i18n import make_bound_gettext
_ = make_bound_gettext('vc_zoom') |
"""Import a WordPress dump."""
from __future__ import unicode_literals, print_function
import os
import re
import sys
import datetime
import io
import json
import requests
from lxml import etree
from collections import defaultdict
try:
from urlparse import urlparse
from urllib import unquote
except ImportError:... |
import collections
from typing import Dict, Tuple
import uqbar.graphs
import supriya.commands
from supriya.nonrealtime.SessionObject import SessionObject
from supriya.utils import iterate_nwise
class State(SessionObject):
"""
A non-realtime state.
"""
### CLASS VARIABLES ###
__documentation_section_... |
"""Test label RPCs.
RPCs tested are:
- getaddressesbylabel
- listaddressgroupings
- setlabel
"""
from collections import defaultdict
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
class WalletLabelsTest(BitcoinTestFramewor... |
"""Ipython parallel ready entry points for parallel execution
"""
import contextlib
import os
try:
from ipyparallel import require
except ImportError:
from IPython.parallel import require
from bcbio import heterogeneity, hla, chipseq, structural, upload, utils
from bcbio.bam import callable
from bcbio.rnaseq im... |
from __future__ import print_function
from lxml import etree as ET
from copy import deepcopy
import re
import os
import glob
from .node import Node
class RapLoader(Node):
@property
def value(self):
return self.child.text
@value.setter
def value(self, fname):
flabel = fname
if not... |
from .models import *
import django_tables2 as tables
from django_tables2.utils import A
from django.utils.translation import ugettext_lazy as _
class PortfolioTabela(tables.Table):
simbol = tables.LinkColumn('portfolioDetailed', text= lambda record: record['simbol'], args=[A('simbol')], verbose_name=_('Simbol'))
... |
import datetime
import LowVoltage.testing as _tst
from LowVoltage.actions.conversion import _convert_dict_to_db, _convert_value_to_db, _convert_db_to_dict, _convert_db_to_value
def _is_dict(d):
return isinstance(d, dict)
def _is_str(s):
return isinstance(s, basestring)
def _is_float(s):
return isinstance(s,... |
from azure.core.exceptions import HttpResponseError
import msrest.serialization
class AnswersFromTextOptions(msrest.serialization.Model):
"""The question and text record parameters to answer.
All required parameters must be populated in order to send to Azure.
:ivar question: Required. User question to quer... |
"""Tests related to the concept of certain datatypes having values with dialects."""
from unittest import TestCase
from statscraper import (BaseScraper, Dataset, Result, Dimension, DimensionValue)
class Scraper(BaseScraper):
"""A scraper with hardcoded yields."""
def _fetch_itemslist(self, item):
yield ... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "happyowlweb.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from msrest.serialization import Model
class SecurityRuleAssociations(Model):
"""All security rules associated with the network interface.
:param network_interface_association:
:type network_interface_association:
~azure.mgmt.network.v2017_03_01.models.NetworkInterfaceAssociation
:param subnet_asso... |
from django.conf.urls.defaults import *
from django.contrib import admin
from settings import UNALOG_ROOT
admin.autodiscover()
urlpatterns = patterns('',
# NOTE: don't enable this for real.
(r'^s/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': "%s/base/media" % UNALOG_ROOT}),
url(r'^a... |
from matplotlib import pyplot
import numpy
from skimage import color
class _color_space:
_LC_curve = None
@staticmethod
def HSLtoRGB(H, S, L):
"""
all input from 0 to 1
"""
# in HSV
V = L + S*numpy.minimum(L, 1-L)
S = 2*(1 - L/V)
S[V==0] = 0*S[V==0]
... |
import caesar_util
pass |
"""
Class that handles the newpost page requests
"""
import basehandler, sys
sys.path.insert(0, './models')
import post
class NewPostPage(basehandler.BaseHandler):
def get(self):
self.render('newpost.html')
def post(self):
subject, content = self.request.get('subject'), self.request.get('content')
arg... |
"""
A Unit is the very basic unit of something in a Simulation.
Unit a composite of Component instances.
Unit can represent particles of environment or unit of life.
"""
class Unit:
"""
Unit of life/environment.
Composite of Components.
"""
def __init__(self, components=None):
"""Wait for an... |
import cherrypy
import random
import string
from datetime import timedelta
from trashmail.models import Trashmail
class Root(object):
@cherrypy.expose
def index(self):
return """<!DOCTYPE html>
<html lang="fr">
<head>
<link rel="stylesheet" type="text/css" href="/static/dhtmlxslider.css"></link>
<sc... |
import argparse
import crypt
import datetime
import json
import sqlite3
import time
import os
from collections import namedtuple
from os import path
import lib.bottle as bottle
from lib.bottle import (
abort,
default_app,
hook,
request,
response,
route,
run,
static_file,
template,
)
... |
'''
This code contains methods for pulling data from NBA.com
It depends on the NBA_PY package
'''
from nba_py import *
from nba_py import team
from nba_py import game
from nba_py.constants import *
from Dunks_experiment import *
import pandas as pd
import datetime as dt
import numpy as np
import time
def create_schedul... |
from django.conf.urls import url
from . import views
app_name = 'blog'
urlpatterns = [
url(r'^$', views.BlogListView.as_view(), name='list'),
url(r'^new/$', views.BlogCreate.as_view(), name='create'),
url(r'^(?P<pk>[0-9]+)/$', views.BlogDetail.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/edit$', vie... |
import numpy as np
from epipy.lib.core.fit import fit
from epipy.ui.view import Notification
from epipy.utils import csvmanager, dateconverter
from epipy.ui.model.sidebarmodel import SideBarModel
from epipy.ui.view.sidebarwidget import SideBarWidget
from epipy.ui.view.advanceddialog import SIRAdvancedDialog, \
SEIR... |
import os
ADMINS = (
('Dave Parizek', 'dparizek@email.arizona.edu'),
('Hagan Franks', 'franks@email.arizona.edu'),
)
MANAGERS = ADMINS
SECRET_KEY = "add secret key here"
AUTHENTICATION_BACKENDS = (
'userena.backends.UserenaAuthenticationBackend',
'guardian.backends.ObjectPermissionBackend',
'announc... |
import string
alphabet = string.ascii_uppercase
class Steckerbrett:
def __init__(self, *args):
map = {}
for arg in args:
if arg[0] in map or arg[1] in map:
raise KeyError('Same letter used twice in plugboard')
map[arg[0]] = arg[1]
map[arg[1]] = arg... |
import logging
from functools import wraps
from django.db.models import Q
from celery import shared_task
from .models import PluginInstance
from .services.manager import PluginInstanceManager
logger = logging.getLogger(__name__)
def skip_if_running(f):
"""
This decorator is supposed to ensure that a task is onl... |
import binwalk.core.magic
from binwalk.core.module import Module, Option, Kwarg
class Signature(Module):
TITLE = "Signature Scan"
ORDER = 10
CLI = [
Option(short='B',
long='signature',
kwargs={'enabled': True, 'explicit_signature_scan': True},
description... |
from __future__ import unicode_literals
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth import get_user_model
from django.contrib import auth
from django.contrib import messages
from authtools import views as authviews
from braces import views as bracesviews
from django.co... |
import os, site, sys
from cx_Freeze import setup, Executable
site_dir = site.getsitepackages()[1]
include_files = []
include_files.append((os.path.join(site_dir, "shapely"), "shapely"))
include_files.append((os.path.join(site_dir, "svg"), "svg"))
include_files.append((os.path.join(site_dir, "svg/path"), "svg"))
include... |
from .flag import FlagInstruction
class ClearInstruction(FlagInstruction):
def execute(self, processor):
processor.p.flags[self.flag_name].clear() |
import climate
import joblib
import numpy as np
import sklearn.utils
import scipy.fftpack
logging = climate.get_logger('wave->spec')
def spectra(z):
'''Compute a spectrogram of the given window.'''
width = z.shape[1]
# or for power spectral density
#spec ** 2 / (width * samplerate)
return abs(scipy.... |
"""313. Super Ugly Number
https://leetcode.com/problems/super-ugly-number/
"""
import heapq
from typing import List
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
store = []
heapq.heapify(store)
heapq.heappush(store, 1)
visited = {1}
while n >... |
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import dateutil.parser
import requests
from .error import error_from_response
from .headers import Headers
from .response import Response
__all__ = ["Request"]
URLS = {
"development": "http://checkout.accepton.dev",
... |
"""
WSGI config for takeyourmeds project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTI... |
"""Implements the essense of the Simulator."""
import logging
import logging.config
from mdes.event_queue import EventQueue
from mdes.process import Process
from mdes.process_generator import ProcessGenerator
from mdes.process_queue import ProcessQueue
class SimulatorState(object):
"""A stored state for a SystemSim... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import StringField, validators
class ImageForm(FlaskForm):
image = FileField('Image')
caption = StringField('Caption', [validators.Length(min=1, max=200)])
credit = StringField('Credit', [validators.Length(min=1, max=200)]) |
"""A module that converts API exceptions to core exceptions."""
import json
import logging
import string
import StringIO
from googlecloudsdk.api_lib.util import resource as resource_util
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core.console im... |
from django.apps import AppConfig
class Ext2020Config(AppConfig):
name = 'ext2020' |
import server
def start():
startmessage = '''fredfishgames matchmaking server for unity
Licenced under the MIT licence
Make sure the configuration file has been set up before starting'''
# Start the server here!
print(startmessage)
s = server.server()
s.start()
start() |
from logparser.logparser import (CustomLog,
find_entries_with_log_level,
find_entries_with_business_id,
find_entries_with_session_id,
find_entries_within_date_range)
from logparser.perftes... |
__author__ = 'hashim'
from flask import Blueprint
authoring = Blueprint('authoring', __name__, template_folder='../templates')
import authoring_views |
'''
Created on Nov 28, 2015
@author: Thomas Adriaan Hellinger
'''
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=31, blank=False)
slug = models.SlugField()
def __unicode__(self):
return u'{0}'.format(self.name)
class Meta:
app_label = 'OASIS_Cano... |
from assembly import Assembly
forbidden_chars = ""
class Utils:
verbose = False # Is debug printing activated?
@staticmethod
def none(*args): return None
@staticmethod
def debug(*ss):
if Utils.verbose:
for s in ss: print s
@staticme... |
import os, sys
import re
filePath = sys.argv[1]
toPath = sys.argv[2]
def convertFormat(strs):
spls = strs.split('-')
tmp = spls[0]
for s in spls[1:]:
tmp += s.capitalize()
return tmp
def printCase(content):
with open(toPath,"w") as ocFile:
for line in content:
str = 'case ' + convertFormat(line[0])+'\n'
... |
import pytest
@pytest.fixture(scope="function")
def portal():
from ipc.portal import Portal
return Portal()
def test_neutralized_portal_level_is_1(portal):
assert portal.level == 1
@pytest.mark.parametrize("resonators,expected", [
([8, 7, 6, 6, 5, 5, 4, 4], 5),
([8, 7, 1, None, None, None, None, Non... |
"""
SDoc
Copyright 2016 Set Based IT Consultancy
Licence MIT
"""
class SDocError(RuntimeError):
"""
Class for errors detected or encountered by SDoc.
"""
pass |
"""
Copyright (c) 2016 Gabriel Esteban
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, publish, distribute,... |
def list_of_primes_slow(n):
if n < 2:
return []
if n == 2:
return [2]
L = [2]
def is_prime(i):
for j in L:
if (i % j) == 0:
return False
if j > i//j:
return True
return True
x = 3
while x <= n:
if is_... |
from __future__ import division
from . import base
from libqtile.log_utils import logger
try:
from pythonwifi.iwlibs import Wireless, Iwstats
def get_status(interface_name):
interface = Wireless(interface_name)
try:
stats = Iwstats(interface_name)
except IOError:
... |
from Primer import primer_10_000_000
from math import log, sqrt
print('Initializing primer...')
primer = primer_10_000_000()
print('...done')
def p(n, k, memo=None):
global primer
if memo is None:
memo = {}
if k < 1:
return 0
if (n, k) in memo:
return memo[(n, k)]
if k == 1:
... |
from django.db import models
from main.models import Show
class VolunteerShow(models.Model):
"""
Indicator of which shows volunteers should be working to process
"""
show = models.ForeignKey(Show, unique=True)
processing = models.BooleanField(default=True, help_text="Indicates that " +
... |
from sys import exit
def gold_room():
print "This room is full of gold! How much would you take?"
next = raw_input("> ")
if next.isdigit():
how_much = int(next)
else:
dead("Type a number, buster.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
... |
from __future__ import unicode_literals
import filer.fields.image
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('filer', '0002_auto_20150606_2003'),
('intern', '0011_auto_20150912_2021'),
]
operations = [
migrations.CreateModel(
... |
def modulus(n):
if type(n) == int :
return n % 2
else:
return -1 |
"""Test general pseudo-class cases."""
from .. import util
class TestPseudoClass(util.TestCase):
"""Test pseudo-classes."""
def test_pseudo_class_not_implemented(self):
"""Test pseudo-class that is not implemented."""
self.assert_raises(':not-implemented', NotImplementedError)
def test_unrec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.