code stringlengths 1 199k |
|---|
from __future__ import unicode_literals
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_INFIXES
from .stop_words import STOP_WORDS
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...attrs import LANG
from ...language import Language
from... |
ID_FIELD = '_id'
ITEM_LOOKUP = True
ITEM_LOOKUP_FIELD = ID_FIELD
ITEM_URL = 'regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")'
GRAPH_DATABASE = 'http://graph:7474/db/data/'
GRAPH_USER = 'neo4j'
GRAPH_PASSWORD = 'admin'
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'DE... |
def readx64( path):
shellcode = r"\xeb\x3f\x5f\x80\x77\x0b\x41\x48\x31\xc0\x04\x02\x48\x31"
shellcode += r"\xf6\x0f\x05\x66\x81\xec\xff\x0f\x48\x8d\x34\x24\x48\x89"
shellcode += r"\xc7\x48\x31\xd2\x66\xba\xff\x0f\x48\x31\xc0\x0f\x05\x48"
shellcode += r"\x31\xff\x40\x80\xc7\x01\x48\x89\xc2\x48\x31\xc0\x04\x01"
she... |
from drf_hal_json.serializers import HalModelSerializer
from .models import TestResource, RelatedResource2, RelatedResource1
class TestResourceSerializer(HalModelSerializer):
class Meta:
model = TestResource
fields = ('id', 'name', 'related_resource_1')
nested_fields = {
'related... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/shield_generator/shared_shd_koensayr_deflector_advanced.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","shd_koensayr_deflector_advanced_n")
#### BEGIN MODIFICATIONS ####
#... |
"""
The MIT License (MIT)
Copyright (c) 2015-2017 Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, pu... |
"""
генератор случайных чисел
"""
import random
str1 = '123456789'
str2 = 'qwertyuiopasdfghjklzxcvbnm'
str3 = str2.upper()
print str3
str4 = str1+str2+str3
print str4
ls = list(str4)
random.shuffle(ls)
psw = ''.join([random.choice(ls) for x in range(12)])
print psw |
from msrest.serialization import Model
class ServerUpdateParameters(Model):
"""Parameters allowd to update for a server.
:param sku: The SKU (pricing tier) of the server.
:type sku: :class:`Sku <azure.mgmt.rdbms.mysql.models.Sku>`
:param storage_mb: The max storage allowed for a server.
:type storag... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='job',
name='content',
field=models.TextFi... |
"""
Given a JSON file, return just the text of the tweet.
Example usage:
utils/tweet_text.py tweets.jsonl > tweets.txt
"""
from __future__ import print_function
import json
import fileinput
for line in fileinput.input():
tweet = json.loads(line)
if "full_text" in tweet:
print(tweet["full_text"].encode("... |
class Coordinate:
def __init__(self, x, y):
self.set_coord(x, y)
def _check_coord(self, val):
return isinstance(int, val) and val >= 0
def get_coord(self):
return (self._x, self._y)
def set_coord(self, coord):
x, y = coord
if self._check_coord(x):
self... |
import asyncio, asyncssh, sys
class MySSHClientSession(asyncssh.SSHClientSession):
def data_received(self, data, datatype):
print(data, end='')
def connection_lost(self, exc):
if exc:
print('SSH session error: ' + str(exc), file=sys.stderr)
@asyncio.coroutine
def run_client():
wi... |
from __future__ import absolute_import
from __future__ import unicode_literals
from dnf.cli import commands
from dnf.cli.option_parser import OptionParser
from dnf.i18n import _
class DowngradeCommand(commands.Command):
"""A class containing methods needed by the cli to execute the
downgrade command.
"""
... |
'''
Created on May 26, 2012
@author: victor
'''
import glob
import re
import sys
import os
import fnmatch
import string
def matchStrInFile(str,filename):
if filename == "./rebrand.py":
return
file = open(filename,'r')
fileTxt = file.read()
replaced = fileTxt
for x in str:
replaced = ... |
from astrometry.util.fits import fits_table
import numpy as np
'''
This is a little script for merging Aaron's astrometric offsets into our
WISE tile file.
'''
W = fits_table('legacypipe/data/wise-tiles.fits')
offsets = fits_table('fulldepth_neo4_index.fits')
off1 = offsets[offsets.band == 1]
off2 = offsets[offsets.ban... |
from runtest import TestBase
import subprocess as sp
TDIR='xxx'
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'sort', """
Avg self Min self Max self Function
========== ========== ========== ====================================
1.078 ms 1.078 ms 1.078 ms us... |
from __future__ import print_function
from __future__ import absolute_import
from Components.ActionMap import ActionMap, HelpableActionMap
from Components.ServiceEventTracker import ServiceEventTracker
from Components.config import config
from Components.SystemInfo import BoxInfo
from Components.Task import job_manager... |
'''
Created on Jun 12, 2015
@author: s1m0n4
@copyright: 2015 s1m0n4 for hookii.it
'''
import unittest
import os
import sys
libs = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../'))
sys.path.append(libs)
from utils import *
class Utils(unittest.TestCase):
def test_datetimestr_t... |
from __future__ import absolute_import
from __future__ import division
import logging
import os
import signal
import sys
def panic(msg):
try:
logging.exception("Panic: %s", msg)
# Depends on SIGALRM handler register during startup.
signal.alarm(10)
logging.shutdown()
finally:
... |
import os
import tuned.logs
from . import base
from tuned.utils.commands import commands
class execute(base.Function):
"""
Executes process and substitutes its output.
"""
def __init__(self):
# unlimited number of arguments, min 1 argument (the name of executable)
super(execute, self).__init__("exec", 0, 1)
de... |
"""
Manages adding, removing, resizing and drawing the canvas
The Canvas is the main area in Conduit, the area to which DataProviders are
dragged onto.
Copyright: John Stowers, 2006
License: GPLv2
"""
import cairo
import goocanvas
import gtk
import pango
from gettext import gettext as _
import logging
log = logging.get... |
import os.path
import shutil
from zipfile import ZipFile, ZIP_DEFLATED, ZIP_STORED
from datetime import datetime
from xcsoar.mapgen.waypoints import welt2000
from xcsoar.mapgen.terrain import srtm
from xcsoar.mapgen.topology import shapefiles
from xcsoar.mapgen.georect import GeoRect
from xcsoar.mapgen.filelist import ... |
from __future__ import print_function
import os
import sys
import glob
import pwd
import time
import shutil
import getpass
from certs.sslToolCli import processCommandline, CertExpTooShortException, \
CertExpTooLongException, InvalidCountryCodeException
from certs.sslToolLib import RhnSslToolException, \
... |
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
lin = nn.Linear(5, 3)
data = autograd.Variable(torch.randn(2, 5))
print(lin(data)) |
"""BibCatalog db layer."""
from invenio.legacy.dbquery import run_sql
def get_all_new_records(since, last_id):
"""
Get all the newly inserted records since last run.
"""
# Fetch all records inserted since last run
sql = "SELECT id, creation_date FROM bibrec " \
"WHERE creation_date >= %s " \... |
"""This module contains the classes that represent Telegram
InlineQueryResultCachedDocument"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
class InlineQueryResultCachedDocument(InlineQueryResult):
def __init__(self,
id,
title,
... |
"""
High-level QEMU test utility functions.
This module is meant to reduce code size by performing common test procedures.
Generally, code here should look like test code.
More specifically:
- Functions in this module should raise exceptions if things go wrong
- Functions in this module typically use functions ... |
import psycopg2
def search(term,size,cur,conn):
try:
cur.execute("""
select URL, title from (
select URL, title, text_vals
from SEARCHABLE, plainto_tsquery(%s) AS q
where (text_vals @@ q)
)
AS Results ORDER BY ts_rank_cd(Results.text_vals, plainto_tsquery(%s)) desc limit %s;
""", (term,term,size)... |
"""
Maps the different status strings in avocado to booleans.
This is used by methods and functions to return a cut and dry answer to whether
a test or a job in avocado PASSed or FAILed.
"""
mapping = {"SKIP": True,
"ABORT": False,
"ERROR": False,
"FAIL": False,
"WARN": True,... |
import inspect
import sqlite3
import time
import traceback
import sqlalchemy as sa
from twisted.internet import defer
from twisted.internet import threads
from twisted.python import log
from twisted.python import threadpool
from buildbot.db.buildrequests import AlreadyClaimedError
from buildbot.db.buildsets import Alre... |
import os
import subprocess
import sys
import paths
def main():
env = os.environ.copy()
if sys.platform == 'darwin':
env['DYLD_LIBRARY_PATH'] = paths.topbuilddir + '/lib/.libs'
env['DYLD_INSERT_LIBRARIES'] = paths.build + \
'/.libs/libgroups_preload.dylib'
... |
import logging
import globals
from award_classification import AwardType
from datastore_classes import TeamEvent, team_event_key, team_key, lineup_key, Lineup, choice_key, account_key
from progress_through_elimination_classification import UNDETERMINED, DIDNTQUALIFY, QUARTERFINALIST, SEMIFINALIST, FINALIST, WINNER
"""U... |
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
from m5.util import addToPath
from Ruby import create_topology
from Ruby import send_evicts
addToPath('../')
from topologies.Cluster import Cluster
from topologies.Crossbar import Crossbar
class CntrlBase:
_seqs = 0
@classmethod
... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SourceDataVersion.elements'
db.add_column(u'data_drivers_sourcedataversion', 'elements',
self.gf(... |
from __future__ import print_function
import json
import argparse
import pyalveo
import os
from urlparse import urlparse
def parser():
parser = argparse.ArgumentParser(description="Downloads documents in an Alveo Item List")
parser.add_argument('--api_key', required=True, action="store", type=str, help="Alveo A... |
from decksite.data import elo
def test_elo() -> None:
assert elo.expected(elo.STARTING_ELO, elo.STARTING_ELO) == 0.5
assert elo.expected(10000, 1) > 0.99
assert elo.expected(1, 10000) < 0.01
assert elo.adjustment(elo.STARTING_ELO, elo.STARTING_ELO) == elo.K_FACTOR / 2
assert elo.adjustment(10000, 1)... |
model_name = 'my_model'
simulation_size = 20
random_seed = 1
def setup_model(model):
"""Write initialization steps here.
e.g. ::
model.put([0,0,0,model.lattice.default_a], model.proclist.species_a)
"""
#from setup_model import setup_model
#setup_model(model)
pass
hist_length = 30
paramete... |
import socket
hostname = socket.gethostname().split('.')[0]
config = {
# Consumer stuff
"bugyou.consumer.enabled": True,
# Turn on logging for bugyou
"logging": dict(
loggers=dict(
bugyou={
"level": "DEBUG",
"propagate": False,
"handler... |
import os
from buildbot.status.html import WebStatus
from buildbot.status.web.authz import Authz
from buildbot.status.web.auth import BasicAuth
from buildbot.schedulers import basic
from buildbot.schedulers.basic import SingleBranchScheduler
from buildbot.buildslave import BuildSlave
from buildbot.process.factory impor... |
'''Some helper functions for testing'''
import sys
import os
import binascii
import random
from decimal import Decimal
data_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, os.path.join(data_dir))
from jmbase import get_log
from jmclient import open_test_wallet_maybe, BIP32Wallet, S... |
from ImageScripter import *
from elan import *
Say("Checking the layout page")
Configurator.layout.Click()
Configurator.layoutpage.SetThreshold(.98)
Configurator.layoutpage.Wait(seconds=10)
Say("Checking the layout page looks great")
Configurator.buildings.Click()
Configurator.buildingspage.SetThreshold(.98)
Configurat... |
"""
Conversion functions for fossils
"""
from collections import defaultdict
import pytz
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
class Conversion(object):
@classmethod
def datetime(cls, dt, tz=None, convert=False):
if dt:
if tz:
if i... |
import euphoria.utils as ut
import dumper
import time
class NotificationManager(dumper.Dumper):
def __init__(self, dumpfile, groups):
super().__init__(dumpfile)
self.messages = dict()
self.groups = groups
def create_notification(self, user, to, sender, message, timestamp):
"""
... |
from .hashable import HashableObject
class Alignment(HashableObject):
"""Alignment options for use in styles."""
HORIZONTAL_GENERAL = 'general'
HORIZONTAL_LEFT = 'left'
HORIZONTAL_RIGHT = 'right'
HORIZONTAL_CENTER = 'center'
HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous'
HORIZONTAL_JUSTIF... |
"""
ciefunctions: GUI application for the calculation of the CIE
cone-fundamental-based colorimetric functions provided
by CIE TC 1-97.
Copyright (C) 2012-2020 Ivar Farup and Jan Henrik Wold
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Ge... |
from __future__ import with_statement
from sympy.core import Symbol, S, Rational, Integer
from sympy.utilities.pytest import raises, XFAIL
from sympy import I, sqrt, log, exp, sin, asin
from sympy.core.facts import InconsistentAssumptions
def test_symbol_unset():
x = Symbol('x', real=True, integer=True)
assert ... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from copy import copy
import io
import os
import warnings
import numpy as np
from numpy import ma
from numpy.testing import assert_array_equal
from matplotlib import (
colors, image as mimage, mla... |
"""
Restart DIRAC MySQL server
"""
from __future__ import print_function
__RCSID__ = "$Id$"
from DIRAC.Core.Base import Script
Script.disableCS()
Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1],
'Usage:',
' %s [option|cfgfile] ..... |
""" Django signals connections and associated receiver functions for geonode's
third-party 'social' apps which include announcements, notifications,
relationships, actstream user_messages and potentially others
"""
import logging
from collections import defaultdict
from dialogos.models import Comment
from djang... |
from datetime import datetime, timedelta
import random
from urlparse import urljoin
import werkzeug
from openerp.addons.base.ir.ir_mail_server import MailDeliveryException
from openerp.osv import osv, fields
from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT, ustr
from ast import literal_eval
from openerp.to... |
type = "overheat"
def handler(fit, module, context):
for tgtAttr in (
"aoeCloudSizeBonus",
"explosionDelayBonus",
"missileVelocityBonus",
"aoeVelocityBonus"
):
module.boostItemAttr(tgtAttr, module.getModifiedItemAttr("overloadTrackingModuleStrengthBonus")) |
def list_pitch_numbers_in_expr(expr):
'''List pitch numbers in `expr`:
::
>>> tuplet = scoretools.FixedDurationTuplet(Duration(2, 8), "c'8 d'8 e'8")
>>> pitchtools.list_pitch_numbers_in_expr(tuplet)
(0, 2, 4)
Returns tuple of zero or more numbers.
'''
from abjad.tools import ... |
"""
Module implementing some common utility functions for the Mercurial package.
"""
from __future__ import unicode_literals
import os
from PyQt5.QtCore import QProcessEnvironment
import Utilities
def getConfigPath():
"""
Public function to get the filename of the config file.
@return filename of the config... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sessao', '0034_oradorordemdia'),
]
operations = [
migrations.AddField(
model_name='resumoordenacao',
name='decimo_quarto',
... |
"""
Add permission classes to your Django Rest Framework serializer fields.
""" |
from hachoir_py3.metadata.metadata import (registerExtractor, Metadata,
RootMetadata, MultipleMetadata)
from hachoir_py3.parser.audio import (AuFile, MpegAudioFile, RealAudioFile,
AiffFile, FlacParser)
from hachoir_py3.parser.container imp... |
../tests.py |
import unicodedata
from hypothesis import strategies as st
from hypothesis import strategy
from hypothesis.searchstrategy.strings import OneCharStringStrategy
from functools import wraps
class MySQLOneCharStringStrategy(OneCharStringStrategy):
def simplifiers(self, random, template):
def filter_bad_chars(fn... |
import minqlx
import logging
import os.path
import datetime
import os
from logging.handlers import RotatingFileHandler
class log(minqlx.Plugin):
def __init__(self):
self.add_hook("player_connect", self.handle_player_connect, priority=minqlx.PRI_LOWEST)
self.add_hook("player_disconnect", self.handle_... |
from sdl2 import SDL_BlitSurface, \
SDL_CreateRGBSurface, \
SDL_SWSURFACE, \
SDL_Rect
from sdl2.ext import Resources, \
SoftwareSprite, \
load_image, \
subsurface
from components.motion import MotionType
RESOURCES = Resources(__file__, '..', 'resources')
class SpriteSheet:
""" Sprite sheet "... |
"""DocumentSource scrapes MDN wiki documents."""
from __future__ import absolute_import, unicode_literals
import logging
import dateutil
from .base import DocumentBaseSource
logger = logging.getLogger('kuma.scraper')
class DocumentSource(DocumentBaseSource):
"""Coordinate scraping and local cloning of an MDN Docume... |
from uuid import uuid4
from django.db import models
class LandingPageSurvey(models.Model):
uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True)
# An insecure random string so that when a survey is submitted with more information
# it can not easily be guessed and the ratelimit will make ... |
try:
import traceback
import filecmp
import os
import unittest
from lactransformer.libs import FriendlyName, AssignProjection, TxtPanPyConverter, LasPyConverter
except ImportError as err:
print('Error {0} import module: {1}'.format(__name__, err))
traceback.print_exc()
exit(128)
def grid... |
""" good.py """
def read_game_progress():
""" read_game_progress """
level = 0
return level |
from typing import List
from ddd.logic.application.commands import SearchApplicationByApplicantCommand
from ddd.logic.application.domain.builder.applicant_identity_builder import ApplicantIdentityBuilder
from ddd.logic.application.dtos import ApplicationByApplicantDTO
from ddd.logic.application.repository.i_application... |
"""
End to end test of the internal reporting user activity table loading task.
"""
import os
import logging
import datetime
import luigi
import pandas
from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase
log = logging.getLogger(__name__)
class InternalReportingUserActivityLoadAcceptanceTest(AcceptanceTe... |
"""
A mixin class for LTI 2.0 functionality. This is really just done to refactor the code to
keep the LTIModule class from getting too big
"""
import base64
import hashlib
import json
import logging
import re
import urllib
import mock
from oauthlib.oauth1 import Client
from webob import Response
from xblock.core impo... |
"""adds new field discount on partner"""
from openerp import models, fields
class ResPartner(models.Model):
_inherit = 'res.partner'
property_partner_sale_discount = fields.Float(
string='Sale Discount (%)',
company_dependent=True,
default=0.0,
help="If select this partner in sal... |
import time
import random
import os
import os.path
import logging
import urlparse
import functools
import lms.lib.comment_client as cc
import django_comment_client.utils as utils
import django_comment_client.settings as cc_settings
from django.core import exceptions
from django.contrib.auth.decorators import login_requ... |
from django import forms
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.forms import formset_factory
from django.utils.translation import gettext_lazy as _
from base.forms.utils.datefield import DateRangeField, DatePickerInput, DATE_FORMAT, DateTimePickerInput
from base.models import... |
import random
import string
import pytest
from db import db
from journalist_app import create_app
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from uuid import uuid4
from .helpers import (
bool_or_none,
random_bool,
random_bytes,
random_chars,
random_datetime,
random_use... |
import picking
import report, wizard |
from .currency_getter_interface import Currency_getter_interface
import logging
_logger = logging.getLogger(__name__)
class MX_BdM_getter(Currency_getter_interface):
"""Implementation of Currency_getter_factory interface
for Banco de México service
"""
def rate_retrieve(self):
""" Get currency e... |
from casting.casting import Casting
from connecter import Connecter
from const.const import Messenger as Msg
from const.const import Queries
from date_tools.date_tools import DateTools
from logger.logger import Logger
class Alterer:
in_dbs = [] # List of databases to be included in the process
old_role = '' #... |
"""
Views for the verification flow
"""
import json
import logging
import decimal
from mitxmako.shortcuts import render_to_response
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from django.shortcuts impor... |
import logging
from glob import glob
from os.path import basename, isfile, join, exists, normpath, realpath
from odoo import api, fields, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
class IrFilesystemDirectory(models.Model):
_name = 'ir.filesystem.directory'
_descriptio... |
from multiprocessing import *
from datetime import *
from fastserializer import *
def ProcessFunc( countQueue, endTime):
client = FastSerializer("localhost", 21212, "", "")
proc = VoltProcedure( client, "measureOverhead", [FastSerializer.VOLTTYPE_INTEGER] )
counter = 0;
while datetime.datetime.now() < e... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn
from lxml import etree
import pandas as pd
import sys
import os
def extract(par,taglist):
result = []
for p in taglist:
print "Attempting to extract tag '%s'..." % p
try:
param = par.xpath("*[@Name='" + p + "']")[0]
... |
"""
Jingle (XEP-0166) testing support.
"""
import random
from gabbletest import make_presence
from twisted.words.xish import domish
from twisted.words.protocols.jabber.client import IQ
import dbus
from caps_helper import send_disco_reply
class JingleTest:
def __init__(self, stream, local_jid, remote_jid):
s... |
"""
Test text channel initiated by me, using Requests.
"""
import dbus
from gabbletest import exec_test
from servicetest import (call_async, EventPattern, assertContains,
assertEquals)
import constants as cs
def test(q, bus, conn, stream):
self_handle = conn.Properties.Get(cs.CONN, "SelfHandle")
jid = '... |
from spack import *
class QtCreator(QMakePackage):
"""The Qt Creator IDE."""
homepage = 'https://www.qt.io/ide/'
url = 'http://download.qt.io/official_releases/qtcreator/4.3/4.3.1/qt-creator-opensource-src-4.3.1.tar.gz'
list_url = 'http://download.qt.io/official_releases/qtcreator/'
list_depth ... |
from __future__ import unicode_literals
'''
An enumeration is a set of symbolic names bound to unique, constant integer values. Within an
enumeration, the values can be compared by identity, and the enumeration itself can be iterated
over. Enumeration items can be converted to and from their integer equival... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobileTe... |
#
"""
Recognition observer base class
============================================================================
"""
import logging
try:
from inspect import getfullargspec as getargspec
except ImportError:
# Fallback on the deprecated function.
from inspect import getargspec
class RecObsManagerBase(objec... |
import numpy as np
from sklearn import linear_model
import time
dataset = np.loadtxt('blogData_train.csv', dtype = np.dtype('d'), delimiter=',')
dataset_X,dataset_Y = np.split(dataset,[280],1);
regr = linear_model.Ridge(alpha=100, copy_X=True, fit_intercept=True, normalize=False, solver='svd')
start = time.time()
regr.... |
from struct import pack, unpack, unpack_from
import re
import warnings
from .php import die, substr, str_repeat, str_pad, strlen, count
from .py3k import b, ord
_TTF_MAC_HEADER = False
GF_WORDS = (1 << 0)
GF_SCALE = (1 << 3)
GF_MORE = (1 << 5)
GF_XYSCALE = (1 << 6)
GF_TWOBYTWO = (1 << 7)
def sub32(x, y):
xlo = x[... |
import requests
try:
requests.packages.urllib3.disable_warnings()
except:
pass
import requests
import json
import argparse
import os
import sys
import uuid
def check_auth(resp):
# Check to see if authentication succeeded
if resp.status_code == 401:
print "[error] Authentication failed: %s" % (resp)
sys.exit(1)
... |
import pandas as pd
import pandas.testing as tm
import pytest
import ibis
import ibis.common.exceptions as com
import ibis.expr.operations as ops
from ibis.backends.pandas.execution import execute
from ibis.backends.pandas.execution.window import trim_window_result
from ibis.expr.scope import Scope
from ibis.expr.timec... |
"""Bencode parser plugin interface."""
import abc
from plaso.parsers import plugins
class BencodePlugin(plugins.BasePlugin):
"""Bencode parser plugin interface."""
NAME = 'bencode_plugin'
DATA_FORMAT = 'Bencoded file'
# _BENCODE_KEYS is a list of keys required by a plugin.
# This is expected to be overridden ... |
try:
from django.conf.urls import include, patterns, url
except ImportError:
from django.conf.urls.defaults import include, patterns, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = patterns('',
url(regex=r'', view=site.urls),
) |
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, redirect
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.http import is_safe_url
from django.utils.html import format_html
from django.views.generic import RedirectView, FormV... |
import collections
import itertools
import mimetypes
import time
import math
import random
from hashlib import md5
from swift import gettext_ as _
from urllib import unquote, quote
from greenlet import GreenletExit
from eventlet import GreenPile
from eventlet.queue import Queue
from eventlet.timeout import Timeout
from... |
try:
import certifi
except ImportError:
certifi = None
import jmespath
import urllib3
from six.moves.urllib import parse
from c7n import utils
from .core import EventAction
class Webhook(EventAction):
"""Calls a webhook with optional parameters and body
populated from JMESPath queries.
.. cod... |
import mock
from oslo.serialization import jsonutils
import webob
import webob.dec
import webob.exc
import nova.api.openstack
from nova.api.openstack import wsgi
from nova import exception
from nova import test
class TestFaultWrapper(test.NoDBTestCase):
"""Tests covering `nova.api.openstack:FaultWrapper` class."""
... |
from google.cloud.aiplatform.v1beta1.schema.predict import instance
from google.cloud.aiplatform.v1beta1.schema.predict import params
from google.cloud.aiplatform.v1beta1.schema.predict import prediction
__all__ = (
"instance",
"params",
"prediction",
) |
'''
A, B matrices of TDDFT method.
'''
import numpy
from pyscf import gto, scf, dft, tddft
mol = gto.Mole()
mol.atom = [
['H' , (0. , 0. , .917)],
['F' , (0. , 0. , 0.)], ]
mol.basis = '6311g*'
mol.build()
def diagonalize(a, b, nroots=5):
nocc, nvir = a.shape[:2]
a = a.reshape(nocc*nvir,nocc*nvir)
b... |
"""Test code for batch_matmul operator"""
import numpy as np
import tvm
import topi
import topi.testing
from topi.util import get_const_tuple
from tvm.contrib.pickle_memoize import memoize
from common import get_all_backend
def verify_batch_matmul(batch, M, N, K):
x = tvm.placeholder((batch, M, K), name='x')
y ... |
import setuptools
setuptools.setup(
setup_requires=['pbr'],
pbr=True) |
import pydot
import StringIO
import objgraph
a = 1
b = {"2": a, "3": a+1}
d = [a, b, [a, b], []]
dot = StringIO.StringIO()
objgraph.show_backrefs([d], output=dot)
graph = pydot.graph_from_dot_data(dot.getvalue())[0]
graph.write_pdf('graph.pdf') |
import re
from .base import Filterer
class Pattern(Filterer):
'''Filter logs using pattern matching.'''
INCLUDE, EXCLUDE = ('include', 'exclude')
def __init__(self, pattern, key='name', mode=INCLUDE):
'''Initialise filterer with *pattern* and *key* to test.
If *pattern* is a string it will b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.