content stringlengths 4 20k |
|---|
from AppKit import NSWindowCloseButton, NSModalPanelWindowLevel, NSWindowZoomButton, NSWindowMiniaturizeButton, \
NSApp
from vanilla import Window as _Window
from vanilla import List as _List
from vanilla import PopUpButton as _PopUpButton
from vanilla import TextBox, EditText, Button, CheckBox, HorizontalLine, Ver... |
import fnmatch
import os
import re
import shutil
import sys
import uuid
from .. import testloader
from base import Step, StepRunner
from tree import Commit
here = os.path.abspath(os.path.split(__file__)[0])
bsd_license = """W3C 3-clause BSD License
Redistribution and use in source and binary forms, with or without... |
from __future__ import absolute_import, division, print_function, unicode_literals
from solaar import __version__, NAME
import solaar.i18n as _i18n
import solaar.cli as _cli
#
#
#
def _require(module, os_package):
try:
__import__(module)
except ImportError:
import sys
sys.exit("%s: missing required package ... |
import copy
import uuid as stdlib_uuid
from oslo_serialization import jsonutils
import webob
from nova.api.openstack.compute import views
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import matchers
NS = {
'atom': 'http://www.w3.org/2005/Atom',
'ns': 'http://doc... |
from django.conf import settings
from django.core.files.storage import default_storage
from django.utils.translation import ugettext
from rest_framework import serializers
import olympia.core.logger
from olympia.access.models import Group
from olympia.amo.utils import clean_nl, has_links, slug_validator
from olympia.... |
from unittest import mock
from ..models import Document, Revision
from ..signals import render_done
def test_on_document_save_signal_invalidated_tags_cache(root_doc, wiki_user):
tags1 = ("JavaScript", "AJAX", "DOM")
Revision.objects.create(document=root_doc, tags=",".join(tags1), creator=wiki_user)
# c... |
"""Defines a dictionary that can evict least recently used items."""
import collections
import json
import time
CURRENT_VERSION = 3
class LRUDict(object):
"""Dictionary that can evict least recently used items.
Implemented as a wrapper around OrderedDict object. An OrderedDict stores
(key, (value, timestamp)... |
"""This is a windows specific address space."""
import os
import pywintypes
import struct
import weakref
import win32file
from rekall import addrspace
from rekall.plugins.addrspaces import standard
def CTL_CODE(DeviceType, Function, Method, Access):
return (DeviceType << 16) | (Access << 14) | (Function << 2) | ... |
# -*- coding: utf-8 -*-
import functools
from navmazing import NavigateToSibling, NavigateToAttribute
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import toolbar as tb
from cfme.web_ui import AngularSelect, Form, Select, SplitTable, accordion,\
fill, flash, form_buttons, Table, Tree, Input, R... |
from __future__ import unicode_literals
from optparse import make_option
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, NoArgsCommand
from .sync_page_themes import Command as PageThemeCommand
from .sync_widget_themes import Command... |
# -*- coding: utf-8 -*-
from micolog_plugin import *
import logging
import urllib
from model import *
from google.appengine.api import users
from google.appengine.api import memcache
from base import BaseRequestHandler,request_cache
from google.appengine.ext import webapp
from datetime import datetime, timedelta
def u... |
import numpy as np
import pandas as pd
from pvlib.iotools import tmy
from conftest import DATA_DIR
# test the API works
from pvlib.iotools import read_tmy3
TMY3_TESTFILE = DATA_DIR / '703165TY.csv'
TMY2_TESTFILE = DATA_DIR / '12839.tm2'
TMY3_FEB_LEAPYEAR = DATA_DIR / '723170TYA.CSV'
def test_read_tmy3():
tmy.re... |
import os
import re
from metadata import tagging
from metadata import musicbrainz as mb
from etc import functions
from etc.logger import log, logfn, logSection
from etc.utils import *
from AbstractFinder import AbstractReleaseFinder
class ArtistFinder(AbstractReleaseFinder):
"""Gatherer of artist data from all a... |
from bottle import route, abort
from api.false_positive_utils import _get
@route('/false-positive/<uuid:uuid>.json')
def fp_(db, lang, uuid):
marker, columns = _get(db, 'false', uuid=uuid)
if not marker:
abort(410, "Id is not present in database.")
marker = dict(marker)
marker['timestamp'] =... |
"""Bookkeeper Task."""
import json
from selinon import StoragePool
from f8a_worker.base import BaseTask
from f8a_worker.graphutils import GREMLIN_SERVER_URL_REST
from f8a_worker.utils import get_session_retry
class BookkeeperTask(BaseTask):
"""Keep bookkeeping data on RDS."""
# we don't want to add `_audit`... |
import wx
from robotide.action.actioninfo import ActionInfoCollection, ActionInfo
from robotide.context import IS_WINDOWS, ctrl_or_cmd, bind_keys_to_evt_menu
from robotide.controller.commands import ChangeTag
from robotide.controller.tags import Tag, DefaultTag
from robotide.publish import RideTestSelectedForRunningCha... |
#!/usr/bin/env python
# Module: py_utc_timestamp.py
# Purpose: Python UTC timestamp
# Notes:
# 1) ...
# Ref:
# http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python
#
"""py_utc_timestamp.py: Python UTC timestamp test"""
from __future__ import division
from datetime import d... |
"""
An example for FValueSelector.
Run with:
bin/spark-submit examples/src/main/python/ml/fvalue_selector_example.py
"""
from __future__ import print_function
from pyspark.sql import SparkSession
# $example on$
from pyspark.ml.feature import FValueSelector
from pyspark.ml.linalg import Vectors
# $example off$
if __... |
from __future__ import absolute_import
import re
import os
from collections import OrderedDict
from functools import partial
import torch
from torch.autograd import Variable
from torch.utils.serialization import load_lua
from .backend.torchlegacy import load_legacy_model, LambdaBase
import numpy as np
from emu.nnada... |
# -*- coding: utf-8 -*-
from ..utils import set_local_roles
from datetime import datetime
from docpool.base.content.documentpool import APPLICATIONS_KEY
from docpool.base.utils import RARELY_USED_TYPES
from docpool.config import _
from docpool.config.general.elan import connectTypesAndCategories
from docpool.config.loc... |
import struct
def _make_packer(format_string):
try:
packer = struct.Struct(format_string) # new in Python 2.5
except AttributeError:
pack = lambda x: struct.pack(format_string, x)
unpack = lambda s: struct.unpack(format_string, s)
else:
pack = packer.pack
unpack = ... |
import os
import pickle
import unittest
from unittest import TestCase
import unit.constants as uuconst
import unit.utils as uu
from core.exceptions import InvalidFileArgumentError
from core.fileobject import FileObject
from core.fileobject import _validate_path_argument
from util import encoding as enc
class TestFil... |
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from haystack.query import SearchQuerySet
from colab.accounts.models import User
from colab.badger.models import Badge
class Command(BaseCommand):
help = "Rebuild the user's badges."
def handle(self, *args, **kwargs):
for b... |
from examples.intersections import SentenceSplitIntersection, AggregateIntersection, WordCountIntersection
from examples.ramps import WordRamp
from motorway.contrib.sql_alchemy.intersections import DatabaseInsertIntersection
from motorway.intersection import Intersection
from motorway.messages import Message
from motor... |
SNIFF_RADVD = 'icmp6'
def sniff_analyzer_radvd(capture):
import re
result = {'advertisement': {'count': 0, 'prefixes': [], 'flags': []},
'solicitation': {'count': 0, 'prefixes': [], 'flags': []}}
p = re.compile('(advertisement|solicitation)|prefix .+ (.+), '
'Flags \[(.+... |
from settings.base import *
try:
from local_settings import *
except ImportError:
pass
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'estlan.eu',
'ts.estlan.eu',
]
SEND_EMAIL = False
LOGGING['handlers'] = {
'console': {
'class': 'logging.handlers.WatchedFileHandler',
'... |
import os
# toolchains options
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='keil'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = ... |
import numpy as np
from rllab.core.serializable import Serializable
from rllab.envs.base import Step
from rllab.envs.proxy_env import ProxyEnv
from rllab.misc import autoargs
from rllab.misc.overrides import overrides
class NoisyObservationEnv(ProxyEnv, Serializable):
@autoargs.arg('obs_noise', type=float,
... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2015 Stefan Wiehler <<EMAIL>>
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 limitatio... |
from datetime import datetime, timedelta
from challenges.models import Submission, SubmissionParent
from challenges.tests.fixtures.ignite_fixtures import (setup_ignite_challenge,
teardown_ignite_challenge,
set... |
from dolfin import *
if not has_cgal():
print "DOLFIN must be compiled with CGAL to run this demo."
exit(0)
# Define 3D geometry
box = Box(0, 0, 0, 1, 1, 1)
sphere = Sphere(Point(0, 0, 0), 0.3)
cone = Cone(Point(0, 0, -1), Point(0, 0, 1), .5, .5)
g3d = box + cone - sphere;
# Test printing
info("\nCompact o... |
from django.core.urlresolvers import reverse
from django.test import TransactionTestCase
from channel_instagram.views import (SESSKEY_OAUTH_NEXT_URI,
SESSKEY_OAUTH_VERIFY_TOKEN)
from channel_instagram.models import InstagramAccount
from django.contrib.auth.models import User
import ... |
from typing import Callable
from axes.helpers import get_lockout_response
class AxesMiddleware:
"""
Middleware that calculates necessary HTTP request attributes for attempt monitoring
and maps lockout signals into readable HTTP 403 Forbidden responses.
This middleware recognizes a logout monitoring ... |
from openerp.tools.translate import _
from openerp.osv import osv, fields
import decimal_precision as dp
class mrp_production(osv.Model):
_inherit = "mrp.production"
def _make_production_line_procurement(self, cr, uid, production_line,
shipment_move_id, context=No... |
# This challenge is similar to the previous one. It operates under the same
# premise that you will have to replace the check_equals_ function. In this
# case, however, check_equals_ is called so many times that it wouldn't make
# sense to hook where each one was called. Instead, use a SimProcedure to write
# your ow... |
"""
DRAC Driver for remote system management using Dell Remote Access Card.
"""
from oslo.utils import importutils
from ironic.common import exception
from ironic.common.i18n import _
from ironic.drivers import base
from ironic.drivers.modules.drac import management
from ironic.drivers.modules.drac import power
from ... |
import os
import socket
from senf import fsnative
from gi.repository import Gtk
from quodlibet.formats import AudioFile
from quodlibet import app
from quodlibet import config
from tests.plugin import PluginTestCase, init_fake_app, destroy_fake_app
from tests import skipIf
@skipIf(os.name == "nt", "mpd server not su... |
from datetime import datetime
from datetime import timezone
from typing import Iterator, List, Tuple
import yaml
from flask_appbuilder import Model
from superset.commands.base import BaseCommand
from superset.commands.exceptions import CommandException
from superset.dao.base import BaseDAO
from superset.utils.dict_im... |
"""BLEURT scoring library."""
import itertools
from bleurt import score as score_lib
import pandas as pd
import tensorflow as tf
flags = tf.compat.v1.flags
logging = tf.compat.v1.logging
FLAGS = flags.FLAGS
flags.DEFINE_string(
"sentence_pairs_file", None,
"Path to a JSONL file that contains sentence pairs. ... |
#!/usr/bin/python3
import subprocess
import os
import shutil
import configparser
def build_flatpak(appid, srcdir, repodir, branch='master', cleanrepodir=True):
print('Building %s from %s into %s' % (appid, srcdir, repodir))
# delete repodir
if cleanrepodir and os.path.exists(repodir):
print("Dele... |
#!/usr/bin/python
# Test.py: demonstration of the Graph.Cartesian class
"""
Test.py - This is a simple example of the use of the
Graph.Cartesian class to plot a graph on a cartesian
coordinate plain.
"""
import math
import Graph, Gfx, Compatibility
GfxDriver = Compatibility.GetDriver()
print("Using Driver: "+GfxDrive... |
"""
Create clones on a remote array of all volumes in a pgroup.
Download latest pypureclient release from:
https://pypi.org/project/py-pure-client
Example usage:
$ python clone_all_snapshots_in_pgroup.py --source pure001 --target pure002 --target-id-token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImQ2O... |
import requests
from bs4 import BeautifulSoup as bs
from urllib.request import urlretrieve
u1 = 'https://www.al.sp.gov.br/alesp/pesquisa-proposicoes/?direction=acima&lastPage=5167¤tPage='
u2 = '&act=detalhe&idDocumento=&rowsPerPage=10¤tPageDetalhe=1&tpDocumento=&method=search&text=&natureId=4005&legislative... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class VirtualMachineSizesOperations(object):
"""VirtualMachineSizesOperations operations.
:param client: Client for service requests.
:param config: Configuration of servic... |
import mock
import pytest
from ulauncher.api.client.Extension import Extension
from ulauncher.api.shared.action.BaseAction import BaseAction
class TestExtension:
@pytest.fixture(autouse=True)
def client(self, mocker):
return mocker.patch('ulauncher.api.client.Extension.Client').return_value
@pyt... |
from enum import Enum
import numpy as np
import pandas as pd
import scripts.utils.scm as scm
from scripts.utils.encoder import encode_input_window, encode_code
class Name(Enum):
EUK_ANC = 'EUK.ANC.csv'
EUK_NUC = 'EUK.NUC.csv'
EUK_NS = 'EUK.CYT.csv'
EUK_S = 'EUK.SIG.csv'
EUK_TEST = 'EUK.TEST.csv'
... |
#!/usr/bin/env python
# File: plot_uvj_vs_icd.py
# Created on: Wed 07 Nov 2012 09:20:44 AM CST
# Last Change: Fri Nov 9 11:44:02 2012
# Purpose of script: <+INSERT+>
import pylab as pyl
from mpl_toolkits.axes_grid1 import AxesGrid
from mk_galaxy_struc import mk_galaxy_struc
from colsort import colsort
def plot_uvj_v... |
"""
@package mi.instrument.ooici.mi.test_driver.test.test_driver
@file marine-integrations/mi/instrument/ooici/mi/test_driver/driver.py
@author Bill French
@brief Test cases for test_driver driver
USAGE:
Make tests verbose and provide stdout
* From the IDK
$ bin/test_driver
$ bin/test_driver -u [-t t... |
import os
import re
from datetime import datetime
import functools
import dicom
from ..helpers.logging import logger
from qiutil import dates
from qidicom import (meta, writer)
from .sarcoma_config import sarcoma_location
DATE_FMT = '%Y%m%d'
"""The DICOM date format is YYYYMMDD."""
COMMENT_PREFIX = re.compile('^TTC ... |
from olympia import amo
from olympia.addons.models import Category
from olympia.addons.utils import get_featured_ids, get_creatured_ids
from olympia.amo.tests import addon_factory, collection_factory, TestCase
from olympia.bandwagon.models import FeaturedCollection
from olympia.constants.categories import CATEGORIES_BY... |
"""
WSGI config for DataAnalysisWeb project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLIC... |
"""
Generate password from (mostly) gibberish words.
http://stackoverflow.com/a/5502875/356942
"""
from __future__ import print_function, unicode_literals, absolute_import
import itertools
import string
from generators import WordGenBase
initial_consonants = (
set(string.ascii_lowercase) - set('aeiou')
# ... |
"""
Implement an observer pattern for lists and dictionaries.
A subclasses for dicts and lists are defined which send information
about changes to an observer.
The observer is sent enough information about the change so that the
observer can undo the change, if desired.
"""
class list_observer(list):
"""
Send... |
from math import log, sqrt, pi
def erfinv(x, a=.147):
"""Approximation of the inverse error function
https://en.wikipedia.org/wiki/Error_function
#Approximation_with_elementary_functions
"""
lnx = log(1 - x * x)
part1 = (2 / (a * pi) + lnx / 2)
part2 = lnx / a
sgn = 1 if x > 0 else -1
... |
import json
import click
from tabulate import tabulate
@click.command('blackouts', short_help='List alert suppressions')
@click.option('--purge', is_flag=True, help='Delete all expired blackouts')
@click.pass_obj
def cli(obj, purge):
"""List alert suppressions."""
client = obj['client']
if obj['output']... |
from core.vectors import ShellCmd, PhpCode
from core.module import Module
class Clearlog(Module):
"""Remove string from a file."""
def init(self):
self.register_info(
{
'author': [
'appo'
],
'license': 'GPLv3'
... |
"""
@author: Disa Mhembere
@organization: Johns Hopkins University
@contact: <EMAIL>
@summary: A module to alter/update the MRdjango database as necessary
"""
'''
FileField stores files e.g. to media/documents based MEDIA_ROOT
Generally, each model maps to a single database table.
'''
from django.db import models
fr... |
from math import sqrt
class Solution(object):
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 9
if n & 1:
sup = 10 ** (n - 1)
sup10 = sup * 10
for i in range(1, sup):
... |
def cycle(key,element,path_string=""):
if isinstance(element, dict):
for k,v in element.items():
if k == key:
print "\n\n\n\t\tFOUND\n\n\n" , path_string+":"+key
return path_string+":"+key
else:
path_string = path_string+":"+k
cycle(key, element[k], path_string)
if isinstance(element, list):
... |
import sys
# check python version
if sys.version_info < (3, 4, 0):
print("CloudBot requires Python 3.4 or newer.")
sys.exit(1)
import json
import logging.config
import logging
import os
__version__ = "1.0.9"
__all__ = ["util", "bot", "connection", "config", "permissions", "plugin", "event", "hook", "log_dir... |
# -*- encoding: utf-8 -*-
from supriya.tools.ugentools.WidthFirstUGen import WidthFirstUGen
class IFFT(WidthFirstUGen):
r'''An inverse fast Fourier transform.
::
>>> pv_chain = ugentools.LocalBuf(2048)
>>> ifft = ugentools.IFFT.ar(
... pv_chain=pv_chain,
... window_si... |
#!/usr/bin/env python
"""Extract n random sequences from a fasta file.
Usage:
%program <input_file> n <output_file>"""
# Importing modules
import sys
import re
import random
# Defining classes
class Fasta(object):
"""Fasta object with name and sequence
"""
def __init__(self, name, sequence):
... |
from PartDesignTests.TestDatum import TestDatumPoint, TestDatumLine, TestDatumPlane
from PartDesignTests.TestShapeBinder import TestShapeBinder
# additive/subtractive features & primitives
from PartDesignTests.TestPad import TestPad
from PartDesignTests.TestPocket import TestPocket
from PartDesignTests.TestHole import... |
"""Test recovery from a crash during chainstate writing.
- 4 nodes
* node0, node1, and node2 will have different dbcrash ratios, and different
dbcache sizes
* node3 will be a regular node, with no crashing.
* The nodes will not connect to each other.
- use default test framework starting chain. initialize s... |
import sys
import samba
import os
import binascii
import socket
class fuzzsmbd(samba.tests.TestCase):
def test_bug_14205(self):
#
# badblob consists of an incorrectly
# terminated SMB1 Negprot, with a valid SessionSetup after.
# BUG: #14205 causes the smbd server to crash.
#... |
# encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
from QGesture import QGesture
class QSwipeGesture(QGesture):
""" QSwipeGesture(QObject parent=None) """
def horizontalDirection(self): #... |
from time import sleep
import sys, os
import subprocess
import re
import json
import urllib.request, urllib.error, urllib.parse
try:
from bs4 import BeautifulSoup
except ImportError:
print("Vous devez instaler python3-bs4")
print("sudo apt-get install python3-bs4")
subprocess.call('sudo apt-get install... |
from __future__ import division, absolute_import, print_function, unicode_literals
from awlsim.common.compat import *
from awlsim.common.util import *
import struct
class MemoryArea(object):
# Possible memType values
EnumGen.start
TYPE_E = EnumGen.item # input memory
TYPE_A = EnumGen.item # output memory
TYP... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ModelerScene.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************... |
# -*- encoding=UTF-8 -*-
from multiprocessing.pool import ThreadPool
import nltk
import os
from askMathPlus.settings import BASE_DIR
from askMathPlus.settings import COLORS_ALL
from askmath.models import Discipline, Lesson, Video
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from d... |
### Author: Dag Wieers <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'extended nfs3 client operations'
self.nick = ('null', 'gatr', 'satr', 'look', 'aces', 'rdln', 'read', 'writ', 'crea', 'mkdr', 'syml', 'mknd', 'rm', 'rmdr', 'ren', 'link', 'rdir', 'rdr+', 'fstt', 'fsnf', 'pa... |
"""
Some utility functions, not for public use
"""
try:
from lxml import etree
except ImportError: # If lxml is not there try python standard lib
from xml.etree import ElementTree as etree
from eeml.namespace import EEML_NAMESPACE, NSMAP
def _elem(name):
"""
Create an element in the EEML namespace
... |
import abc
import typing
import pkg_resources
from google import auth
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
from google.ads.googleads.v6.resources.types import group_placement_view
from goog... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contests', '0001_initial'),
migrations... |
import socket
import six
from flask import Flask
from flask_appbuilder import AppBuilder, SQLA
from flask_caching import Cache
from flask_wtf.csrf import CSRFProtect
from six.moves.urllib.parse import urlparse
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.contrib.fixers import ProxyFix
from airflow imp... |
import salome
salome.salome_init()
from salome.geom import geomBuilder
geompy = geomBuilder.New(salome.myStudy)
# This script demonstrates generation of 3D mesh basing on a modified 2D mesh
#
# Purpose is to get a tetrahedral mesh in a sphere cut by a cube.
# The requirement is to have a surface mesh on the cube comp... |
from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.base import TemplateView
from django.views.generic import DetailView, DateDetailView
from blog.models import Entry
from blog.feeds import LatestEntriesFeed
admin.autodiscover()
handler500 = 'djangotoolbox.errorviews.ser... |
import unittest
from neo.rawio.openephysrawio import OpenEphysRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestOpenEphysRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = OpenEphysRawIO
entities_to_test = ['OpenEphys_SampleData_1',
# 'OpenEphys_SampleData_2_(multipl... |
import logging
import matplotlib.colors
import numpy as np
logger = logging.getLogger(__name__)
class Vdx:
"""
This class holds logic for plotting Vdx stuff.
"""
def __init__(self, projection_selector):
self.projection_selector = projection_selector
self.vois = []
self.ctx = ... |
from SipMessage import SipMessage
import Helper
class SipRequest (SipMessage):
"""This class inherits all code from SipMessage and implementes all
additional function which are required to handle a SIP request.
"""
def __init__(self):
SipMessage.__init__(self)
self.isRequest = True
self.method = None
sel... |
import numpy as np
def make_sure_ind(inds, req_len=None):
"""Given an object, constructs a tuple of floats the required length.
Either removes items that cannot be cast as floats, or adds the last valid
item until the required length is reached.
Parameters
----------
inds : sequence
t... |
def solution():
mod = 10**9+7
T = int(input())
for t in range(T):
V, S = map(int, input().split(' '))
# hash vocabulary
vocabulary = {}
for v in range(V):
word = input()
lst = [0] * 26
for letter in word:
lst[ord(letter) - o... |
import re
from . import process_grammar
from .errors import (
OnStatementSyntaxError,
UnsatisfiedStatementError,
)
_SELECTOR_PATTERN = re.compile(r'\Aon\s+([^,\s](?:,?[^,]+)*)\Z')
_WHITESPACE_PATTERN = re.compile(r'\A.*\s.*\Z')
class OnStatement:
"""Process an 'on' statement in the stage packages gramma... |
"""Tiny library for handling csv"""
from __future__ import with_statement
import os
import csv
import itertools
__all__ = ("read_csv", "write_csv", "format_to_csv")
# HELPER FUNCTIONS
def is_type(_type, x):
try:
return str(_type(x)) == x
except ValueError:
return False
def determine_type... |
from msrest.serialization import Model
class UserIdentityFragment(Model):
"""Identity attributes of a lab user.
:param principal_name: Set to the principal name / UPN of the client JWT
making the request.
:type principal_name: str
:param principal_id: Set to the principal Id of the client JWT ma... |
from openerp.osv import osv, fields
import tempfile
import os
import codecs
import base64
import xml.dom.minidom
from datetime import datetime, timedelta
from openerp.tools.translate import _
try:
from SOAPpy import WSDL
except:
print "Package SOAPpy missed"
pass
import time
from openerp import tools
clas... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from m... |
from scrapy.spiders import CrawlSpider
from psicrawler.items import GenericItem
from newspaper import Article, Config as ArticleConfig
import os
class DefaultSpider(CrawlSpider):
source = "DefaultSpider"
allowed_topics = (
'Technology',
'Economics',
'Politics',
'Science',
... |
import datajoint as dj
from datajoint.jobs import key_hash
from . import experiment
schema = dj.schema('pipeline_notification', locals())
# Decorator for notification functions. Ignores exceptions.
def ignore_exceptions(f):
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
e... |
#-*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse_lazy
from django.middleware.csrf import get_token
from geoads.views import AdSearchView
from models import HomeForRentAd
class HomeForRentAdSearchView(AdSearchView):
model = HomeForRentAd
... |
"""
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.ticketing import category_service, event_service, \
ticket_bundle_service as bundle_service
from tests.helpers import create_brand, create_party
def test_revoke_bundle(admin_app_with_db, norm... |
class TemplateWriter(object):
'''Abstract base class for writing policy templates in various formats.
The methods of this class will be called by PolicyTemplateGenerator.
'''
def __init__(self, platforms, config):
'''Initializes a TemplateWriter object.
Args:
platforms: List of platforms for whi... |
"""The interface of expr function exposed from C++."""
from __future__ import absolute_import
from ... import build_module as _build
from ... import container as _container
from ..._ffi.function import _init_api, register_func
@register_func("relay.backend.lower")
def lower(sch, inputs, func_name, source_func):
... |
from __future__ import print_function
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
# -*- coding: utf-8 -*-
"""mpfr_vector provides an arbitrary-precision mathematical vector class."""
# Python standard library imports
from collections.abc import Sequence
# Third-party imports
import gmpy2 # pylint: disable=import-error
class MPFRVector(Sequence):
"""MPFRVector represents an aribitrary-precisi... |
#!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a liliucoind or l... |
import collections
import itertools
import six
def flatten(sequence_of_sequences):
return itertools.chain.from_iterable(sequence_of_sequences)
def pairwise(sequence):
sequence = iter(sequence)
try:
while True:
yield next(sequence), next(sequence)
except StopIteration:
pass... |
"""Synchronize replicas for training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.framework import types_pb2
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import... |
from __future__ import with_statement
import os
import sys
import time
import unittest
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import u
from libcloud.utils.py3 import PY3
from libcloud.compute.deployment import MultiStepDeployment, Deployment
from libcloud.compute.deployment import SSHKeyDeplo... |
# -*- coding: utf-8 -*-
'''
Copyright 2012-2017 HWM
This file is part of PorDB3.
PorDB3 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 o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.