src stringlengths 721 1.04M |
|---|
import sys, select # for timing out input
'''
This is the overall idea of the game's main logic:
stack = [] # last value is the top of the stack
while not gameOver:
if stack is empty:
stack = [ nextEvent() ]
# stack now has at least one element
top = stack[-1]
imminent(top) # this may ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualVmxnet3Option(vim, *args, **kwargs):
'''The VirtualVmxnet3Option data object t... |
#! /usr/bin/env python
# I found this file inside Super Mario Bros python
# written by HJ https://sourceforge.net/projects/supermariobrosp/
# the complete work is licensed under GPL3 although I can not determine# license of this file
# maybe this is the original author, we can contact him/her http://www.pygame.org/pro... |
# -*- coding: UTF-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context, RequestContext
from django.shortcuts import render_to_response
from datetime import datetime
from django.contrib.auth import authenticate, login, log... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-08-08 08:09
from __future__ import unicode_literals
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('applications', '0001_initial'),
]
operations = [
... |
# Program to spin a wheel and choose a language
# Created By Jake Huxell For Advent Of Code 2015
"""
Some notes about the program.
TODO:
1. Upkeep and bug fix as I go along
"""
# Get pygame libraries
import pygame, sys, random
from pygame.locals import *
# Generate random seed for the program - Use current time
ra... |
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, redirect, render
from django.template import RequestContext
from django.utils import simplejson
from collections import OrderedDict
from GEWB_app.models import *
# Create your views here.
def master(request):
... |
"""
Copyright (c) 2017 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 rights
to use, copy, modify, merge, publish, distribute... |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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... |
import json
from django.db import models
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from django.core.exceptions import ValidationError
from django.contrib.postgres.fields import HStoreField, ArrayField
from django.utils.translation import ugettext_lazy as _
from django.templat... |
import sys
from idl.ttypes import CommandDTO
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from idl import CenterSynRPCService
from Command import Command
from prettytable import PrettyTable
sys.path.append("./idl")
d... |
# coding: utf-8
import sys
from setuptools import setup, find_packages
install_requires = [
'Flask',
'PyYAML',
'cairocffi',
'pyparsing>=1.5.7',
'pytz',
'six',
'tzlocal',
]
if sys.version_info < (2, 7):
install_requires.append('importlib')
install_requires.append('logutils')
in... |
""" Builds up a release package ready to be built or distributed by NPM. The distributable content
is taken from the development folder to make it easier to strip out unneeded package content. """
#!/usr/bin/python
# Imports
import os
import shutil
import fnmatch
import distutils.dir_util
import cli
#
# Finds all fi... |
import numpy as np
import mj
import matplotlib.pyplot as plt
from matplotlib import cm
import sys, os
# ---------------------------------------------------------------------------------------------------
# montrer que l'algorithme de construction des lots est fiable
#
Ncandidats = 100
electeurs = np.arange(10000,1... |
from git_repo import GitRepo, MultiGitRepo
import json;
import os;
import re;
import subprocess;
import sys;
import pandas as pd
import requests
import fnmatch
from IPython.nbformat import current as nbformat
from IPython.nbconvert import PythonExporter
import networkx as nx
import compiler
from compiler.ast import Fro... |
#!/usr/bin/env python3
from os import makedirs, walk
from os.path import abspath, join, expandvars, dirname, isdir
from string import Template
import codecs
VARS = {
'FOREGROUND': 'a7a7a7',
'BACKGROUND': '1e1e1e',
'BLACK': '1e1e1e',
'BLACK2': '323537',
'RED': 'cf6a4c',
'RED2': 'cf6a4c',
'G... |
from pearce.emulator import OriginalRecipe, ExtraCrispy
from pearce.mocks import cat_dict
import numpy as np
from os import path
import tensorflow as tf
from tensorflow.python.client import device_lib
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local... |
# This library is a simple implementation of a function to convert textual
# numbers written in English into their integer representations.
#
# This code is open source according to the MIT License as follows.
#
# Copyright (c) 2008 Greg Hewgill
#
# Permission is hereby granted, free of charge, to any person obtaining ... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# Section 3: Algebraic simplification
# This code implements a simple computer algebra system, which takes in an
# expression made of nested sums and products, and simplifies it into a
# single sum of products. The goal is described in more detail in the
# problem set writeup.
# Much of this code is already implement... |
"""This file contains code for use with "Think Bayes",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import math
import thinkstats2
def RawMoment(xs, k):
return sum(x**k for x in xs) / float(len(xs))
def CentralMo... |
"""Messaging library for Python."""
from __future__ import absolute_import, unicode_literals
import os
import re
import sys
if sys.version_info < (2, 7): # pragma: no cover
raise Exception('Kombu 4.0 requires Python versions 2.7 or later.')
from collections import namedtuple # noqa
__version__ = '4.6.6'
__aut... |
from django.db import models
from readings import choices as readings_choices
class DateLocationMeasurementModel(models.Model):
"""
Abstract base class for PressureNET measurements.
"""
date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
user_id = models.CharField(max_length=255... |
import os
import asyncio
import logging
from discord import opus, ClientException
from discord.ext import commands
from discord.opus import OpusNotLoaded
from cogs.utils.music import Music
from cogs.utils.music_type import MusicType
from cogs.utils.music_player import MusicPlayer
OPUS_LIBS = ['libopus-0.x86.dll', 'lib... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import xbmcgui
import xbmc
import xbmcvfs
import time
import urllib
import urllib2
import re
import sys
import traceback
import json
from t0mm0.common.net import Net
__SITE__ = 'http://kodi.mrpiracy.xyz/'
__COOKIE_FILE__ = os.path.join(xbmc.translatePath('special:/... |
# Name:Misfortune Cookie vulnerability authentication bypass
# File:misfortune_auth_bypass.py
# Author:Ján Trenčanský
# License: GNU GPL v3
# Created: 22.9.2016
# Description: PoC based on 31C3 presentation,
# exploit based on Marcin Bury and Milad Doorbash routersploit module.
import core.Exploit
import interface.uti... |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
compat_urllib_parse,
)
class XNXXIE(InfoExtractor):
_VALID_URL = r'^https?://(?:video|www)\.xnxx\.com/video(?P<id>[0-9]+)/(.*)'
_TEST = {
'url': 'http://video.xnxx.com/vide... |
#! /usr/bin/python3
#
# Mostly copied code from find_unblocked_orphans.py in fedora
#
# Credits to original authors:
# Jesse Keating <jkeating@redhat.com>
# Till Maas <opensource@till.name>
#
# Copyright (c) 2009-2013 Red Hat
# SPDX-License-Identifier: GPL-2.0
#
# From:
# https://pagure.io/releng/blob/main/f/sc... |
from __future__ import unicode_literals
from future.builtins import int
from collections import defaultdict
from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import urlize
from mezzanine.conf import setti... |
#!/usr/bin/env python
import sys
import unittest
from ZSI import TC, ParsedSoap, ParseException, FaultFromZSIException, FaultFromException, SoapWriter
class t2TestCase(unittest.TestCase):
"Test case wrapper for old ZSI t2 test case"
def checkt2(self):
try:
ps = ParsedSoap(IN)
e... |
import os
import shutil
import pytest
from IPython.nbformat import write as write_nb
from IPython.nbformat.v4 import new_notebook
@pytest.mark.usefixtures("temp_cwd")
class BaseTestApp(object):
def _empty_notebook(self, path):
nb = new_notebook()
full_dest = os.path.join(os.getcwd(), path)
... |
#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... |
import os
import pytest
import pandas as pd
from unittest.mock import patch, ANY
from pyrestcli.exceptions import ServerErrorException
from cartoframes.auth import Credentials
from cartoframes.data.observatory.catalog.entity import CatalogList
from cartoframes.data.observatory.catalog.dataset import Dataset
from car... |
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import json
import glob
import xmltodict
import mysql.connector
# Load configurations file
configFile = open("config.xml", "r")
configDict = xmltodict.parse(configFile.read())
config = configDict["config"]["client"]["crawler"]
# Open database connection
config["connarg... |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... |
#
# Copyright (C) 2014-
# Sean Poyser (seanpoyser@gmail.com)
#
# This Program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# Thi... |
#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
import json
from django import forms
from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.widgets import Input
from django.utils.safestring import mark_safe
from django.utils.translation import to_locale, get_language, ugettext as _
from fields import ElfinderFile
from conf im... |
from __future__ import division
import sys
import copy
sys.dont_write_bytecode = True
"""
Testing LDA
"""
def test_LDA():
from LDA import LDA
x = [
[2.95, 6.63],
[2.53, 7.79],
[3.57, 5.65],
[3.16, 5.47],
[2.58, 4.46],
[2.16, 6.22],
[3.27, 3.52]
]
... |
###############################################################################
##
## Copyright (C) 2014-2015, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... |
#! /usr/bin/python
# -*- coding: utf8 -*-
# Copyright 2009 Gabriel Sean Farrell
# Copyright 2008 Mark A. Matienzo
#
# This file is part of Kochief.
#
# Kochief is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation,... |
# Standard imports
from matplotlib import pyplot as pl
import numpy as np
from scipy import integrate
# 3rd party imports
# local imports
tmax = 10
tstep = 0.001
# 0.5 V --> 0.25 J
# 2.0 V --> 4.0 J
V0 = 27
R = 0.300
# 0.5 C --> 0.5 J
# 2.0 C --> 2.0 J
N = 1
C0 = 2*4.5 #1.e-6*(3*2200 + 3*1800 + 3*1500 + 3*1500 +... |
"""
Window showing a Trac Ticket
"""
##############################################################################
# SageUI: A graphical user interface to Sage, Trac, and Git.
# Copyright (C) 2013 Volker Braun <vbraun.name@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it u... |
"""Parser of a Solr schema.xml"""
from alm.solrindex.interfaces import ISolrField
from alm.solrindex.interfaces import ISolrFieldHandler
from alm.solrindex.interfaces import ISolrSchema
from elementtree.ElementTree import parse
from zope.component import getUtility
from zope.component import queryUtility
from zope.in... |
# Copyright (c) 2004 Python Software Foundation.
# All rights reserved.
# Written by Eric Price <eprice at tjhsst.edu>
# and Facundo Batista <facundo at taniquetil.com.ar>
# and Raymond Hettinger <python at rcn.com>
# and Aahz <aahz at pobox.com>
# and Tim Peters
# This module is currently Py2.3 ... |
"""
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
class Solution(object):
def t... |
import inspect
import gc
import sys
import os.path
import difflib
from collections import OrderedDict
import pandas as pd
from pandas.core.common import in_ipnb
def is_property(code):
"""
Using some CPython gc magics, check if a code object is a property
gc idea taken from trace.py from stdlib
"""
... |
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits as pyfits
import glob
from astropy.stats.funcs import median_absolute_deviation as MAD
from scipy.ndimage import label
from photo_test import raw_moment, intertial_axis, plot_bars
from kepf... |
#!/usr/bin/env python
import json
import os
import sys
from argparse import ArgumentParser
from enum import IntEnum
from hearthstone.cardxml import load
from hearthstone.enums import CardType, Faction, GameTag, Locale
from hearthstone.utils import SCHEME_CARDS, SPELLSTONE_STRINGS
NBSP = "\u00A0"
MECHANICS_TAGS = [
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorlayer as tl
from tests.utils import CustomTestCase
class Layer_Merge_Test(CustomTestCase):
@classmethod
def setUpClass(cls):
cls.data = dict()
... |
# ===============================================================================
# Copyright 2011 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licens... |
# Copyright 2020 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
class Transform(object):
"""Class for representing affine transformations"""
def __init__(self, data):
self.data = data
@staticmethod
def unit():
"""Get a new unit tranformation"""
return Transform([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
@staticmethod
def move(dx, dy):
... |
from lib import bin_search_right, snd
def search(arr):
"""
Given a list of tasks, represented as tuple of starting time, finishing time, and profit (non-negative). Returns
the maximum profit achievable by choosing non-conflicting tasks.
Solution is binary search on tasks sorted by finishing time.
... |
class Device(object):
def __init__(self, client, device_id):
self.client = client
self.device_id = device_id
def set_zone(self, zone_id, state):
"""
set_zone(zone_id, state)
Turn on or off a zone. When specifing a zone, keep in
mind they are zero based, so ... |
import argparse
import locale
import sys
from deepl import translator
def print_results(result, extra_data, verbose=False):
if verbose:
print("Translated from {} to {}".format(extra_data["source"], extra_data["target"]))
print(result)
def main():
parser = argparse.ArgumentParser(description="Tr... |
"""
Views for Discussion Forum
Keeping activity for add operations only. Can be extended easily if required
TODO
- introduce user specific variable "follow" for thread
Whether user is following thread or not ?
- introduce 'liked', variable for Thread/Comment/Reply
- handle anonymity while serializ... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
""" Implementation of "INVENTORY VALUATION TESTS (With valuation layers)" spreadsheet. """
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
from odoo.tests import Form, tagged
from... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import progressbar
from neupy.utils import iters
__all__ = ('ProgressbarSignal', 'PrintLastErrorSignal', 'EpochEndSignal',
'ErrorCollector')
def format_time(time):
"""
Format seconds into human readable format.
Pa... |
#!/usr/bin/env python2.7
# -*- mode: python; coding: utf-8; -*-
##################################################################
# Documentation
"""Module defining methods common to many modules.
Attributes:
_ispunct (method): check if word consists only of punctuation characters
prune_punc (method): remove tok... |
from api.decorators import api_view, request_data
from api.vm.qga.api_views import VmQGA
__all__ = ('vm_qga',)
#: vm_status: PUT: running, stopping
@api_view(('PUT',))
@request_data() # get_vm() = IsVmOwner
def vm_qga(request, hostname_or_uuid, command, data=None):
"""
Run (:http:put:`PUT </vm/(hostname_or... |
import ujson
from configman import ConfigurationManager
from configman.dotdict import DotDict
from mock import Mock, patch
from socorro.lib.transform_rules import TransformRuleSystem
from socorro.processor.processor_2015 import (
Processor2015,
rule_sets_from_string
)
from socorro.processor.general_transform_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Phamda documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 19 12:46:42 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# aut... |
# Copyright 2015-2017 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
"""
The unit tests in this module test the internal behaviour of the Pywr-Hydra application.
"""
from hydra_pywr.importer import PywrHydraImporter
import pytest
import json
@pytest.fixture()
def pywr_nodes_edges():
""" Example node and edge data from Pywr.
This data looks like "nodes" and "edges" section of... |
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# -*- coding: utf-8 -*-
""" Sahana Eden Project Model
@copyright: 2011-2012 (c) Sahana Software Foundation
@license: MIT
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 witho... |
'''
This file is part of uvscada
Licensed under 2 clause BSD license, see COPYING for details
'''
import os
from temp_file import ManagedTempFile
from util import print_debug
class Execute:
@staticmethod
def simple(cmd, working_dir = None):
'''Returns rc of process, no output'''
print_debug('cmd in: %s' % cm... |
# Copyright 2014 - Savoir-Faire Linux inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, ... |
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from chroma_core.models.storage_plugin import StorageResourceAttributeSerialized
class BaseResourceAttribute(object):
"""Base class for declared attributes of Base... |
from binascii import hexlify, unhexlify
from datetime import datetime
from hashlib import sha256
from operator import attrgetter
import argparse
import functools
import inspect
import io
import os
import shlex
import signal
import stat
import sys
import textwrap
import traceback
from . import __version__
from .helpers... |
# -*- encoding: utf-8 -*-
import json
from flask import Blueprint
from flask import current_app
from flask import make_response
from flask import request
from flask import render_template
from flask import url_for
from discograph import exceptions
from discograph import helpers
blueprint = Blueprint('ui', __name__, ... |
from ..schemas import Schema, fields
from ..utils import FrozenMixin
from ..enums import (EnumField, CustomerTypeEnum, CurrencyEnum,
ResidenceStatusEnum)
class IdentificationSchema(Schema):
Ssn = fields.String()
BirthDate = fields.Date()
CustomerRegistrationDate = fields.Date()
In... |
'''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... |
import settingsManager
import pygame
import xml.etree.ElementTree as ElementTree
import xml.dom.minidom
import os
import engine.baseActions as baseActions
import engine.collisionBox as collisionBox
import weakref
import engine.hurtbox as hurtbox
import math
import numpy
import spriteManager
import engine.ar... |
from cno.io.mapback import MapBack
from cno import CNOGraph, cnodata
def test_mapback():
# init
pknmodel = CNOGraph(cnodata("PKN-ToyMMB.sif"), cnodata("MD-ToyMMB.csv"))
model = CNOGraph(cnodata("PKN-ToyMMB.sif"), cnodata("MD-ToyMMB.csv"))
model.preprocessing()
mp = MapBack(pknmodel, model)
... |
"""This module provides an API to validate and to some extent
manipulate data structures, such as JSON and XML parsing results.
Example usage:
>>> validate(int, 5)
5
>>> validate({text: int}, {'foo': '1'})
ValueError: Type of '1' should be 'int' but is 'str'
>>> validate({'foo': transform(int)... |
"""
Django settings for haveaniceday project.
Generated by 'django-admin startproject' using Django 1.9.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
# Build... |
# Copyright (C) 2006-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library ... |
# Copyright (c) 2012 - 2015 EMC Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
from typing import Mapping, Union, Sequence
from twisted.names.error import ResolverError
from twisted.python.failure import Failure
from dnsagent.resolver.cn import CnResolver
from dnsagent.resolver.parallel import PoliciedParallelResolver, BaseParalledResolverPolicy
__all__ = ('DualResolver',)
class PolicyError... |
"""
This files offers a recommendation system based on collaborative filtering technique.
1) Let U be the user we want to give recommendations to, for each user U2 != U we need to compute distance(U, U2) (*)
and get the top K neighbors. These neighbors should have watched a lot of animes also watched by U,
giv... |
#!/usr/bin/env python
'''Script that manages motion sensor, camera module and light
When motion is detected, turn on infrared light, take and save picture, turn off light
Maximum of one picture every 4 seconds'''
from gpiozero import MotionSensor
import subprocess
from datetime import datetime
from time import sl... |
from contextlib import contextmanager
import inspect
import json
import vcr
def json_query_matcher(r1, r2):
"""
Match two queries by decoding json-encoded query args and comparing them
"""
if len(r1.query) != len(r2.query):
return False
for i,q in enumerate(r1.query):
if q[0] !=... |
# Copyright (c) 2014, 2015 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice... |
#-*- coding: utf-8 -*-
#
# This file belongs to Gyrid.
#
# Gyrid is a mobile device scanner.
# Copyright (C) 2013 Roel Huybrechts
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versio... |
# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Integration tests for loading and saving netcdf files."""
# Import iris.tests first so that some things can be initialised ... |
"""Module containing class `WaveAudioFileType`."""
import os.path
import wave
import numpy as np
from vesper.signal.audio_file_reader import AudioFileReader
from vesper.signal.unsupported_audio_file_error import UnsupportedAudioFileError
'''
audio_file_utils:
read_audio_file(file_path)
write_audio_file(fi... |
import pytest
fixture = pytest.fixture
@fixture
def bed(request):
from google.appengine.ext import testbed
bed = testbed.Testbed()
bed.activate()
request.addfinalizer(lambda: teardown_bed(bed))
return bed
def teardown_bed(bed):
bed.deactivate()
@fixture
def mailer(bed):
from google.appe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-26 14:15
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('multiboards', '0004_auto_20170526_1615'),... |
#Задача №9, Вариант 7
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать.
#Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо
#буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен
#попробо... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
from toee import *
import race_defs
###################################################
def GetCategory():
return "Core 3.5 Ed Classes"
print "Registering race: Troll"
raceEnum = race_troll
raceSpec = race_defs.RaceSpec()
raceSpec.modifier_name = "Troll" # Python modifier to be applied
raceSpec... |
# -*- coing: utf-8 -*-
class UnionFind(object):
def __init__(self, N):
self.roots = [0] * N
for i in range(N):
self.roots[i] = i
def find_roots(self, i):
root = i
while root != self.roots[root]:
root = self.roots[root]
# 路径压缩, 用于提升速度, TODO: 补充一个pa... |
from fabric.api import env, task, run, local, require, cd
from gitric.api import ( # noqa
git_seed, git_reset, git_init, git_head_rev, allow_dirty, force_push
)
from fabvenv import virtualenv, make_virtualenv
env.use_ssh_config = True
@task
def prod():
'''an example production deployment'''
env.hosts = ... |
#!/usr/bin/env python
############################################################################
#
# Copyright (C) 2014 PX4 Development Team. All rights reserved.
# Author: Julian Oes <joes@student.ethz.ch>
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provide... |
"""
Contains imports of forms from django and captha and our custom models.
Has logic for form validation as well.
"""
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.extras.widgets import SelectDateWidget
from captcha.fields... |
#!/usr/bin/env python
from nose.tools import assert_raises
from dependencybuilder.dependencybuilder import DependencyBuilder
from dependencybuilder.dependencybuilderexceptions import *
__author__ = 'James Johnson'
__version__= '1.0.0'
test_dependencey_builder = DependencyBuilder()
def test_init():
local_depende... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.