code stringlengths 1 199k |
|---|
import re
import json
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream
SWF_URL = "https://www.connectcast.tv/jwplayer/jwplayer.flash.swf"
_url_re = re.compile("http(s)?://(\w+\.)?connectcast.tv/")
_manifest_re = re.compile(".*data-playba... |
import Queue
import sys
import threading
import time
from test.test_support import verify, TestFailed, verbose
QUEUE_SIZE = 5
class _TriggerThread(threading.Thread):
def __init__(self, fn, args):
self.fn = fn
self.args = args
self.startedEvent = threading.Event()
threading.Thread.__i... |
import os
import sys
import tempfile
import unittest
import warnings
from io import StringIO
from unittest import mock
from django.apps import apps
from django.contrib.sites.models import Site
from django.core import management
from django.core.files.temp import NamedTemporaryFile
from django.core.management import Com... |
import operator
from ..util import decorator
from . import config
from .. import util
import inspect
import contextlib
from sqlalchemy.util.compat import inspect_getargspec
def skip_if(predicate, reason=None):
rule = compound()
pred = _as_predicate(predicate, reason)
rule.skips.add(pred)
return rule
def... |
from importlib import import_module
from django.core.management.base import CommandError
from django.core.management.templates import TemplateCommand
from ..utils import get_random_secret_key
class Command(TemplateCommand):
help = (
"Creates a Django project directory structure for the given project "
... |
import os
abspath = os.path.abspath(__file__)
os.chdir(os.path.dirname(abspath))
exec(compile(open("wpt", "r").read(), "wpt", 'exec')) |
const NONE = 0;
const READ_ONLY = 1;
const DONT_ENUM = 2;
const DONT_DELETE = 4;
const GETTER = 0;
const SETTER = 1;
const kApiTagOffset = 0;
const kApiPropertyListOffset = 1;
const kApiSerialNumberOffset = 2;
const kApiConstructorOffset = 2;
const kApiPrototypeTemplateO... |
from ._trustregion import (_minimize_trust_region)
from ._trlib import (get_trlib_quadratic_subproblem)
__all__ = ['_minimize_trust_krylov']
def _minimize_trust_krylov(fun, x0, args=(), jac=None, hess=None, hessp=None,
inexact=True, **trust_region_options):
"""
Minimization of a scala... |
from __future__ import unicode_literals
from frappe.model.document import Document
class DosageStrength(Document):
pass |
DOCUMENTATION = """
---
module: eos_template
version_added: "2.1"
author: "Peter sprygada (@privateip)"
short_description: Manage Arista EOS device configurations
description:
- Manages network device configurations over SSH or eAPI. This module
allows implementors to work with the device running-config. It
... |
import sys
import os
geonode_path = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '../geonode'))
sys.path.append(geonode_path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import glob
from random import randint
from timeit import Timer
from django.core.files import File
from django.conf ... |
"""
The Topology module is the root of an object model composed of entities
like switches, hosts, links, etc. This object model is populated by other
modules. For example, openflow.topology populates the topology object
with OpenFlow switches.
Note that this means that you often want to invoke something like:
$ ./... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ansible._vendor
from ansible.release import __version__, __author__ |
import base64
import re
import unicodedata
import json
from django.core.exceptions import ImproperlyConfigured
from django.core.validators import validate_email, ValidationError
from django.core import urlresolvers
from django.contrib.sites.models import Site
from django.db.models import FieldDoesNotExist
from django.d... |
from . import mrp_production |
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class World(Base):
__tablename__ = 'world'
id = Column(Integer, primary_key=True)
randomnumber = Column(Integer)
sa_worlds = World.__table__
class Fortune(Base):
__tablename__... |
from collections import namedtuple
name0 = "name"
name = name0
nt = namedtuple(name, ["x", "y"]) |
import os, sys, time, os
from multiprocessing.pool import ThreadPool
thread_pool = ThreadPool(4)
stat = open(sys.argv[1])
line = stat.readline()
while not 'second:' in line:
line = stat.readline()
keys = line.strip().split(':')[1:]
output_dir = 'session_stats_report'
line_graph = 0
histogram = 1
stacked = 2
graph_colo... |
nplurals=3 # Czech language has 3 forms:
# 1 singular and 2 plurals
get_plural_id = lambda n: ( 0 if n==1 else
1 if 2<=n<=4 else
2 ) |
from __future__ import with_statement
__author__ = 'rafek@google.com (Rafe Kaplan)'
import logging
from . import descriptor
from . import generate
from . import messages
from . import util
__all__ = ['format_proto_file']
@util.positional(2)
def format_proto_file(file_descriptor, output, indent_space=2):
out = generat... |
"""
hyper/common/decoder
~~~~~~~~~~~~~~~~~~~~
Contains hyper's code for handling compressed bodies.
"""
import zlib
class DeflateDecoder(object):
"""
This is a decoding object that wraps ``zlib`` and is used for decoding
deflated content.
This rationale for the existence of this object is pretty unpleas... |
import errno
import os
import warnings
from datetime import datetime
from django.conf import settings
from django.core.exceptions import SuspiciousFileOperation
from django.core.files import File, locks
from django.core.files.move import file_move_safe
from django.core.signals import setting_changed
from django.utils i... |
"""Various utility classes and functions."""
import codecs
from datetime import timedelta, tzinfo
import os
import re
try:
set = set
except NameError:
from sets import Set as set
import textwrap
import time
from itertools import izip, imap
missing = object()
__all__ = ['distinct', 'pathmatch', 'relpath', 'wrapt... |
""" API v1 URLs. """
from django.conf import settings
from django.conf.urls import patterns, url, include
from commerce.api.v1 import views
COURSE_URLS = patterns(
'',
url(r'^$', views.CourseListView.as_view(), name='list'),
url(r'^{}/$'.format(settings.COURSE_ID_PATTERN), views.CourseRetrieveUpdateView.as_... |
from __future__ import print_function, division
from sympy import pi, I
from sympy.core.singleton import S
from sympy.core import Dummy, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.functions import assoc_legendre
from sympy.functions.elementary.trigonometric import sin, cos, cot
from... |
from __future__ import unicode_literals
import re
from .mtv import MTVServicesInfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse,
)
from ..utils import (
ExtractorError,
float_or_none,
unified_strdate,
)
class ComedyCentralIE(MTVServicesInfoExtractor):
_VALID_URL = r'''(?x)http... |
"""
An alphabetical list of Swedish counties, sorted by codes.
http://en.wikipedia.org/wiki/Counties_of_Sweden
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
COUNTY_CHO... |
import document_page_show_diff |
"""Data structures and algorithms for profiling information."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
class ProfileDatum(object):
"""Profile data point."""
def __init__(self,
device_name,
node_exec_stats,
... |
from openerp.osv import fields,osv
from openerp import tools
AVAILABLE_PRIORITIES = [
('0', 'Low'),
('1', 'Normal'),
('2', 'High')
]
class crm_claim_report(osv.osv):
""" CRM Claim Report"""
_name = "crm.claim.report"
_auto = False
_description = "CRM Claim Report"
_columns = {
'user... |
import csv
import numpy as np
from utils import util
from utils.clock_utils import make_bufg, MAX_GLOBAL_CLOCKS
from prjuray.db import Database
CMT_XY_FUN = util.create_xy_fun('')
def print_top(seed):
np.random.seed(seed)
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
site_to_tile =... |
"""
controlbeast.keystore.handler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2013 by the ControlBeast team, see AUTHORS.
:license: ISC, see LICENSE for details.
"""
from collections import UserDict
import os
import tempfile
import yaml
from controlbeast.keystore.plain import CbKsPlain
from cont... |
"""
@file test_magnet_mag3110.py
"""
import os
import time
from oeqa.utils.helper import shell_cmd
from oeqa.oetest import oeRuntimeTest
from EnvirSetup import EnvirSetup
from oeqa.utils.decorators import tag
@tag(TestType="FVT", FeatureID="IOTOS-757")
class TestMagnetMAG3110(oeRuntimeTest):
"""
@class TestMagn... |
class Node:
def __init__(self, val=None):
self.left, self.right, self.val = None, None, val
INFINITY = float("infinity")
NEG_INFINITY = float("-infinity")
def isBST(tree, minVal=NEG_INFINITY, maxVal=INFINITY):
if tree is None:
return True
if not minVal <= tree.val <= maxVal:
return F... |
from __future__ import division
import numpy as np
from numpy.linalg import solve
def cov_mat(x1, x2, a, b):
return a * np.exp(-b * (x1[:, np.newaxis] - x2)**2)
def reg_cov_mat(x, a, b, c):
return cov_mat(x, x, a, b) + c * np.eye(x.shape[0])
def compute_means_covs(ts, t_ref, gp_parms, winsize=0, mean_shift=True... |
import arrow
from jinja2 import Environment, FileSystemLoader, select_autoescape
import mistune
from yaml import load
import os
from pathlib import Path
import pygments
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html
import shutil
import re
from xml.dom ... |
from typing import Tuple
from hypothesis import strategies
from cetus.queries.filters import (PREDICATES,
LOGICAL_OPERATORS,
INCLUSION_OPERATORS,
RANGE_OPERATORS,
COMPARISON_OPERAT... |
from django.contrib.auth.decorators import login_required
from django.db.models.functions import Lower
from django.shortcuts import render
from django.contrib import messages
import random
import re
from .models import Hunt, Team
from .forms import PersonForm, ShibUserForm
import logging
logger = logging.getLogger(__na... |
people = [
{
'name': "Мария",
'interests': ['пътуване', 'танци', 'плуване', 'кино'],
'gender': "female",
},
{
'name': "Диана",
'interests': ['мода', 'спортна стрелба', 'четене', 'скандинавска поезия'],
'gender': "female",
},
{
'name': "Дарина",... |
from utils import parse_date
import datetime
import unittest
class TestLateTube(unittest.TestCase):
def test_calculate_duration(self):
self.assertEqual(0, 0)
def test_parse_date(self):
dt = parse_date("19-Aug-2017", "19:33")
self.assertEqual(datetime.datetime(2017, 8, 19, 19, 33), dt)
def ... |
str = "print(3*(2-3^8))"#raw_input()
stack = []
queue = []
for index, c in enumerate(str):
print(index, c)
raw_input() |
import _plotly_utils.basevalidators
class NameValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="name",
parent_name="heatmap.colorbar.tickformatstop",
**kwargs
):
super(NameValidator, self).__init__(
plotly_name=plotly_na... |
import _plotly_utils.basevalidators
class TickmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="tickmode", parent_name="contour.colorbar", **kwargs
):
super(TickmodeValidator, self).__init__(
plotly_name=plotly_name,
parent_... |
def check(s):
if( 'i' in s or 'o' in s or 'l' in s):
return 0
count = 0
flag = 0
char = ""
for i in range(len(s)-1):
if(s[i] == s[i+1] and s[i] not in char):
count += 1
char += s[i]
for i in range(len(s)-2):
if(s[i] == chr(ord(s[i+1])-1) and s[i+1]... |
"""find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4."""... |
import datetime
import hashlib
import json
import logging
import mimetypes
import os
import pkg_resources
import pytz
import grades
from functools import partial
from courseware.models import StudentModule
from django.core.exceptions import PermissionDenied
from django.core.files import File
from django.core.files.stor... |
"""
AVWX Test Suite
"""
import sys
from pathlib import Path
sys.path.insert(0, Path(__file__).parent.joinpath("..")) |
class Cache(object):
def __init__(self, max=1000):
self.d = {}
self.l = []
self.max = max
def put(self, k, v):
self.d[k] = v
self.l.append(k)
while (len(self.l) > self.max):
kdel = self.l[0]
del self.l[0]
del self.d[kdel]
def get(self, k):
try:
return self.d[k]
except:
return None
def... |
"""
Serializer class to convert Python objects into a binary data stream for sending them to Rserve.
"""
__all__ = ['reval', 'rassign', 'rSerializeResponse']
import struct, os, cStringIO, socket
import numpy
import rtypes
from misc import FunctionMapper
from rexceptions import RSerializationError
from taggedContainers ... |
from pymiecoated import Mie
import sys
import os
import numpy as np
from pprint import pprint
from datetime import datetime
import mysql.connector
import math
import matplotlib.pyplot as plt
import matplotlib.colors
import calendar
from scipy.optimize import curve_fit
assumed_coating_th = [41,43,44,40,38,40,44,41,38,38... |
from typing import Generic, TypeVar, Dict, Sized, Tuple
from typing import List
T = TypeVar("T")
InternalEntry = Tuple[float, int, T]
Entry = Tuple[T, float]
class BinaryHeap(Generic[T], Sized):
"""
Dvojiška kopica z najmanjšo vrednostjo na vrhu.
Kopica je predstavljena s seznamom,
v katerem je i-ti vno... |
import time
import callServer
POLL_FREQ_IN_S = 5
MIN_TIME_THRESHOLD = 1
WEIGHT_THRESHOLD_IN_G = 100
FEEDING_FREQ = 12
def getData():
return 0
def notify():
callServer.BoomerIsFed()
def run(debug=False):
# Get data from the sensor
data = getData()
thresholdTime = 0
while(True):
time.sleep... |
import asyncio
import discord
import random
import urllib
import requests
import json
import time
import os
from discord.ext import commands
from Cogs import Message
from Cogs import FuzzySearch
from Cogs import GetImage
from Cogs import Nullify
class Humor:
def __init__(self, bot, settings, listName = "Adjectives.t... |
from __future__ import (unicode_literals, division, absolute_import, print_function)
import json
from powerline.lib.url import urllib_read, urllib_urlencode
from powerline.lib.threaded import KwThreadedSegment
from powerline.segments import with_docstring
weather_conditions_codes = (
('tornado', 'storm... |
from __future__ import unicode_literals
from .logic_adapter import LogicAdapter
class NoKnowledgeAdapter(LogicAdapter):
"""
This is a system adapter that is automatically added
to the list of logic adapters durring initialization.
This adapter is placed at the beginning of the list
to be given the h... |
import sys
CS = [
"abcefg", "cf", "acdeg", "acdfg", "bcdf",
"abdfg", "abdefg", "acf", "abcdefg", "abcdfg",
]
LENS = set(len(x) for x in CS)
RCS = {l: [(i, x) for i, x in enumerate(CS) if len(x) == l] for l in LENS}
MCS = {k: i for i, k in enumerate(CS)}
def get(s):
l = list(s)
assert len(l) == 1, s
... |
import os
import logging
from rdb_backup.utility import run_shell
from rdb_backup.processor import DatabaseProcessor, TableProcessor
log = logging.getLogger(__name__)
class MysqlLocal(DatabaseProcessor):
processor_name = 'mysql'
tmp_dir = '/tmp/rdb_backup/mysql_local'
if not os.path.exists(tmp_dir):
... |
from django.http import HttpResponse
from django.template import RequestContext, loader
from rss_feed.models import Feed
import feedparser
def index(request):
"""
index lists the feeds we are tracking
"""
feed_list = Feed.objects.all()
template = loader.get_template('index.html')
context = Reque... |
"""Test Automation config panel."""
from http import HTTPStatus
import json
from unittest.mock import patch
import pytest
from homeassistant.bootstrap import async_setup_component
from homeassistant.components import config
from homeassistant.helpers import entity_registry as er
from tests.components.blueprint.conftest... |
from SDA import *
import unittest
import numpy
class FlightBoundaryTestCase(unittest.TestCase):
def setUp(self):
test_min_altitude1 = 50.0
test_max_altitude1 = 200.0
test_min_altitude2 = -300.0
test_max_altitude2 = -50.0
test_boundary_waypoints1 = numpy.array([(0,0),(0,100),(... |
"""
Response from a Homogeneous Layer for Different Waveforms
=========================================================
Here we use the module *SimPEG.electromagnetics.viscous_remanent_magnetization*
to predict the characteristic VRM response over magnetically viscous layer.
We consider a small-loop, ground-based surve... |
"""
This module implements an internal topology builder class QTopology.
QTopology creates a mapping between the system's structure (QStruct),
bonding patterns/charges (QLib), and the parameters (Qrm), allowing
evaluation of individual topological components of the system.
"""
from __future__ import absolute_import, un... |
def func_TODO():
'''
TODO
:param: TODO TODO
:return: TODO
'''
pass
class ClassTODO:
'''
TODO
'''
def __init__(self):
'''
Constructor for TODO
'''
pass
def main():
'''
Main execution point of the program
'''
pass
if __name__ == "__ma... |
from __future__ import print_function
import sys
import re
import time, datetime
class ProgressBar(object):
def __init__(self, total_items):
"""Initialized the ProgressBar object"""
#Vars related to counts/time
self.total_items = total_items
self.current = 0
self.finished = F... |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
def compute_checksum(data, *algorithms):
checksums = {}
def _finalize(algorithm):
digest = checksums.get(algorithm.name)
if digest:
checksums[algorithm.name] = digest.finalize()... |
"""Test resurrection of mined transactions when the blockchain is re-organized."""
from test_framework.test_framework import nealcoinTestFramework
from test_framework.util import *
class MempoolCoinbaseTest(nealcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
sel... |
from __future__ import division, print_function
import numpy as np
class OnlineStatistics(object):
def __init__(self, axis=0):
self.axis = axis
self.n = None
self.s = None
self.s2 = None
self.reset()
def reset(self):
self.n = 0
self.s = 0.0
self.s2... |
"""Change navigation bar relationship.
Revision ID: f8fcd4bb38cc
Revises: 94f861ea7006
Create Date: 2017-02-11 13:57:03.925474
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
revision... |
"""
A stream buffer abstraction
StreamBuf is similar to StringIO (or cStringIO)
but will continue to return the same data on
read() until you ack(n), which advances the read
pointer. close()'ing a StreamBuf marks it as
closed but does not prevent further reads -- useful
for allowing a produc... |
from app import db
from app.models.base_model import BaseEntity
from app.models.contact import Contact
from app.models.location import Location
class Company(db.Model, BaseEntity):
__tablename__ = 'company'
name = db.Column(db.String(200), unique=True)
description = db.Column(db.Text())
logo_file_id = d... |
import re
from core.actionModule import actionModule
from core.keystore import KeyStore as kb
from core.mymsf import myMsf
from core.utils import Utils
class exploit_msf_psexec_pth(actionModule):
def __init__(self, config, display, lock):
super(exploit_msf_psexec_pth, self).__init__(config, display, lock)
... |
from __future__ import unicode_literals
import accelerator_abstract.models.base_expert_interest
import accelerator_abstract.models.secure_file_system_storage
import accelerator_abstract.utils
from decimal import Decimal
from django.conf import settings
import django.core.validators
from django.db import migrations, mod... |
import sys,os
import re
import json
interaction_f = sys.argv[1]
node_f = sys.argv[2]
prefix = sys.argv.pop()
NetJson = {}
NetJson['nodes'] = []
NetJson['links'] = []
node = {}
i = 0
no = open(node_f, 'rb')
while True:
l = no.readline()
if len(l) == 0:
break
if re.search('^#',l):
continue
l = l.strip('\n')
lc =... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
s1 = set(nums)
s2 = set(nums)
for num in nums:
if num in s1:
s1.remove(num)
elif num in s2:
s2.remove(... |
import unittest
from mygrations.helpers.dotenv import dotenv, DotEnvSyntaxError
import io
import tempfile
class DotEnvTest(unittest.TestCase):
dotenv = None
test_string = 'test string'
def setUp(self):
self.dotenv = dotenv()
# get_contents should accept a number of parameters.
# It should ac... |
import json
import logging
import os
import tempfile
import capture
import maya.cmds as cmds
from .vendor.Qt import QtCore, QtWidgets, QtGui
from . import lib
from . import plugin
from . import presets
from . import version
from . import tokens
from .accordion import AccordionWidget
log = logging.getLogger("Capture Gui... |
import logging
import requests
from twython import TwythonStreamer
import settings
class FactStreamer(TwythonStreamer):
def __init__(self, users, *args, **kwargs):
self.users = users
super().__init__(*args, **kwargs)
@property
def logger(self):
return logging.getLogger(str(self))
... |
from sqlalchemy import BINARY, Column, Index, Integer, String, VARBINARY
from sqlalchemy import String, Unicode, ForeignKey
from sqlalchemy.orm import relationship, backref
from dbdatetime import dbdatetime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class ... |
import sys
from boto.ec2.connection import EC2Connection
def instancedetails(ec2, instance_ids):
reservations = ec2.get_all_instances(instance_ids=instance_ids)
for reservation in reservations:
instances = reservation.instances
for instance in instances:
print "Instance {0}".format(instance.id)
print "State... |
from __future__ import with_statement
import os
from vcs.backends.hg import MercurialRepository, MercurialChangeset
from vcs.exceptions import RepositoryError, VCSError, NodeDoesNotExistError
from vcs.nodes import NodeKind, NodeState
from vcs.tests.conf import TEST_HG_REPO, TEST_HG_REPO_CLONE, TEST_HG_REPO_PULL
from vc... |
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from orcid_api_v3.models... |
from django.conf.urls import url
from . import views
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = [
url(r'^$', RedirectView.as_view(url=reverse_lazy('list_job')), name='index'),
url(r'^list-job$', views.list_job, name='list_job'),
url(r'^new-j... |
import boto3
from sh import Command, chmod, cp, mkdir, rsync, ErrorReturnCode
import uritools
from ..decorators import schemes
from ..err import Err
from .files import File, FileTar
from .http import HTTP, HTTPTar, HTTPJar
from .jar import Jar
from .core import onepath, oneurl, SignableURL, twopaths
from .tar import Ta... |
from satella.threads import BaseThread
from satella.contrib.instrumentation_as_json import export
import time
class InstrumentationSaverThread(BaseThread):
def __init__(self, insmgr, confsection):
BaseThread.__init__(self)
self.interval = confsection['save_interval']
self.savetarget = confse... |
from django import template
from django.template.loader import render_to_string
def split_into_variables(token):
# split and remove name
tokens = token.split_contents()[1:]
return map(template.Variable, tokens)
class GenericTemplateTag(template.Node):
def __init__(self, *args, **kwargs):
raise N... |
from sen.docker_backend import DockerBackend, DockerContainer
from sen.tui.views.container_info import ProcessList
from tests.real import mock
def test_short_id():
mock()
b = DockerBackend()
operation = DockerContainer({"Status": "Up", "Id": "voodoo"}, b).top()
top_response = operation.response
pt =... |
from distutils.core import setup, Extension
from os import system, environ
from os.path import abspath, dirname, exists
from sys import platform
v8eval_root = abspath(dirname(__file__))
v8_dir = v8eval_root + '/v8'
py_dir = v8eval_root + '/python'
py_v8eval_dir = py_dir + '/v8eval'
system(v8eval_root + '/build.sh')
sys... |
import sys
import traceback
import rpcrequest
import rpcresponse
import rpcerror
import rpcjson
def rpcmethod(func):
"""
Decorator
Sign the decorated method as JSON-RPC-Method
"""
# Sign the function as JSON-RPC-Method
func.rpcmethod = True
# Return the function itself
return func
class ... |
import threading
from queue import Queue
class WorkQueue(Queue):
'''Simple wrapper to also provide ability to indicate when no more work is expected.
'''
def __init__(self, *args):
Queue.__init__(self, *args) # Queue does not inherit from object (is an old-style class)
self._all_jobs_submit... |
import matplotlib as mpl
import pylab as pl
from pylab import rc
rc('axes', linewidth=1.2)
mpl.rcParams['font.size'] = 18.
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['font.serif'] = ['Times']#Computer Modern Roman']
mpl.rcParams['font.weight'] = 'bold'
mpl.rcParams['text.usetex'] = True
mpl.rcParams['axes.label... |
__author__ = 'chris'
import json
import os
import time
from constants import DATA_FOLDER
from db.datastore import VendorStore, MessageStore
from random import shuffle
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol
from protos.countries import CountryCode
from protos.objects impor... |
from .stop_words import STOP_WORDS
from ...language import Language
class LatvianDefaults(Language.Defaults):
stop_words = STOP_WORDS
class Latvian(Language):
lang = "lv"
Defaults = LatvianDefaults
__all__ = ["Latvian"] |
<<<<<<< HEAD
<<<<<<< HEAD
"""distutils.msvc9compiler
Contains MSVCCompiler, an implementation of the abstract CCompiler class
for the Microsoft Visual Studio 2008.
The module is compatible with VS 2005 and VS 2008. You can find legacy support
for older versions of VS in distutils.msvccompiler.
"""
import os
import subp... |
import sys, os, arcgisscripting, subprocess
def check_output(command,console):
if console == True:
process = subprocess.Popen(command)
else:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
output,error = process.commu... |
import cv2
import pickle as pickle
class Rectify:
def __init__(self, path=None):
if not path:
path = "calibrate.pkl"
self.cdata = pickle.load(open(path, "rb"))
def rectify(self, img):
return cv2.remap(img, self.cdata['mapx'], self.cdata['mapy'], cv2.INTER_LINEAR)
if __name__ ... |
from sopel import *
import random
from itertools import repeat
@module.rule('.[Aa][Ll][Pp][Ii][Nn][Ee].*')
def alpine(bot, trigger):
bot.say('FUCK TAD') |
from discord import Client
from discord.errors import Forbidden
from moneybot import config
from moneybot.command import get_command
from moneybot.exc import InvalidCommand, MoneybotException
from moneybot.ledger import update_balance, get_user_balance, transfer_balance
import discord
client = Client()
def get_contents... |
"""Objects representing api tokens."""
from pywikibot import debug
from pywikibot.exceptions import Error
_logger = 'site.tokenwallet'
class TokenWallet:
"""Container for tokens."""
def __init__(self, site) -> None:
"""Initializer.
:type site: pywikibot.site.APISite
"""
self.site... |
from nose.tools import eq_, assert_not_equal
import inflect
def is_eq(p, a, b):
return (p.compare(a, b) or
p.plnounequal(a, b) or
p.plverbequal(a, b) or
p.pladjequal(a, b))
def test_many():
p = inflect.engine()
data = get_data()
for line in data:
if 'TODO:' in... |
turnsignal_min = 0
turnsignal_max = 255
turnsignal_step = 15
turnsignal_delay = 0.1
brakelight_min = 75
brakelight_max = 255
brakelight_step = 100
brakelight_delay = 0.1
def input_turnr(key): # returns the state of the right turn input
if key == 77: # (right arrow)
return 1
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.