code stringlengths 1 199k |
|---|
import logging as log
class Singleton:
def __init__(self, decrated):
log.debug("Singleton Init %s" % decrated)
self._decorated = decrated
def getInstance(self):
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
... |
from __future__ import unicode_literals
import datetime
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import models
from django.forms import (
CharField, FileField, Form, ModelChoiceField, ModelForm,
)
from django.forms.models import ModelFormMetaclass
from django.test import SimpleTe... |
from waflib import Task, Runner
Task.CANCELED = 4
def cancel_next(self, tsk):
if not isinstance(tsk, Task.TaskBase):
return
if tsk.hasrun >= Task.SKIPPED:
# normal execution, no need to do anything here
return
try:
canceled_tasks, canceled_nodes = self.canceled_tasks, self.canceled_nodes
except AttributeErr... |
from vtk import *
database = vtkSQLDatabase.CreateFromURL("psql://bnwylie@tlp-ds.sandia.gov:5432/sunburst")
database.Open("")
vertex_query_string = """
select d.ip, d.name, i.country_name,i.region_name,i.city_name,i.latitude, i.longitude
from dnsnames d, ipligence i where ip4(d.ip)<<= ip_range;
"""
edge_query_string =... |
from setuptools import setup, Extension
from os.path import join as pjoin
from os.path import dirname
def read(fname):
return open(pjoin(dirname(__file__), fname)).read()
setup(
name='ortools_examples',
version='1.VVVV',
install_requires = ['ortools'],
license='Apache 2.0',
author = 'Google Inc'... |
import os
from eventlet.green import subprocess
from eventlet import greenthread
from oslo_log import log as logging
from neutron.common import utils
LOG = logging.getLogger(__name__)
def create_process(cmd, addl_env=None):
cmd = map(str, cmd)
LOG.debug("Running command: %s", cmd)
env = os.environ.copy()
... |
from m5.params import *
from m5.SimObject import SimObject
class BasicLink(SimObject):
type = 'BasicLink'
link_id = Param.Int("ID in relation to other links")
latency = Param.Int(1, "latency")
# The following banwidth factor does not translate to the same value for
# both the simple and Garnet model... |
print '3. Operations'
print 'XXX Mostly not yet implemented'
print '3.1 Dictionary lookups fail if __cmp__() raises an exception'
class BadDictKey:
def __hash__(self):
return hash(self.__class__)
def __cmp__(self, other):
if isinstance(other, self.__class__):
print "raising error"
... |
from contextlib import contextmanager
from django.core.exceptions import FieldDoesNotExist, FieldError
from django.db.models.query_utils import InvalidQuery
from django.test import SimpleTestCase
from django.utils.deprecation import RemovedInDjango40Warning
class InvalidQueryTests(SimpleTestCase):
@contextmanager
... |
import datetime
import pickle
from decimal import Decimal
from operator import attrgetter
from unittest import mock
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import FieldError
from django.db import connection
from django.db.models import (
Avg, Case, Count, DecimalField,... |
from m5.SimObject import SimObject
from m5.params import *
class PowerTLB(SimObject):
type = 'PowerTLB'
cxx_class = 'PowerISA::TLB'
size = Param.Int(64, "TLB size") |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_log_syslogd3_filter
except ImportError:
... |
import vtk
sphere = vtk.vtkSphereSource()
sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereMapper.GlobalImmediateModeRenderingOn()
sphereActor = vtk.vtkLODActor()
sphereActor.SetMapper(sphereMapper)
textActor = vtk.vtkTextActor()
textActor.SetTextScaleModeToProp()
tex... |
"""Operations for generating and loading vocab remappings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.contrib.framework.python.ops import gen_checkpoint_ops
from tensorflow.contrib.util import loader
from tensorflow.python.... |
import json
import unittest
from telemetry.core.platform.power_monitor import monsoon_power_monitor
class MonsoonPowerMonitorTest(unittest.TestCase):
def testEnergyComsumption(self):
data = {
'duration_s': 3600.0,
'samples': [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0)]
}
results = mons... |
"""
pygments.regexopt
~~~~~~~~~~~~~~~~~
An algorithm that generates optimized regexes for matching long lists of
literal strings.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from re import escape
from os.path import com... |
from openerp import models, fields, api, exceptions, _
class AccountMove(models.Model):
_inherit = 'account.move'
locked = fields.Boolean('Locked', readonly=True)
@api.multi
def write(self, vals):
for move in self:
if move.locked:
raise exceptions.Warning(_('Move Lock... |
import datetime
import json
import os
import os.path
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urllib
import urllib2
import yaml
from collections import defaultdict
from distutils.version import LooseVersion
from jinja2 import Environment
from optparse import OptionParser
import a... |
from warnings import warnpy3k
warnpy3k("the cdplayer module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
cdplayerrc = '.cdplayerrc'
class Cdplayer:
def __init__(self, tracklist):
import string
self.artist = ''
self.title = ''
if type(tracklist) == type(''):
... |
from django.contrib.gis import views as gis_views
from django.contrib.gis.sitemaps import views as gis_sitemap_views
from django.contrib.sitemaps import views as sitemap_views
from django.urls import path
from .feeds import feed_dict
from .sitemaps import sitemaps
urlpatterns = [
path('feeds/<path:url>/', gis_views... |
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):
# Removing unique constraint on 'Release', fields ['project', 'version', 'environment']
db.delete_un... |
DOCUMENTATION = '''
---
module: ec2_vpc_nat_gateway
short_description: Manage AWS VPC NAT Gateways.
description:
- Ensure the state of AWS VPC NAT Gateways based on their id, allocation and subnet ids.
version_added: "2.2"
requirements: [boto3, botocore]
options:
state:
description:
- Ensure NAT Gateway i... |
import os, unittest
import sqlite3 as sqlite
class CollationTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def CheckCreateCollationNotCallable(self):
con = sqlite.connect(":memory:")
try:
con.create_collation("X", 42)
self.fai... |
from gnuradio import gr, filter
from fm_emph import fm_deemph
from math import pi
try:
from gnuradio import analog
except ImportError:
import analog_swig as analog
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates... |
import unittest
import collections
class BasicTestMappingProtocol(unittest.TestCase):
# This base class can be used to check that an object conforms to the
# mapping protocol
# Functions that can be useful to override to adapt to dictionary
# semantics
type2test = None # which class is being tested ... |
DOCUMENTATION = u'''
---
module: bzr
author: "André Paramés (@andreparames)"
version_added: "1.1"
short_description: Deploy software (or files) from bzr branches
description:
- Manage I(bzr) branches to deploy files or software.
options:
name:
required: true
aliases: [ 'parent' ]
descrip... |
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Point Of Sale',
'sequence': 6,
'summary': 'Touchscreen Interface for Shops',
'description': """
Quick and Easy sale process
===========================
This module allows you to manage your shop sales very easily with a fully web based ... |
{
'name': 'Accounting Consistency Tests',
'version': '1.0',
'author': 'OpenERP',
'category': 'Accounting & Finance',
'website': 'https://www.odoo.com/page/accounting',
'description': """
Asserts on accounting.
======================
With this module you can manually check consistencies and incon... |
import os
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
EC2_ACCESS_ID = 'your access id'
EC2_SECRET_KEY = 'your secret key'
Driver = get_driver(Provider.EC2)
conn = Driver(EC2_ACCESS_ID, EC2_SECRET_KEY)
key_file_path = os.path.expanduser('~/.ssh/id_rsa_my_key_pair_1.pub')... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = '''
---
module: nios_dns_view
version_added: "2.5"
author: "Peter Sprygada (@pr... |
from unittest import mock
from urllib.parse import urlencode
from django.contrib.sitemaps import (
SitemapNotFound, _get_sitemap_full_url, ping_google,
)
from django.core.exceptions import ImproperlyConfigured
from django.test import modify_settings, override_settings
from .base import SitemapTestsBase
class PingGo... |
from twisted.application.service import ServiceMaker
TwistedNews = ServiceMaker(
"Twisted News",
"twisted.news.tap",
"A news server.",
"news") |
"""distutils.mwerkscompiler
Contains MWerksCompiler, an implementation of the abstract CCompiler class
for MetroWerks CodeWarrior on the Macintosh. Needs work to support CW on
Windows."""
__revision__ = "$Id: mwerkscompiler.py 37828 2004-11-10 22:23:15Z loewis $"
import sys, os, string
from types import *
from distutil... |
"""A collection of modules for iterating through different kinds of
tree, generating tokens identical to those produced by the tokenizer
module.
To create a tree walker for a new type of tree, you need to do
implement a tree walker object (called TreeWalker by convention) that
implements a 'serialize' method taking a t... |
import frappe
import unittest
test_records = frappe.get_test_records('Operation')
class TestOperation(unittest.TestCase):
pass |
import java
import sys
DEBUG = 'debug'
INFO = 'info'
WARN = 'warn'
ERROR = 'error'
FATAL = 'fatal'
levels_dict = {}
ix = 0
for level in [DEBUG, INFO, WARN, ERROR, FATAL, ]:
levels_dict[level]=ix
ix += 1
class modjy_logger:
def __init__(self, context):
self.log_ctx = context
self.format_str =... |
from __future__ import absolute_import
from datetime import datetime
from django.test import TestCase
from django.utils import six
from .models import Reporter, Article, Writer
class M2MIntermediaryTests(TestCase):
def test_intermeiary(self):
r1 = Reporter.objects.create(first_name="John", last_name="Smith"... |
'''SSL with SNI_-support for Python 2. Follow these instructions if you would
like to verify SSL certificates in Python 2. Note, the default libraries do
*not* do certificate checking; you need to do additional work to validate
certificates yourself.
This needs the following packages installed:
* pyOpenSSL (tested with... |
__author__ = "Panagiotis H.M. Issaris"
__email__ = "takis@issaris.org"
__version__ = "0.1.1"
from wkhtmltopdf import htmltopdf |
from django.conf import settings
from django.db import connection
from django.utils.translation import ugettext as _
from modoboa.lib.exceptions import InternalError
def db_table_exists(table):
"""Check if table exists."""
return table in connection.introspection.table_names()
def db_type(cname="default"):
... |
from peewee import OP, Database, ImproperlyConfigured, QueryCompiler, logger
from pydrill_dsl.result import DrillQueryResultWrapper
try:
from pydrill.client import PyDrill
PYDRILL_AVAILABLE = True
except ImportError:
PYDRILL_AVAILABLE = False
try:
import pyodbc
PYODBC_AVAILABLE = True
except ImportE... |
ACTION_PAY = 'pay'
ACTION_HOLD = 'hold'
ACTION_SUBSCRIBE = 'subscribe'
ACTION_PAYDONATE = 'paydonate'
ACTION_AUTH = 'auth'
ACTIONS = (
(ACTION_PAY, ACTION_PAY),
(ACTION_HOLD, ACTION_HOLD),
(ACTION_SUBSCRIBE, ACTION_SUBSCRIBE),
(ACTION_PAYDONATE, ACTION_PAYDONATE),
(ACTION_AUTH, ACTION_AUTH),
)
CURRE... |
import time
import pprint
from testify import *
from dynochemy import db, Table, DynamoDBError
class TestDB(db.BaseDB):
def __init__(self):
super(TestDB, self).__init__()
self.allow_sync = True
self.ioloop = None
self.client = turtle.Turtle()
class SimpleTest(TestCase):
def test(... |
from sqlalchemy import and_
from sqlalchemy import asc
from sqlalchemy import desc
from sqlalchemy import exc as sa_exc
from sqlalchemy import exists
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import literal_column
from sqlalchemy import select
from sqla... |
"""
friendica.py
A python 3 module to access the Friendica API.
See https://github.com/friendica/friendica/wiki/Friendica-API for the
documentation of the friendica API.
Author: Tobias Diekershoff
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provide... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='TermsOfService',
fields=[
('id', models.AutoField(verbose_name='ID', seriali... |
ROUND_TIME = 120
TECH_COST = {
1: 50,
2: 150,
3: 400
}
TECH_POINTS_PLANET_MULTIPLIER = 3
TECH_POINTS_SYSTEM_MULTIPLIER = 0.2
UPGRADE_BONUS = {
'offensive': 0.05,
'defensive': 0.05,
'economic': 0.05
}
DESTROY_CHANCE = {
'attacker': 0.6,
'defender': 0.7
}
STATS_TEMPLATE = {
'techGained': {},
'techSpent': {},
'... |
from sqlalchemy.testing import eq_
import datetime
from sqlalchemy import *
from sqlalchemy.sql import table, column
from sqlalchemy import sql, util
from sqlalchemy.sql.compiler import BIND_TEMPLATES
from sqlalchemy.testing.engines import all_dialects
from sqlalchemy import types as sqltypes
from sqlalchemy.sql import... |
import os
import tempfile
import unittest
from . import utils
class LogTests(unittest.TestCase):
def setUp(self):
__, self.logpath = tempfile.mkstemp()
def tearDown(self):
os.remove(self.logpath)
def test_bootstrap(self):
self.log, __ = utils.bootstrap(self.logpath)
with open... |
__author__ = 'hvishwanath'
from setuptools import setup
import sys, os
import platform
install_requires = [
"PyYAML==3.11",
"click==4.0",
"peewee==2.5.1",
"requests==2.6.0",
"sh==1.11",
]
kwargs = {}
if sys.version_info[0] >= 3:
from setuptools import setup
kwargs['use_2to3'] = True
classifi... |
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Sortable Challenge 2016'
copyright = u'2016, Albert Heinle'
version = '0.1'
release = '0.1'
exclude... |
class addition(object):
def __init__(self, left, right):
self.left = left
self.right = right
class subtract(object):
def __init__(self, left, right):
self.left = left
self.right = right
class product(object):
def __init__(self, left, right):
self.left = left
s... |
import gpiozero
import time
from datetime import datetime
from curses import wrapper
def now():
return datetime.now().time().strftime('%H:%M:%S:%f')
class robo_car:
def __init__(self):
self.valid_go = ('stop', 'forward', 'backward',
'rotate_left', 'rotate_right',
... |
import sys
from pathlib import Path
import yaml
import tqdm # type: ignore
from multiprocessing import Pool
"""
Script for collecting information about VASP calculations into YAML format, for further processing.
Expects a series of directories (listed in `result_dirs`) that each contain:
vasprun.xml
vaspmeta.y... |
from flask_wtf import Form
from wtforms import SubmitField, SelectField, TextAreaField, BooleanField
from wtforms.validators import Required
class ReportForm(Form):
course = SelectField('Course', validators=[Required()],
choices=[('atoc185x', 'ATOC185x'),
('atoc185x... |
import json
from django.shortcuts import render, get_object_or_404
from django.conf import settings
from kobo.django.views.generic import DetailView, SearchView
from rest_framework import viewsets, mixins, status
from rest_framework.response import Response
from . import filters
from . import signals
from . import mode... |
def fib(n):
if n==1 or n==0:
return 1
return fib(n-2) + fib(n-1)
def memoize(f):
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf
fib = memoize(fib)
print fib(969) |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import sru
class StackedBRNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers,
dropout_rate=0, dropout_output=False, rnn_type=nn.LSTM,
concat_layers=False, paddi... |
class DiseaseError(Exception):
"Base class for disease module exceptions."
pass
class ParserError(DiseaseError): pass |
import os
import subprocess
import time
import pytest
@pytest.fixture(scope='session')
def h2o(request):
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(base_dir)
proc = subprocess.Popen(
['./h2o/h2o-2.0.0/h2o', '-c', './h2o.conf'], shell=True,
stdout=subproce... |
import sys, os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'FPO'
copyright = u'2012, Ryan Quigley, Jonathan Chu'
version = '0.1'
release = '0.1.0'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
html... |
from lyrica import lyrica
import os
port = int(os.environ.get('PORT', 5000))
lyrica.run(host='0.0.0.0', port=port, debug=True) |
from pygame import image, rect
from config import *
class Tileset:
#---------------------------------------------------------------------------
# Method: __init__
#
# Description: Loads an image file and extracts tile surfaces from it.
#
# Inputs: filename - Name of an image file.
... |
from cb2_send import * |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangocms_googlecalendar', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='googlecalendar',
name='title',
... |
"""
Baseline SNLI model
Inspired by https://github.com/Smerity/keras_snli
TODO: Refactor SNLI baseline so that it takes embedded words (this will factor out dict lookup kwargs nicely)
TODO: Add bn before LSTM
TODO: Recurrent dropout
TODO: Pass translate intelligently
TODO: Debug simlex?
"""
import theano
import theano.... |
"""
This script is currently quite experimental, and requires editing to use for each organism. If
you can't see what to edit in the code you probably shouldn't be trying it.
Your input is a GFF3 file containing gene models.
"""
import argparse
import math
import random
from biocode import gff
def main():
parser =... |
"""
pyvisa.visa
~~~~~~~~~~~
Module to provide an import shortcut for the most common VISA operations.
This file is part of PyVISA.
:copyright: 2014 by PyVISA Authors, see AUTHORS for more details.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals,... |
import webcache
import os
CACHE_DIRECTORY = os.path.join(os.path.abspath((webcache.__path__)[0]), 'cache')
DEFAULT_THROTTLE_DELAY = 5 # can also be a tuple range
COMPRESSION = False
EXPIRES = False # ex. 60 * 60 * 24 * 7 = 1 week
OVERWRITE = F... |
"""
Automatically package and test a Python project against configurable
Python2 and Python3 based virtual environments. Environments are
setup by using virtualenv. Configuration is generally done through an
INI-style "tox.ini" file.
"""
from __future__ import with_statement
import tox_plus
import py
import os
import s... |
import sublime, sublime_plugin, os.path
_schemeEditor = None
_skipOne = 0
_wasSingleLayout = None
_lastScope = None
_lastScopeIndex = 0
def find_matches ( scope, founds ):
global _schemeEditor
ret = []
maxscore = 0
# find the scope in the xml that matches the most
for found in founds:
foundstr = _schemeEditor.su... |
import sys, os
import subprocess
import os.path
from Overc.utils import Process
from Overc.utils import CONTAINER_MOUNT
from Overc.utils import ROOTMOUNT
CONTAINER_SCRIPT_PATH = "/etc/overc/container/"
class Container(object):
def __init__(self):
pass
def activate(self, name, template, force_create):
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("pos", "0009_auto_20180328_1051")]
operations = [
migrations.RemoveField(model_name="colour", name="outline_colour"),
migrations.RemoveField(model_name="item", name="b... |
import time
from collections import deque
from flask import current_app
request_stats = deque()
def add_request():
ts_now = int(time.time())
# 只记录app.config['REQUEST_STATS_WINDOW']秒内的请求
while len(request_stats) > 0 and request_stats[0] < (ts_now - current_app.config['REQUEST_STATS_WINDOW']):
request... |
'''
Test
'''
from torcms.handlers.reply_handler import ReplyHandler
def test_b():
urls = [
("/label/(.*)", ReplyHandler, {}),
]
assert urls |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hosted in a Docker container!"
if __name__ == '__main__':
app.run(port=80) |
"""
Models in this application, Task and Todo,
see theirs docs for help.
"""
import json
import requests
class Task(object):
"""
A task looks like::
- [x] Go shopping
Use '[x]' to mark a task done.
attributes
content str (required)
done bool (optional, default: ... |
import pyinotify as pyinotify
from nekumo.api.base import NekumoNodeEvent, API
from nekumo.utils.filesystem import path_split_unix
class EventHandler(pyinotify.ProcessEvent):
def __init__(self, nekumo, directory):
super().__init__()
self.nekumo = nekumo
self.directory = directory
def pro... |
import numpy as np
import re
import itertools
from collections import Counter
"""
Original taken from https://github.com/dennybritz/cnn-text-classification-tf
"""
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sente... |
import sys
import os
import socket
import fcntl
import struct
import subprocess
import psutil
from psutil._compat import print_
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ''
try:
addr = socket.inet_ntoa(fcntl.ioctl(s.fileno(),
... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class BaseConfig:
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_RECORD_QUERIES = False
MARSHMALLOW_STRICT = True
MARSHMALLOW_DATEFORMAT = 'rfc'
SECRET_KEY = 'test_key'
SECURITY_LOGIN_SALT = 'test'
SECURITY_PASSWORD_HASH = 'pbkd... |
import logging
import os
import re
import shlex
import shutil
import stat
import sys
from pathlib import Path
from pprint import pformat
import pytest
from pyscaffold import shell
from .helpers import uniqstr
def test_ShellCommand(tmpfolder):
echo = shell.ShellCommand("echo")
output = echo("Hello Echo!!!")
... |
import numpy
def make_g_matrix(hmatrix, content_bits_number):
submatrix_to_transpose = hmatrix[:,0:content_bits_number]
l = numpy.transpose(submatrix_to_transpose)
return numpy.concatenate([l, numpy.eye(content_bits_number)], axis=1)
def make_binary_vector(i, data_length):
result = [int(a) for a in bin(... |
import _plotly_utils.basevalidators
class LocationssrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="locationssrc", parent_name="choropleth", **kwargs):
super(LocationssrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... |
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
else:
while n > 1 and n % 2 == 0:
n /= 2
if n == 1:
return True
else:
return False
a = Solution()
print a.isPowerOfThre... |
from django.contrib import admin
from membership.models import MembershipType, Membership
admin.site.register(MembershipType)
admin.site.register(Membership) |
from collections import OrderedDict
expected = OrderedDict(
[
(
"generated",
[
OrderedDict(
[
("id", u"dataset1"),
("date", u"2018"),
(
"authors",
... |
from warnings import warn
from .. import VARIABLES
class CustomDict(dict):
def __init__(self, args, required=set(), optional=set(), required_or=[]):
passed_keywords = set(args.keys())
missing = required - passed_keywords
if missing:
raise TypeError('The following required argumen... |
import re, os, sys
from lxml import etree
import robotparser #for check a wbe page can be fetched or not
from urlparse import urljoin #for combine the link
import urllib, urllib2, httplib, socket
from urllib2 import urlopen,Request
import urlparse
import datetime, time
from collections import OrderedDict
import json
re... |
"""Account family test constants."""
FIRST_NAME = "Quentin"
LAST_NAME = "TARANTINO"
FULL_NAME = FIRST_NAME + " " + LAST_NAME
PERSON_ID = (FIRST_NAME + LAST_NAME).lower()
PRIMARY_EMAIL = PERSON_ID + "@hotmail.fr"
APPLE_ID_EMAIL = PERSON_ID + "@me.com"
ICLOUD_ID_EMAIL = PERSON_ID + "@icloud.com"
MEMBER_1_FIRST_NAME = "Jo... |
import socket
host = '127.0.0.1'
port = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hello World')
data = s.recv(1024)
s.close()
print 'Received',repr(data) |
from jinja2 import Template, Environment
import requests
from json import dumps
from good import Schema, Optional
from glue import p
template_schema = Schema({ # TODO: not just a string, but valid Jinja template!
'url' : str,
'type' : str,
Optional('data') : str
})
env = Environment()
env.filters['json'] = ... |
from __future__ import absolute_import
import os
import djcelery
from datetime import timedelta
djcelery.setup_loader()
BROKER_URL = os.environ.get('RABBITMQ_HOST', "amqp://guest@localhost//")
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBack... |
version = '1.1.1' |
import FingerPrinter
import sys
import os
import urllib.request
import requests
versionData = "https://launchermeta.mojang.com/mc/game/version_manifest.json"
def getVersionURL(version):
data = requests.get(versionData).json()
versions = data["versions"]
for x in versions:
if x["id"] == version:
... |
from urllib import request
url = "http://bit.ly/GoogleScholar"
webpage = request.urlopen(url)
code = webpage.getcode()
info = webpage.info()
headers = info
new_url = webpage.geturl()
print(url, "redirected to", new_url) |
from six.moves import cPickle
import gzip
def writePickleZip (outputFile, data, log=None) :
'''Utility to write a pickle to disk.
NOTE: This first attempts to use protocol 2 for greater portability
across python versions. If that fails it, and we're using py3,
we attempt again with... |
import boto3
import datetime
import json
kinesis = boto3.client("kinesis")
payload = {
"network": "array_of_things_chicago",
"meta_id": 0,
"node_id": "0000001e0610ba72",
"sensor": "tmp421",
"data": {"temperature": 10.0},
"datetime": str(datetime.da... |
import os,errno
valid_folder="C:/Validation"
for root, dirs, files in os.walk("./Image_Dataset", topdown=False):
for directory in dirs:
#print(os.listdir(os.path.join(root,directory)))
label = directory.split(' ')[0]
dirname="C:/wamp/www/SpoonSnapBackEnd/js/data/Image_Dataset/" + directory
... |
import tensorflow as tf
from resnet import softmax_layer, conv_layer, residual_block
n_dict = {20:1, 32:2, 44:3, 56:4}
def resnet(inpt, n):
if n < 20 or (n - 20) % 12 != 0:
print "ResNet depth invalid."
return
num_conv = (n - 20) / 12 + 1
layers = []
num_residual = 16
chOut =0
wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.