code stringlengths 1 199k |
|---|
import logging
from pyvisdk.exceptions import InvalidArgumentError
log = logging.getLogger(__name__)
def NumericRange(vim, *args, **kwargs):
'''The class that describe an integer range.'''
obj = vim.client.factory.create('ns0:NumericRange')
# do some validation checking...
if (len(args) + len(kwargs)) <... |
from robber import BadExpectation
from robber import expect
from robber.explanation import Explanation
from robber.matchers.base import Base
class Above(Base):
"""
expect(2).to.be.above(1)
"""
def matches(self):
return self.actual > self.expected
@property
def explanation(self):
... |
from .response_base import ResponseBase
class Identifiable(ResponseBase):
"""Defines the identity of a resource.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: Response
Variables are only populated by the server, and will be ignored when
sending a reques... |
"""
06b.py
~~~~~~
Advent of Code 2017 - Day 6: Memory Reallocation
Part Two
Out of curiosity, the debugger would also like to know the size of the
loop: starting from a state that has already been seen, how many block
redistribution cycles must be performed before that same state is seen
... |
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n == 0:
return 0
nums = [0] * (n + 2)
nums[1] = 1
for i in range(1, n // 2 + 1):
nums[2 * i] = nums[i]
nums[2 * i + 1] = nums[i] + nums[i + 1]
return max(nums[1 : n + 1])
for ... |
"""
ASN.1 type classes for universal types. Exports the following items:
- load()
- Any()
- Asn1Value()
- BitString()
- BMPString()
- Boolean()
- CharacterString()
- Choice()
- EmbeddedPdv()
- Enumerated()
- GeneralizedTime()
- GeneralString()
- GraphicString()
- IA5String()
- InstanceOf()
- Integer()
... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'StundenTabelle'
db.delete_table('stunden_stundentabelle')
# Adding model 'StundenAufzeichnung'
db.cre... |
def supress_nonlocal_image_warn():
import sphinx.environment
sphinx.environment.BuildEnvironment.warn_node = _supress_nonlocal_image_warn
def _supress_nonlocal_image_warn(self, msg, node, **kwargs):
from docutils.utils import get_source_line
if not msg.startswith('nonlocal image URI found:'):
se... |
"""Implements an |Edge| that receives messages with the HTTP protocol. WSGI_ is
a Python specification for defining communication between web servers and the
application.
The resulting edge can be used by any HTTP client, like curl::
$ curl -v -X POST -H 'Content-Type: message/rfc822' \\
--data-binary @t... |
import sys
import gzip
import bz2
import codecs
import argparse
import logging
def iopen(file, *args, **kwargs):
_open = open
if file.endswith('.gz'):
_open = gzip.open
elif file.endswith('.bz2'):
_open = bz2.open
return _open(file, *args, **kwargs)
def read_triples(path):
logging.in... |
import pytest
mark_benchmark = pytest.mark.skipif(not pytest.config.getoption("--run-benchmark"),
reason="need --run-benchmark option to run") |
from __future__ import division
import gpxpy
import gpxpy.gpx
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
def make_map(llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat, image):
fig, ax = plt.subplots()
m = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
... |
from httoop.codecs.codec import Codec
from httoop.exceptions import DecodeError
from httoop.util import _
class Multipart(Codec):
mimetype = 'multipart/*'
default_content_type = 'text/plain; charset=US-ASCII'
@classmethod
def encode(cls, data, charset=None, mimetype=None):
boundary = mimetype.boundary.encode('ISO... |
"""
This model contains the basic definition of an user.
We made the following assumptions:
- The user will login with his/her email on all instances of the website.
- We prefer to extend what django already has than to create something new.
"""
from django.contrib.auth.models import (AbstractBaseUser, BaseUser... |
from django.contrib import admin
from .models import Host, Event, Location, Category, Weekdays
admin.site.register(Host)
admin.site.register(Event)
admin.site.register(Location)
admin.site.register(Category)
admin.site.register(Weekdays) |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('snisi_core', '0008_auto_20150415_0945'),
]
operations = [
migrations.AlterField(
model_name='expectedvalidation',
name='report',
... |
import re
import datetime
from djangoapp.apps.caronasbrasil.model.post import Post
__author__ = 'edubecks'
class DateTimePost(Post):
def __init__(self, info):
super(DateTimePost, self).__init__(info)
self.tag_time = None
self.tag_date = None
self.post_date = None
## creation_... |
import re
import smbus
class Adafruit_I2C(object):
@staticmethod
def getPiRevision():
"Gets the version number of the Raspberry Pi board"
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
try:
with open('/proc/cpuinfo', 'r') as infile:
for line in i... |
from flask.ext import restful
from . import database
from flask import abort, request
from werkzeug import secure_filename
import os
class DocumentInstance(restful.Resource):
def get(self, id):
document = database.get_document(id)
if document is None:
abort(404)
document = {
... |
from __future__ import unicode_literals
from django.db import models
class Vehicle(models.Model):
license_plate = models.CharField(max_length=8)
vehicle_make = models.CharField(max_length=32)
vehicle_model = models.CharField(max_length=32)
build_year = models.IntegerField(default=0)
mileage_unit = models.CharField... |
from obspy.core.inventory import (Inventory, Network, Station, Channel, Site,
Response, InstrumentSensitivity, Frequency,
PolesZerosResponseStage,CoefficientsTypeResponseStage)
from obspy.core.util.obspy_types import FloatWithUncertaintiesAndUnit
from ... |
import os
import sys
import inspect
import optparse
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from fileIO import exportToFile, loadAlignment
from loggers import logging, init_logger
if __name__ == '__... |
import sys
from time import time
from clustering import cluster
from metrics import dice_metric, cosine_metric, lcs_metric
from preprocessing import process
from utils import write_result, calculate_quality
__author__ = "Michał Ciołczyk"
_ACTIONS = ["compare", "dice", "cosine", "lcs"]
_METRICS = ["dice", "cosine", "lcs... |
import psycopg2
""" This module contains classes and methods for the Swiss Tournament Manager.
"""
__appname__ = "Swiss Tournament Manager"
__author__ = "Davide Nastri"
__version__ = "1.0"
__license__ = "MIT"
def connect():
"""Connect to the PostgreSQL database.
Returns:
a database connection.
... |
from __future__ import absolute_import
import logging
import re
import cStringIO as StringIO
from . import configfile
from . import basesettings
logger = logging.getLogger(__name__)
def create_config_file(file, settings, disable=True):
config = create_config_object(settings)
with open(file, 'w') as fd:
... |
import os
os.system('rm -rf ../../question_library/test_caesar/')
os.system('rm ../../quizzes/test_caesar.py') |
"""Implements common model functions."""
import numpy as _nmp
import numpy.random as _rnd
import eQTLseq.utils as _utils
_EPS = _nmp.finfo('float').eps
def get_idxs_redux(beta, tau, zeta, eta, beta_thr):
"""Identifies relevant genes and markers."""
idxs = _nmp.abs(beta) > beta_thr
idxs_markers = _nmp.any(id... |
from jsonrpc import ServiceProxy
import sys
import string
rpcuser = ""
rpcpass = ""
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:55445")
else:
access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:55445")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destin... |
"""
@file
@brief Class to transfer files to a website using FTP, it only transfers updated files
"""
from __future__ import print_function
import re
import os
import warnings
import sys
import ftplib
from io import BytesIO
from time import sleep
from random import random
from .files_status import FilesStatus
from ..log... |
import math
import numpy as np
from data_io import get_dframe, get_data_for_source
from models import Model_2d_anisotropic
if __name__ == '__main__':
# First, get the number of sources
df = get_dframe()
nsources = len(df.source.unique())
# Fix parameters of group distribution
# log(V0) ~ N(mu, sigma... |
import dateutil.parser
import json
from urlparse import urljoin
from datetime import timedelta
from fb.http.http_client import HttpClient, AttachHeaderInterceptor, \
JsonResponseTransformer, InMemoryCacheStrategy
from fb.models import RemoteServer
from fb.domain.models import DomainPostParser
REMOTE_POSTS_CACHE = I... |
"""Test send_response."""
import io
import pytest
from phial import Attachment, Phial, Response
from tests.helpers import wildpatch
def test_send_response_string() -> None:
"""Test send_response works with a string."""
def mock_send_message(instance: Phial, response: Response) -> None:
assert response.t... |
import os
import sys
if __name__ == "__main__":
# CHANGED manage.py will use development settings by
# default. Change the DJANGO_SETTINGS_MODULE environment variable
# for using the environment specific settings file.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dilesmo.settings.development")
f... |
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.remote.webelement import WebElement
from Selenium2Library import utils
from Selenium2Library.locators import ElementFinder
from Selenium2Library.locators import CustomLocator
from key... |
import os
import sys
import subprocess
import tempfile
import itertools
STANFORD_CORENLP_3_4_1_JAR = 'stanford-corenlp-3.4.1.jar'
PUNCTUATIONS = ["''", "'", "``", "`", "-LRB-", "-RRB-", "-LCB-", "-RCB-", ".", "?", "!", ",", ":", "-", "--", "...", ";"]
class PTBTokenizer:
"""Python wrapper of Stanford PTBTokenizer""... |
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, extend3d=True, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
plt.show() |
from __future__ import division
import os
import sys
import string
try:
import argparse
except ImportError:
from optparse import OptionParser
class FormatBytes(object):
units = {
'1024': ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], # Kilobyte
'1000': ['B', 'kB', 'MB', 'GB', 'TB', '... |
from CIM15.CDPSM.Connectivity.IEC61970.Core.Equipment import Equipment
class TransformerTank(Equipment):
"""An assembly of two or more coupled windings that transform electrical power between voltage levels. These windings are bound on a common core and place in the same tank. Transformer tank can be used to model ... |
import inspect
from datetime import datetime
from heapqueue import *
class Message:
"""
A message passed between two components
:param: source, A Component, from which the message was sent
:param func: A string, the api function of the target to be run
component is required
:param func_context: ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('academics', '0038_auto_20160229_1120'),
]
operations = [
migrations.AlterModelOptions(
name='term',
options={'ordering': ['academ... |
"""\
PyMzn supports asynchronous solving through Python coroutines. The package
``pymzn.aio`` contains the coroutine version of the standard ``pymzn.minizinc``
function. This coroutine allows to execute the minizinc as an asynchronous
process and to obtain intermediate solutions while the solver is still in
execution. ... |
import sys, os, glob, re, shutil
FILTERED_DIR_NAME = "Filtered roms"
pattern = re.compile("\[(.*?)\]")
directory = sys.argv[1] if len(sys.argv) == 2 else os.path.dirname(os.path.realpath(__file__))
os.chdir(directory)
files = []
for file in glob.glob("*.nes"):
if "(U)" in file:
if not pattern.search(file) o... |
__requires__ = 'mozmill-automation==2.0.10'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('mozmill-automation==2.0.10', 'console_scripts', 'testrun_endurance')()
) |
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class StreamEntry(models.Model):
# ContentType for all StreamItems
item_type = models.ForeignKey(ContentType, related_name='streamentry_item_set')
# Parent object for all S... |
from django.conf.urls import patterns, url
import views
urlpatterns = [url(r'^$', views.api_index, name='api_index'), url(r'^refresh_cache$', views.refresh_cache, name='refresh_cache'), url(r'^endpointlist', views.endpointlist, name='endpointlist')]
endpoints = views.endpoints()
for endpointkey in endpoints:
endpoi... |
from setuptools import setup
import os
_dirs = \
[
'logs',
'output',
'output/heroes',
'output/adversaries',
]
for _dir in _dirs:
if (not os.path.isdir(_dir)):
os.makedirs(_dir)
setup \
(
name='hammerhal',
version='0.2',
install_requires =
[
'jsonschema',
'Pill... |
from sys import argv
from nltk.tag import StanfordNERTagger
from nltk.tag import StanfordPOSTagger
from nltk.tokenize import sent_tokenize
import re
import sys
import logging
reload(sys)
sys.setdefaultencoding('utf8')
script, filename, loadname = argv
logging.basicConfig(format='preprocess progress:%(message)s', level=... |
username = "username"
password = "password"
settings_file_path = "settings"
host = "localhost"
port = 27017 |
import requests
import re
import urllib
from flask import Flask, jsonify, render_template
from flask.ext.cacheify import init_cacheify
from flask.ext.misaka import Misaka
app = Flask(__name__)
app.debug = True
Misaka(app, fenced_code=True)
cache = init_cacheify(app)
@app.route('/')
def index():
# render README.md as i... |
try:
from collections import namedtuple
except ImportError:
from _collections import namedtuple
T = namedtuple("Tup", "foo bar")
t = T(1, 2)
print(t)
print(t[0], t[1])
print(t.foo, t.bar)
print(len(t))
print(bool(t))
print(t + t)
print(t * 3)
print(isinstance(t, tuple))
try:
t[0] = 200
except TypeError:
... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0066_rewrite_mobile_numbers'),
]
operations = [
migrations.AddField(
model_name='team',
name='page_image',
field=models.ImageField(blank=True,... |
from django.apps import AppConfig
class Degree360Config(AppConfig):
name = 'Degree360' |
import codecs
import datetime
import os
from functools import wraps
import bottle
from bottle import (
route,
run,
jinja2_template as template,
redirect,
request,
response,
static_file,
)
from bottle_utils.flash import message_plugin
from middleware.twitter import TwitterMiddleware
import ut... |
def isqrt(x):
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y |
from django.template.response import TemplateResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from .utils import total_seconds
from . import utils
ALLOWED_RESPONSE_TYPES = ("code", "token", )
ALLOWED_GRANT_TYPES = ("authorization_code", "refresh_token", )
class OAuthVi... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import bagger
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Bagger'
copyright = u'2015, Jon Ferretti'
version =... |
from __future__ import absolute_import, unicode_literals
from base import GAETestCase
from category_app.category_model import Category
from routes.categorys.home import index, delete
from gaebusiness.business import CommandExecutionException
from gaegraph.model import Node
from mommygae import mommy
from tekton.gae.mid... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class AvailabilitySetsOperations(object):
"""AvailabilitySetsOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
... |
import pyaudio
import wave
import audioop
import sys
import websocket
CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SEC = input('REC TIME >')
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
... |
import re
try:
from _scss import Scanner, NoMoreTokens
except ImportError:
Scanner = None
if not Scanner:
class NoMoreTokens(Exception):
"""
Another exception object, for when we run out of tokens
"""
pass
class Scanner(object):
def __init__(self, patterns, ignore... |
from msrest.serialization import Model
class ExpressRouteCircuitsArpTableListResult(Model):
"""Response for ListArpTable associated with the Express Route Circuits API.
:param value: Gets list of the ARP table.
:type value:
list[~azure.mgmt.network.v2017_09_01.models.ExpressRouteCircuitArpTable]
:p... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exile', '0005_auto_20160915_0012'),
]
operations = [
migrations.AddField(
model_name='seccion',
name='posicion',
fiel... |
import os
from setuptools import setup, find_packages
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
setup(
name='pytest-watch',
version='3.3.0',
description='Local continuous test runner with pytest and watchdog.',
long_description=rea... |
import json
from typing import Set, Union
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models, connection
from django.db.models import Subquery, F, IntegerField, OuterRef, Count
from django.db.models.functions import Coalesce
from django.utils.functional import c... |
import pygame, math, time
import numpy as np
PlayerGroup = pygame.sprite.Group()
LevelGroup = pygame.sprite.Group()
class Level(pygame.sprite.Sprite):
def __init__(self, *args, **kwargs):
pygame.sprite.Sprite.__init__(self, LevelGroup)
self.image = pygame.image.load('testlevel.png').convert_alpha()
... |
import numpy as np
np.seterr(all='raise')
N_big = 20
N_small = 5
thresh = 1e-6
from snippets.safemath import normalize
from snippets.safemath import safe_log
from snippets.safemath import safe_multiply
def check_normalization_constants(arr, axis):
sum = np.log(np.sum(arr, axis=axis))
z = normalize(np.log(arr), ... |
"""
PostgreSQL is basically just driven by a database/user/password configuration.
Everything else (replication, ports, etc) is not available, yet. For most web
applications though, this is enough. You can also specify multiple databases.
.. sourcecode:: yaml
deploy:
- postgresql
database: fooba... |
"""
=====================================================
Distance computations (:mod:`scipy.spatial.distance`)
=====================================================
Function Reference
------------------
Distance computation within/between collections of raw observation vectors
using index pointers.
ssdist -- spars... |
"""
Main UI
- ~To Do~
Type Description
"""
from pyqode.qt import QtCore, QtGui, QtWidgets
from pyqode.python.widgets import PyInteractiveConsole
from pyqode.core.widgets.outline import OutlineTreeWidget
from pyqode.core.widgets import SplittableCodeEditTabWidget
from fileDropWidget import FileDropWidget
class MainUI(ob... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feelings.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is rea... |
from django.urls import reverse
from django.test import TestCase
from ditto.pinboard.factories import AccountFactory, BookmarkFactory
class PinboardViewTests(TestCase):
def test_home_templates(self):
"The Pinboard home page uses the correct templates"
response = self.client.get(reverse("pinboard:hom... |
from web import app
from flask import render_template
from flask_login import current_user
@app.route('/login')
def login():
return 'hello'
@app.route('/me')
def profile():
user = current_user
return render_template('user/profile.html', user=user) |
"""Views for the ``django-tinylinks`` application."""
import re
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model, login
from django.contrib.auth.decorators import permission_required
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db.mode... |
from .local import *
env = os.environ.get
INSTALLED_APPS += [
'django.contrib.postgres'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': env('RDS_DB_NAME'),
'USER': env('RDS_USERNAME'),
'PASSWORD': env('RDS_PASSWORD'),
'HOST': env('RDS_HOSTN... |
__author__ = 'david'
class TestObject(object):
def __init__(self):
self.message = u'This is the test object' |
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.UserListView.as_view(),
name='list'
),
url(
regex=r'^profile/$',
view=views.ProfileView.as_view(),
name='... |
from datetime import date
import TwitterGEXF as TG # custom gexf saver
import networkx as nx
class GEXFSaver(object):
"""
Saves graph in gexf format
"""
problems = [ ]
@staticmethod
def stringit(x):
"""
Fixes problem with unicode encoding
"""
try:
ret... |
"""
Custom made Quaternion attribute made for simulation
"""
class Quaternion:
def __init__(self):
self.x = None
self.y = None
self.z = None
self.w = None |
import torch
from . import nccl
from torch._utils import _accumulate, _take_tensors, _flatten_dense_tensors, \
_flatten_sparse_tensors, _unflatten_dense_tensors, \
_unflatten_sparse_tensors, _reorder_tensors_as
def broadcast(tensor, devices):
"""Broadcasts a tensor to a number of GPUs.
Arguments:
... |
import wx
class Menu(wx.Menu):
def __init__(self):
wx.Menu.__init__(self)
def GetIdIndex(self, mi_id):
index = -1
for MI in self.GetMenuItems():
index += 1
if MI.GetId() == mi_id:
break
if index < 0:
return None
return i... |
"""
Base Settings
"""
import os
import sys
import socket
import logging.config
CUR_DIR = os.path.dirname(os.path.abspath(__file__))
APP_DIR = os.path.dirname(CUR_DIR)
ROOT_DIR = os.path.dirname(APP_DIR)
APP_NAME = os.path.basename(APP_DIR)
sys.path.insert(0, os.path.join(APP_DIR, 'apps'))
DEBUG = True
SETTINGS_DIR = '/... |
__revision__ = "test/CPPDEFINES/append.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Verify appending to CPPPDEFINES with various data types.
See also pkg-config.py in this dir.
"""
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """\
env_1738_2 = Environment(CPPDEFPREFIX='-D')... |
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../Contents/Code')))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../Contents/Libraries/Shared'))) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='APIKeyPair',
fields=[
('id', models.AutoField(auto_create... |
from grow.pods import pods
from grow.pods.collectionz import collectionz
from grow.pods.collectionz import messages
from grow.pods import locales
from grow.pods import storage
import unittest
class CollectionsTestCase(unittest.TestCase):
def setUp(self):
self.pod = pods.Pod('grow/pods/testdata/pod/', storage=stor... |
import urllib
import urllib2
import re
try:
url = 'http://pythonprogramming.net/parse-website-using-regular-expressions-urllib/'
#values = {'q' : 'sql'}
#data = urllib.urlencode(values)
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/... |
"""
- `File`: fabfile.py
- `Author`: Me
- `Email`: 0
- `Github`: 0
- `Description`: Makefile for generating documentaiton
"""
import os
from fabric.api import local
from ConfigParser import ConfigParser
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
DOC_DIR = os.path.join(PROJECT_DIR, 'docs'... |
from bisect import bisect
import gtk
from gtk.keysyms import F2, Escape, Control_L, Control_R, Alt_L, Alt_R, Shift_L, Shift_R
from gtk.gdk import SHIFT_MASK, CONTROL_MASK, MOD1_MASK, SUPER_MASK
from .utils import make_missing_dirs
ANY_CTX = ('any', )
DEFAULT_PRIORITY = 0
gtk.accelerator_set_default_mod_mask(SHIFT_MASK ... |
"""Copyright 20102 Phidgets Inc.
This work is licensed under the Creative Commons Attribution 2.5 Canada License.
To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ca/
"""
__author__ = 'Adam Stelmack'
__version__ = '2.1.8'
__date__ = 'May 10 2010'
import threading
from ctypes import *
fro... |
import os
from collections import namedtuple
import json
LocalBusiness = namedtuple('LocalBusiness', ['address', 'geo', 'name', 'url', 'telephone', 'id'])
GeoCoordinates = namedtuple('GeoCoordinates', ['latitude', 'longitude'])
Address = namedtuple('Address', ['addressCountry', 'addressLocality', 'addressRegion', 'po... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20150228_1957'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.Au... |
"""taxiInfo 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... |
import string
import socket
import sys
import time
class SimpleSocket(object):
def __init__(self, hostname, port = 22611, timeout = 20):
self.hostname = hostname
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
sys.stderr.wr... |
from PyQt5 import QtCore, QtWidgets, QtGui
from UI import ChoicePopup
from Wolke import Wolke
class VariantPopupWrapper(object):
def __init__(self, variantListCollection, windowTitle, currentEP):
super().__init__()
self.formMain = QtWidgets.QDialog()
self.formMain.setWindowFlags(
... |
import numpy as np
import pandas.lib as lib
import pandas as pd
from pandas.compat import reduce
from pandas.core.index import Index
from pandas.core import common as com
def match(needles, haystack):
haystack = Index(haystack)
needles = Index(needles)
return haystack.get_indexer(needles)
def cartesian_prod... |
import unittest
"""
Expressions written in postfix expression are evaluated faster compared to infix notation
as postfix does not require parenthesis. Write program to evaluate postfix expression.
"""
"""
Approach:
1. Scan postfix expression from left to right.
2. If element is operand, we push it on the stack.
3. If e... |
from datetime import datetime, timedelta
from django.shortcuts import get_object_or_404
from service_order.models import Order_State_Machine, Service_Order as Order, SO_Refund_Sheet as Refund_Sheet, \
input_actions, SO_Refund_Log as Refund_Log
class Order_System:
@classmethod
def get_initial(cls):
re... |
from toee import *
def OnBeginSpellCast(spell):
print "Dissonant Chord OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Dissonant Chord OnSpellEffect"
targetsToRemove = []
s... |
"""
[2015-05-04] Challenge #213 [Easy] Pronouncing Hex
http://www.reddit.com/r/dailyprogrammer/comments/34rxkc/20150504_challenge_213_easy_pronouncing_hex/
Description
The HBO network show "Silicon Valley" has introduced a way to pronounce hex.
Kid: Here it is: Bit… soup. It’s like alphabet soup, BUT… it’s ones and zer... |
from setuptools import setup, find_packages
setup(name='MODEL1311110000',
version=20140916,
description='MODEL1311110000 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main/MODEL1311110000',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmail.com',
packages=find_packages()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.