content string |
|---|
from __future__ import print_function, unicode_literals, division
from idd3 import Relation, Ruleset, config
from idd3.rules.universal.np_rulesets import NounPhraseRuleset
from idd3.rules.universal.vp_rulesets import VerbPhraseRuleset
from idd3.rules.universal.adjp_rulesets import AdjectivalPhraseRuleset
import loggin... |
import sys
try:
import settings
import utils
except:
from . import (settings, utils)
# XXX This is a quick hack to make it work with new I18n... objects! To be reworked!
def main():
import argparse
parser = argparse.ArgumentParser(description=""
"Merge one or more .po files in... |
from __future__ import unicode_literals
import webnotes
import webnotes.defaults
@webnotes.whitelist()
def get_roles_and_doctypes():
webnotes.only_for(("System Manager", "Administrator"))
return {
"doctypes": [d[0] for d in webnotes.conn.sql("""select name from `tabDocType` dt where
ifnull(istable,0)=0 and
n... |
import json
from unittest import mock
from urllib.parse import quote_plus, urlparse
import pyodbc
from airflow.models import Connection
from airflow.providers.odbc.hooks.odbc import OdbcHook
class TestOdbcHook:
def get_hook(self=None, hook_params=None, conn_params=None):
hook_params = hook_params or {}
... |
import json
import logging
import os
import pytz
import requests
import sys
import urllib.request, urllib.parse, urllib.error
import time
if os.path.dirname(__file__) == "matrixbot/plugins":
sys.path.append(os.path.abspath("."))
from matrixbot import utils
pp, puts, set_property = utils.pp, utils.puts, utils.set... |
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.contrib.auth.models import User
class DmUser(models.Model):
user=models.ForeignKey(User,unique=True,related_name='dm_user')
last_activity=models.DateTimeField(auto_now_add=True)
contacts=models.ManyToManyField(User,rel... |
import time
import os
import re
import sys
from twisted.web.resource import Resource
from buildbot.status.web import baseweb
from buildbot.status.builder import FAILURE, SUCCESS, WARNINGS
class XmlResource(Resource):
contentType = "text/xml; charset=UTF-8"
def render(self, request):
data = self.conte... |
#!/usr/bin/env python
# encoding: utf-8
"""
Example of creating a block model using the blockmodel function in NX. Data used is the Hartford, CT drug users network:
@article{,
title = {Social Networks of Drug Users in {High-Risk} Sites: Finding the Connections},
volume = {6},
shorttitle = {Social Networks of Drug ... |
"""Reads, parses, and (optionally) writes as HTML the contents of Markdown
files passed as arguments. Intended for rendering network stack documentation
stored as Markdown in the source tree to a human-readable format."""
import argparse
import os.path
import sys
def nth_parent_directory(path, n):
for i in range(... |
from rest_framework import serializers
from models import Condominio, Edificio, Departamento, Servicio, LecturaServicio
from models import AdministradorEdificio, Conserje
class ConserjeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Conserje
class AdministradorEdificioSerializer... |
import os
import urlparse
import hashlib
try:
import boto
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def grant_check(module, gs, obj):
try:
acp = obj.get_acl()
if module.params.get('permission') == 'public-read':
grant = [ x for x in acp.entries.entry_list if x.sc... |
'''
Bitcoin base58 encoding and decoding.
Based on https://bitcointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return byte... |
# -*- coding: utf-8 -*-
"""
"""
from __future__ import absolute_import
from ._utils import _cd
from ..unitquantity import UnitConstant
natural_unit_of_action = UnitConstant(
'natural_unit_of_action',
_cd('natural unit of action'),
symbol='hbar',
u_symbol='ħ'
)
natural_unit_of_energy = UnitConstant(
... |
from zeobuilder import context
from molmod.data.periodic import periodic
from molmod.data.bonds import bonds, BOND_SINGLE, BOND_DOUBLE, BOND_TRIPLE
import molmod.units
class Expression(object):
l = {
"periodic": periodic,
"bonds": bonds,
"BOND_SINGLE": BOND_SINGLE,
"BOND_DOUBLE":... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
#!/opt/anaconda1anaconda2anaconda3/bin/python
#
# Wrapper script for DeepVariant call_variants
BINARY_DIR="/opt/anaconda1anaconda2anaconda3/BINARYSUB"
MODEL_DIRS= {"wgs": "/opt/anaconda1anaconda2anaconda3/WGSMODELSUB",
"wes": "/opt/anaconda1anaconda2anaconda3/WESMODELSUB"}
import argparse
import os
impor... |
import json
from django.contrib.postgres import forms
from django.contrib.postgres.fields.array import ArrayField
from django.core import exceptions
from django.db.models import Field, Lookup, Transform, TextField
from django.utils import six
from django.utils.translation import ugettext_lazy as _
__all__ = ['HStore... |
# -*- coding: utf-8 -*-
import re
from ..base.xfs_account import XFSAccount
class UptoboxCom(XFSAccount):
__name__ = "UptoboxCom"
__type__ = "account"
__version__ = "0.25"
__status__ = "testing"
__description__ = """Uptobox.com account plugin"""
__license__ = "GPLv3"
__authors__ = [
... |
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'community',
'version': '1.0'}
import base64
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackZoneFacts(AnsibleCloudStack):
def __init__(self, module):
... |
import logging
import sys
import mock
import os
from pytest import fixture
from mock import patch, call
import kiwi
from ..test_helper import argv_kiwi_tests
from kiwi.tasks.system_build import SystemBuildTask
class TestSystemBuildTask:
@fixture(autouse=True)
def inject_fixtures(self, caplog):
self... |
'''Collections of messages and their translations, called cliques. Also
collections of cliques (uber-cliques).
'''
import re
import types
from grit import constants
from grit import exception
from grit import lazy_re
from grit import pseudo
from grit import pseudo_rtl
from grit import tclib
class UberClique(object... |
"""
Tests of ModelAdmin system checks logic.
"""
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Album(models.Model):
title = models.CharFie... |
data = (
'ddwim', # 0x00
'ddwib', # 0x01
'ddwibs', # 0x02
'ddwis', # 0x03
'ddwiss', # 0x04
'ddwing', # 0x05
'ddwij', # 0x06
'ddwic', # 0x07
'ddwik', # 0x08
'ddwit', # 0x09
'ddwip', # 0x0a
'ddwih', # 0x0b
'ddyu', # 0x0c
'ddyug', # 0x0d
'ddyugg', # 0x0e
'ddyugs', # 0x0f
'dd... |
"""
Utility classes for dealing with circular references.
"""
from twisted.python import log, reflect
try:
from new import instancemethod
except:
from org.python.core import PyMethod
instancemethod = PyMethod
class NotKnown:
def __init__(self):
self.dependants = []
self.resolved = 0
... |
from openerp import SUPERUSER_ID
from openerp.osv import osv
class crm_claim(osv.osv):
_inherit = "crm.claim"
def _get_default_partner_id(self, cr, uid, context=None):
""" Gives default partner_id """
if context is None:
context = {}
if context.get('portal'):
u... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from .brightcove import BrightcoveLegacyIE
from ..compat import (
compat_parse_qs,
compat_urlparse,
)
from ..utils import smuggle_url
class RMCDecouverteIE(InfoExtractor):
_VALID_URL = r'https?://rmcdecou... |
"""MovieLens data handling: download, parse, and expose as DataIter
"""
import os
import mxnet as mx
def load_mldata_iter(filename, batch_size):
"""Not particularly fast code to parse the text file and load it into three NDArray's
and product an NDArrayIter
"""
user = []
item = []
score = []
... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from rompy import rompy, plot_utils, utils
map1 = False
map2 = False
map3 = False
map4 = False
map5 = False
map6 = False
map7 = Fa... |
# encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Institute'
db.create_table('institute', (
('gid', self.gf('django.db.models.fields.IntegerField')()),
... |
import mock
from cinder import exception
from cinder import test
from cinder.tests.unit.volume.drivers.emc.vnx import fake_exception \
as storops_ex
from cinder.tests.unit.volume.drivers.emc.vnx import fake_storops as storops
from cinder.tests.unit.volume.drivers.emc.vnx import res_mock
from cinder.tests.unit.volu... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import datetime
import json
import logging
import mock
import zlib
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.utils import timezone
from gzip i... |
"""
Integration tests for importing courses containing pure XBlocks.
"""
from django.conf import settings
from xblock.core import XBlock
from xblock.fields import String
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.mongo.draft import as_dr... |
"""Something just to look at via pydoc."""
import types
class A_classic:
"A classic class."
def A_method(self):
"Method defined in A."
def AB_method(self):
"Method defined in A and B."
def AC_method(self):
"Method defined in A and C."
def AD_method(self):
"Method de... |
from neutron.common import constants
from neutron.objects.qos import policy
from neutron.objects.qos import rule
from neutron.services.qos import qos_consts
from neutron.tests import base as neutron_test_base
from neutron.tests.unit.objects import test_base
from neutron.tests.unit import testlib_api
POLICY_ID_A = 'pol... |
from __future__ import print_function
import logging
import textwrap
import portage
from portage import os
from portage.emaint.modules.logs.logs import CleanLogs
from portage.news import count_unread_news, display_news_notifications
from portage.output import colorize
from portage.util._dyn_libs.display_preserved_lib... |
"""Gluon Batch Processor for Estimators"""
from ...utils import split_and_load
from .... import autograd
__all__ = ['BatchProcessor']
class BatchProcessor(object):
"""BatchProcessor Class for plug and play fit_batch & evaluate_batch
During training or validation, data are divided into minibatches for proces... |
#! /usr/bin/python2
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import sys
first = True
s = 2e-5
eta_contour_levels = np.append(np.arange(-1e-4, 0, s), np.arange(s, 1e-4, s))
zoom_lat = True
zoom_lat = False
zoom_lat = 'eta' in sys.argv[1]
fontsize=8
figsize=(9, 3)... |
# -*- coding: utf-8 -*-
"""
pygments.styles.algol_nu
~~~~~~~~~~~~~~~~~~~~~~~~
Algol publication style without underlining of keywords.
This style renders source code for publication of algorithms in
scientific papers and academic texts, where its format is frequently used.
It is based on the ... |
#!/usr/bin/env python
"""
Reorder the integer arguments to the commands in a LAMMPS input
file if these arguments violate LAMMPS order requirements.
We have to do this because the moltemplate.sh script will automatically
assign these integers in a way which may violate these restrictions
and the user ha... |
import os
import imp
import random
import string
import sys
import logging
from threading import Lock
from ycmd import user_options_store
from ycmd.responses import UnknownExtraConf, YCM_EXTRA_CONF_FILENAME
from fnmatch import fnmatch
# Singleton variables
_module_for_module_file = {}
_module_for_module_file_lock = L... |
"""
Draws dolphins using matplotlib features.
From matplotlib documentation:
https://matplotlib.org/gallery/shapes_and_collections/dolphin.html#sphx-glr-gallery-shapes-and-collections-dolphin-py
"""
# Fixing random state for reproducibility
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.pa... |
from __future__ import absolute_import
import inspect
import warnings
class RemovedInDjango20Warning(PendingDeprecationWarning):
pass
class RemovedInDjango110Warning(DeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInDjango110Warning
class warn_about_renamed_method(object):
def __init... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
''' Fail with custom message '''
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=dict()):
msg = 'Failed as requested fr... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from cms.models import Page
from cms.service import init_page
class TestService(TestCase):
def setUp(self):
self.SLUG = 'home'
self.HOME = 'Home'
def test_init_not(self):
try:
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import test
try:
import unittest2 as unittest
except ImportError:
import unittest
import yamlish
test_data_list = [
{
"name": "Input test",
"in": r"""---
bill-to:
address:
city: "Royal Oak"
... |
import os, sys
from codecs import EncodedFile
from calibre.ebooks.rtf2xml import copy, check_encoding
from calibre.ptempfile import better_mktemp
public_dtd = 'rtf2xml1.0.dtd'
class ConvertToTags:
"""
Convert file to XML
"""
def __init__(self,
in_file,
bug_handler,
... |
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'core',
'version': '1.0'}
import grp
import platform
class Group(object):
"""
This is a generic Group manipulation class that is subclassed
based on platform.
A subclass may wish to override the... |
"""
Common base classes for devices
"""
import logging
from six import StringIO
from virttest import xml_utils
from virttest.libvirt_xml import base, xcepts, accessors
from virttest.xml_utils import ElementTree
class UntypedDeviceBase(base.LibvirtXMLBase):
"""
Base class implementing common functions for a... |
import numpy as np
import math
import cv2
import itertools as it
import sys
import time
import helping_functs as hf
import class_objects as co
def detect_corners():
'''function to detects intersection limits of mask with calib_edges'''
calib_set = set([tuple(i) for i in np.transpose(
np.fliplr(np.non... |
"""Tests for samba.registry."""
import os
from samba import registry
import samba.tests
class HelperTests(samba.tests.TestCase):
def test_predef_to_name(self):
self.assertEquals("HKEY_LOCAL_MACHINE",
registry.get_predef_name(0x80000002))
def test_str_regtype(self):
... |
"""
Acceptance tests for Studio's Setting pages
"""
from .base_studio_test import StudioCourseTest
from ...pages.studio.settings_certificates import CertificatesPage
class CertificatesTest(StudioCourseTest):
"""
Tests for settings/certificates Page.
"""
def setUp(self, is_staff=False):
super(C... |
# @ut.accepts_scalar_input2(argx_list=[1])
# def get_obj(depc, tablename, root_rowids, config=None, ensure=True):
# """ Convinience function. Gets data in `tablename` as a list of
# objects. """
# print('WARNING EXPERIMENTAL')
# try:
# if tablename == depc.root:
# obj_list = list(dep... |
#-*- coding: utf-8 -*-
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User, Permission # NOQA
from django.contrib.auth.models import Group
from django.core.files import File as DjangoFile
from django.conf import setting... |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2010 (ita)
"""
Utilities and platform-specific fixes
The portability fixes try to provide a consistent behavior of the Waf API
through Python versions 2.3 to 3.X and across different platforms (win32, linux, etc)
"""
import os, sys, errno, traceback, inspec... |
from past.builtins import basestring
from pyramid.threadlocal import manager as threadlocal_manager
def get_root_request():
if threadlocal_manager.stack:
return threadlocal_manager.stack[0]['request']
def ensurelist(value):
if isinstance(value, basestring):
return [value]
return value
... |
"""Helper functions for enqueuing data from arrays and pandas `DataFrame`s."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import random
import numpy as np
from tensorflow.contrib.learn.python.learn.dataframe.queues import feeding_qu... |
import socket
from django.core.mail import mail_admins, mail_managers, send_mail
from django.core.management.base import BaseCommand
from django.utils import timezone
class Command(BaseCommand):
help = "Sends a test email to the email addresses specified as arguments."
missing_args_message = "You must specif... |
"""Integration tests for notification command."""
from __future__ import absolute_import
import re
import uuid
import boto
import gslib.tests.testcase as testcase
from gslib.tests.util import ObjectToURI as suri
from gslib.tests.util import unittest
def _LoadNotificationUrl():
return boto.config.get_value('GSUt... |
import io
from jinja2 import Template
from bokeh.embed import components
from bokeh.models import Range1d
from bokeh.plotting import figure
from bokeh.resources import INLINE
from bokeh.util.browser import view
# create some data
x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
y1 = [0, 8, 2, 4, 6, 9, 5, 6, 25, 28, 4, 7]... |
# -*- coding: utf-8 -*-
"""
This module contains tests for the pulp.server.db.model.consumer module.
"""
import unittest
import mock
from ....base import PulpServerTests
from pulp.server.db.model import consumer
class TestRepoProfileApplicability(PulpServerTests):
"""
Test the RepoProfileApplicability Mode... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.titl... |
""" These are the standard themes that come with Pyflag. """
import pyflag.conf
config=pyflag.conf.ConfObject()
import pyflag.FlagFramework as FlagFramework
import pyflag.Registry as Registry
import pyflag.Theme as Theme
class BlueTheme(Theme.BasicTheme):
""" This class encapsulates the theme elements. The results... |
import logging
import re
from typing import TYPE_CHECKING, Awaitable, Callable, Dict, List, Optional
from synapse.api.errors import Codes, LoginError, SynapseError
from synapse.api.ratelimiting import Ratelimiter
from synapse.api.urls import CLIENT_API_PREFIX
from synapse.appservice import ApplicationService
from syna... |
# -*- coding: utf-8 -*-
"""
pyspecific.py
~~~~~~~~~~~~~
Sphinx extension with Python doc-specific markup.
:copyright: 2008-2014 by Georg Brandl.
:license: Python license.
"""
ISSUE_URI = 'http://bugs.python.org/issue%s'
SOURCE_URI = 'https://hg.python.org/cpython/file/3.4/%s'
from ... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
def create_vmkernel_adapter(host_system, port_group_name,
... |
#! /usr/bin/python
# Tool for visualizing quaternion as rotated cube
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import sys
import math
from ivy.std_api import *
import logging
import getopt
import pygame
import time
import platform
import os
_NAME = 'attitude_viz'
class TelemetryQ... |
"""
This module is the heart of the upnp support. Device discover, ip discovery
and port mappings are implemented here.
@author: Raphael Slinckx
@author: Anthony Baxter
@copyright: Copyright 2005
@license: LGPL
@contact: U{<EMAIL><mailto:<EMAIL>>}
@version: 0.1.0
"""
__revision__ = "$id"
import socket, random, urlpar... |
import os, unittest
from ctypes import *
try:
WINFUNCTYPE
except NameError:
# fake to enable this test on Linux
WINFUNCTYPE = CFUNCTYPE
import _ctypes_test
lib = CDLL(_ctypes_test.__file__)
class CFuncPtrTestCase(unittest.TestCase):
def test_basic(self):
X = WINFUNCTYPE(c_int, c_int, c_int)
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_appsvcs_extension
short_description: Manage applicati... |
# coding: utf-8
""" Config, Date, User and Exceptions """
from __future__ import unicode_literals, absolute_import
import os
import re
import sys
import codecs
import datetime
import optparse
import StringIO
import xmlrpclib
import ConfigParser
from dateutil.relativedelta import MO as MONDAY
from ConfigParser import... |
# -*- coding: utf-8 -*-
import re
from odoo import api, models, _
from odoo.exceptions import UserError, ValidationError
def normalize_iban(iban):
return re.sub('[\W_]', '', iban or '')
def pretty_iban(iban):
""" return iban in groups of four characters separated by a single space """
return ' '.join([... |
#!/usr/bin/env python
from __future__ import print_function
import os
import re
import boto
from boto.s3.connection import S3Connection
from boto.iam.connection import IAMConnection
import inquirer
key_policy_json = """{
"Statement": [
{
"Action": "iam:*AccessKey*",
"Effect": "Allow",
"Resour... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import get_capabilities, nxos_argument_spec
from ansible.mod... |
#!/usr/bin/env python
import sys
import pmt
from gnuradio.ctrlport.GNURadioControlPortClient import GNURadioControlPortClient
from optparse import OptionParser
parser = OptionParser(usage="%prog: [options]")
parser.add_option("-H", "--host", type="string", default="localhost",
help="Hostname to conn... |
import numba
@numba.jit(['f8(f8[:, :])'], nopython=True, nogil=True, cache=True)
def polygon_area(vertices):
r"""Shoelace formula for computing area of polygon
.. math::
A = \sum_{i=1}^{n} x_i \left(y_{i+1} - y_{i-1}\right), \quad i\mod n
References:
- https://en.wikipedia.org/wiki/Shoel... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.common import Backend
from lib.core.common import readInput
from lib.core.data import logger
from lib.core.enums import OS
from lib.core.exception import SqlmapU... |
"""Execute files of Python code."""
import imp, marshal, os, sys
from coverage.backward import exec_code_object, open_source
from coverage.misc import ExceptionDuringRun, NoCode, NoSource
try:
# In Py 2.x, the builtins were in __builtin__
BUILTINS = sys.modules['__builtin__']
except KeyError:
# In Py 3.... |
from django.db import models
from django.conf import settings
User = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class PinCard(models.Model):
token = models.CharField(max_length=32, db_index=True, editable=False)
display_number = models.CharField(max_length=20, editable=False)
expiry_month = models... |
import unittest
from tornado.options import define, options
from m2core.utils.tests import RESTTest
from m2core.utils.data_helper import DataHelper
from m2core import M2Core
from m2core.bases import http_statuses
from tornado.escape import json_decode
from example.models import User
# init empty object to pass it thr... |
"""Production settings and globals."""
from os import environ
from base import *
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConfigured
def get_env_setting(setting):
""" Get the envi... |
import datetime as dt
from flask_login import UserMixin
from news_website.extensions import db, bcrypt
from news_website.database import (
Column,
Model,
ReferenceCol,
relationship,
SurrogatePK,
)
class User(UserMixin, SurrogatePK, Model):
__tablename__ = 'users'
username = Column(db.Str... |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import socket
import struct
import re
import logging
from shadowsocks import common, lru_cache, eventloop, shell
CACHE_SWEEP_INTERVAL = 30
VALID_HOSTNAME = re.compile(br"(?!-)[A-Z\d\-_]{1,63}(?<!-)$", re.IGNORECASE)
c... |
"""
tweet_read.py
Serve tweets to a socket for spark-streaming.
Adapted from:
http://www.awesomestats.in/spark-twitter-stream/
"""
import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
import socket
import json
import logging
logger = logging.getLog... |
from modules import AbstractModule
from kernel.output import Output
import hashlib
class Hash(AbstractModule):
def is_collect_data(self) -> bool:
return True
def check(self):
return True
def description(self) -> str:
return "A module which collects data about file hashes"
de... |
import unittest
from ctypes import *
from struct import calcsize
class SubclassesTest(unittest.TestCase):
def test_subclass(self):
class X(Structure):
_fields_ = [("a", c_int)]
class Y(X):
_fields_ = [("b", c_int)]
class Z(X):
pass
self.assertE... |
import urllib
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
json = None
def do_request(module, url, params, headers=None):
data = urllib.urlencode(params)
if headers is None:
headers = dict()
headers = dict(headers, **{
... |
"""
This module adds shared support for generic api modules
In order to use this module, include it as part of a custom
module as shown below.
The 'api' module provides the following common argument specs:
* rate limit spec
- rate: number of requests per time unit (int)
- rate_limit: time window ... |
from __future__ import unicode_literals
import os
from django import forms
from django.test import TestCase
from django.test.client import RequestFactory
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.formto... |
# -*- coding: utf-8 -*-
import sys
import os
import json
import glob
sys.path.append(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'../python/ext-libs'))
cpp = open(sys.argv[1], "w", encoding="utf-8")
cpp.write(
"#include \"qgsexpression.h\"\n"
"#include \"qgsexpression_p.h\... |
from deluge.ui.client import client
from popup import SelectablePopup, Popup
from input_popup import InputPopup
import deluge.component as component
from deluge.ui.console import colors, modes
from twisted.internet import defer
import logging
log = logging.getLogger(__name__)
torrent_options = [
("max_download_s... |
"""
Given a continuous time first order transfer function of the form:
n1 * s + n0
-----------
s + d0
Compute the Tustin approximation and return a state space realization of this
discrete time transfer function.
"""
from sympy import symbols, Poly, ccode, S, sqrt
def discrete_realization_tustin(n0, n1... |
from django.dispatch.saferef import *
from django.utils import unittest
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class Tester(unittest.TestCase):
def setUp(self):
ts = []
ss = []
for x in x... |
import re
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.middleware.csrf import rotate_token
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_... |
"""
=========================
Kernel Density Estimation
=========================
This example shows how kernel density estimation (KDE), a powerful
non-parametric density estimation technique, can be used to learn
a generative model for a dataset. With this generative model in place,
new samples can be drawn. These... |
""" Matrix Screen Effect
(c) 2016, Leif Theden, <EMAIL>
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.
... |
"""Load / save to libwww-perl (LWP) format files.
Actually, the format is slightly extended from that used by LWP's
(libwww-perl's) HTTP::Cookies, to avoid losing some RFC 2965 information
not recorded by LWP.
It uses the version string "2.0", though really there isn't an LWP Cookies
2.0 format. This indicates that ... |
"""Setup links to a Chromium checkout for Libyuv.
Libyuv shares a lot of dependencies and build tools with Chromium.
To do this, many of the paths of a Chromium checkout is emulated by creating
symlinks to files and directories. This script handles the setup of symlinks to
achieve this.
It's a modified copy of the si... |
import enum
from citext import CIText
from sqlalchemy import (
CheckConstraint,
Column,
Enum,
ForeignKey,
Index,
UniqueConstraint,
Boolean,
DateTime,
Integer,
String,
)
from sqlalchemy import orm, select, sql
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm.ex... |
#!/usr/bin/python
import __main__
import json
#===================================================================================================================
#PLUGIN CALLS
async def help_menu():
help_info = {}
help_info['title'] = 'Message log'
help_info['description'] = 'Search logged messages.'
... |
#!/usr/bin/env python
# This will create golden files in a directory passed to it.
# A Test calls this internally to create the golden files
# So it can process them (so we don't have to checkin the files).
import msgpack, msgpackrpc, sys, os, threading
def get_test_data_list():
# get list with all primitive typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.