content stringlengths 4 20k |
|---|
'''A baseclass for simple gatherers that store their gathered resource in a
list.
'''
import types
from grit.gather import interface
from grit import clique
from grit import tclib
class SkeletonGatherer(interface.GathererBase):
'''Common functionality of gatherers that parse their input as a skeleton of
transla... |
"""
This file contains utilities to work with autodock vina.
"""
from typing import List, Optional, Tuple
import numpy as np
from deepchem.utils.typing import RDKitMol
from deepchem.utils.pdbqt_utils import pdbqt_to_pdb
def write_vina_conf(protein_filename: str,
ligand_filename: str,
... |
"""SCons.Tool.Perforce.py
Tool-specific initialization for Perforce Source Code Management system.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, ... |
import distutils.spawn
import logging
import os
import re
import stat
import subprocess
from telemetry.core.platform import desktop_platform_backend
from telemetry.core.platform import ps_util
def _BinaryExistsInSudoersFiles(path, sudoers_file_contents):
"""Returns True if the binary in |path| features in the sudo... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
import sys
try:
import pan.xapi
HAS_LIB = True
except ImportError:
HAS_LIB = False
def main():
argument_spec... |
"""Data structures for the application.
Copyright 2014 University of Liverpool
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 appl... |
#!/usr/bin/env python
from math import sqrt, acos, atan, sin, cos
import argparse
import vtktools
parser = argparse.ArgumentParser(description='Radially scale a .vtu file.')
parser.add_argument('input_vtu', nargs='+',
help='The .vtu file(s) to be scaled.')
parser.add_argument('-p', dest='output_pre... |
import ctypes
import weakref
from . import heap
from . import get_context
from .context import assert_spawning
from .reduction import ForkingPickler
__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized']
#
#
#
typecode_to_type = {
'c': ctypes.c_char, 'u': ctypes.c_wchar,
'b': ctypes.... |
import warnings
from django import test
from django.contrib.contenttypes.fields import GenericRelation
from django.core.exceptions import FieldDoesNotExist
from django.db.models.fields import CharField, related
from django.utils.deprecation import RemovedInDjango20Warning
from .models import BasePerson, Person
from .... |
"""Error object commonly used in linters."""
__author__ = ('<EMAIL> (Robert Walker)',
'<EMAIL> (Andy Perelson)')
class Error(object):
"""Object representing a style error."""
def __init__(self, code, message, token=None, position=None, fix_data=None):
"""Initialize the error object.
Args:... |
"""
Classes to handle image files.
Collection of classes to handle image upload/download to/from Image service
(like Glance image storage and retrieval service) from/to VMware server.
"""
import httplib
import urllib
import urllib2
import netaddr
import six.moves.urllib.parse as urlparse
from cinder.i18n import _
fr... |
# -*- coding: utf-8 -*-
"""
sphinx.util.osutil
~~~~~~~~~~~~~~~~~~
Operating system-related utility functions for Sphinx.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
import sys
import time
import errno
import shut... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Usage of IC 7418
# <codecell>
from __future__ import print_function
from BinPy import *
# <codecell>
# Usage of IC 7418:
ic = IC_7418()
print(ic.__doc__)
# <codecell>
# The Pin configuration is:
inp = {
1: 1,
2: 0,
3: 0,... |
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
from scipy.sparse import identity, bmat
import scipy.io
def IndexSet(W,type = 'standard'):
if type == 'standard':
if str(W.__class__).find('MixedFunctionSpace') != -1:
n = W.num_sub_spaces()
IS = [0]*n
... |
from twisted.trial import unittest
from twisted.conch.insults import helper, text
A = text.attributes
class Serialization(unittest.TestCase):
def setUp(self):
self.attrs = helper.CharacterAttribute()
def testTrivial(self):
self.assertEquals(
text.flatten(A.normal['Hello, world.']... |
import sys
# Unix
sys.path.append('/usr/share/inkscape/extensions')
# OS X
sys.path.append('/Applications/Inkscape.app/Contents/Resources/extensions')
# Windows
sys.path.append('C:\Program Files\Inkscape\share\extensions')
# We will use the inkex module with the predefined Effect base class.
import inkex
def propStrT... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); ... |
from django_fsm_log.conf import settings
from django.core.cache import get_cache
class BaseBackend(object):
@staticmethod
def setup_model(model):
raise NotImplementedError
@staticmethod
def pre_transition_callback(*args, **kwargs):
raise NotImplementedError
@staticmethod
def... |
"""
==============================================
Label Propagation learning a complex structure
==============================================
Example of LabelPropagation learning a complex internal structure
to demonstrate "manifold learning". The outer circle should be
labeled "red" and the inner circle "blue". Be... |
"""
Tests for tools
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import pandas as pd
from scipy.linalg import solve_discrete_lyapunov
from statsmodels.tsa.statespace import tools
from statsmodels.tsa.api import acovf
# from .resul... |
"""
Flask-Celery
------------
Celery integration for Flask
"""
from setuptools import setup
setup(
name='Flask-Celery',
version='2.4.2',
url='http://github.com/ask/flask-celery/',
license='BSD',
author='Ask Solem',
author_email='<EMAIL>',
description='Celery integration for Flask',
lo... |
from random import random
from hashlib import md5
from time import time
from SipConf import SipConf
from SipGenericHF import SipGenericHF
class SipCallId(SipGenericHF):
hf_names = ('call-id', 'i')
body = None
def __init__(self, body = None):
SipGenericHF.__init__(self, body)
self.parsed = ... |
from bases.FrameworkServices.ExecutableService import ExecutableService
# default module values (can be overridden per job in `config`)
update_every = 5
CHRONY_COMMAND = 'chronyc -n tracking'
# charts order (can be overridden if you want less charts, or different order)
ORDER = [
'system',
'offsets',
'st... |
"""Package contenant la commande 'scripting'."""
from primaires.interpreteur.commande.commande import Commande
from .alerte import PrmAlerte
from .exec import PrmExec
class CmdScripting(Commande):
"""Commande 'scripting'"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__ini... |
import os
import tempfile
# Try to import PIL in either of the two ways it can end up installed.
# Checking for the existence of Image is enough for CPython, but for PyPy,
# you need to check for the underlying modules.
try:
from PIL import Image, _imaging
except ImportError:
try:
import Image, _imagi... |
"""Controllers for simple, mostly-static pages (like About, Forum, etc.)."""
__author__ = '<EMAIL> (Sean Lip)'
import urllib
import urlparse
from core.controllers import base
from core.controllers import editor
from core.domain import config_domain
import feconf
ABOUT_PAGE_YOUTUBE_VIDEO_ID = config_domain.ConfigP... |
"""
Generates simple converter functions that convert a single value from
python to C or C to python. These can be useful in certain
specialized contexts, such as converting list elements.
"""
from typehandlers.base import ReverseWrapperBase, ForwardWrapperBase
from typehandlers import ctypeparser
class PythonToCCon... |
#!/usr/bin/env python
import boto.sdb
import sys
import time
from optparse import OptionParser
default_bucket = "cassandra-archive" # priam default
default_zones_available = "eu-west-1a,eu-west-1b,eu-west-1c"
default_sdb_region = "us-east-1"
def main(argv=None):
parser = OptionParser(usage="""
simpledb_co... |
"""
Tests for StudentViewTransformer.
"""
# pylint: disable=protected-access
from openedx.core.lib.block_cache.block_structure_factory import BlockStructureFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import ToyCourseFactory
from ..student_vi... |
import json
import os
import sys
from tempfile import TemporaryDirectory
from jupyter_client.kernelspec import install_kernel_spec
kernel_json = {
"argv": [sys.executable, "-m", "libqtile.interactive.iqshell_kernel", "-f", "{connection_file}"],
"display_name": "iqshell",
"language": "qshell",
}
def main... |
import copy
import inspect
from importlib import import_module
from django.db import router
from django.db.models.query import QuerySet
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
def ensure_default_manager(cls):
"""
Ensures that a Model subclass contains a defa... |
"""
The I{soaparray} module provides XSD extensions for handling
soap (section 5) encoded arrays.
"""
from suds import *
from logging import getLogger
from suds.xsd.sxbasic import Factory as SXFactory
from suds.xsd.sxbasic import Attribute as SXAttribute
class Attribute(SXAttribute):
"""
Represents an XSD <a... |
"""The tests for the Input number component."""
# pylint: disable=protected-access
import asyncio
from homeassistant.core import CoreState, State, Context
from homeassistant.components.input_number import (
ATTR_VALUE, DOMAIN, SERVICE_DECREMENT, SERVICE_INCREMENT,
SERVICE_SET_VALUE)
from homeassistant.const im... |
LOCAL_MODULES = [
#'my_extra_api_definitions',
]
import sys
import os
sys.path.insert(0, sys.argv[2])
from pybindgen import FileCodeSink, write_preamble
from pybindgen.module import MultiSectionFactory
import pybindgen.settings
pybindgen.settings.deprecated_virtuals = False
from ns3modulegen_generated im... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import botocore
except ImportError:
pass # will be detected ... |
#!/usr/bin/env ambari-python-wrap
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the... |
from weboob.tools.test import BackendTest
from weboob.capabilities.calendar import Query, CATEGORIES
from datetime import datetime, timedelta
class SueurDeMetalTest(BackendTest):
MODULE = 'sueurdemetal'
def test_sueurdemetal_searchcity(self):
q = Query()
q.city = u'paris'
self.assertT... |
"""JSON token scanner
"""
import re
try:
from _json import make_scanner as c_make_scanner
except ImportError:
c_make_scanner = None
__all__ = ['make_scanner']
NUMBER_RE = re.compile(
r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
(re.VERBOSE | re.MULTILINE | re.DOTALL))
def py_make_scanner(context):
... |
import asyncio
import signal
import aiohttp
import click
from . import main
from .pretty import print_info, print_error
from ..request import Request
from ..session import AsyncSession
from ..compat import asyncio_run_forever, current_loop
class WSProxy:
__slots__ = (
'api_session', 'session_id',
... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
'sentry.filtervalue': {
'Meta': {'uniq... |
from src.pluginSystem.pluginDynamicMutatePolicies import dynamic_load_init as get_policy_check_mutate_names
from src.pluginSystem.pluginDynamicSelectPolicies import dynamic_load_init as get_policy_check_select_names
from src.pluginSystem.pluginDynamicSubstitutions import dynamic_load_init as get_substitution_check_name... |
from __future__ import unicode_literals
from operator import attrgetter
import transaction
from indico.core.db import db
from indico.modules.categories.models.legacy_mapping import LegacyCategoryMapping
from indico.modules.fulltextindexes.models.categories import IndexedCategory
from indico.modules.users import Favo... |
import sys
import os
import psutil
import time
import hashlib
import getpass
import threading
from SocketServer import ThreadingMixIn
from whiteprocess_common import *
from whiteprocess_agent import *
from whiteprocess_socket import *
# Class for manage lists
class whiteprocess_list():
main_list = None
def __i... |
import os
import sys
import inspect
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
arch_dir = '../lib/x64' if sys.maxsize > 2 ** 32 else '../lib/x86'
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
import Leap
from Leap... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
import time
import unittest
from django.test import TestCase
from django.conf import settings as s
from condor.models import CondorDag... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from django.apps import apps
from django.core import checks
from django.core.checks import Error, Warning
from django.core.checks.registry import CheckRegistry
from django.core.management import call_command
from django.core.management.base im... |
"""Testing for bicluster metrics module"""
import numpy as np
from sklearn.utils.testing import assert_equal, assert_almost_equal
from sklearn.metrics.cluster.bicluster import _jaccard
from sklearn.metrics import consensus_score
def test_jaccard():
a1 = np.array([True, True, False, False])
a2 = np.array([T... |
from common_fixtures import * # NOQA
TEST_HANDLER_PREFIX = 'test-handler-'
@pytest.fixture(scope='module', autouse=True)
def tear_down(request, admin_user_client):
request.addfinalizer(lambda: _disable_test_handlers(admin_user_client))
def _get_extension(admin_client, extension_point_name, impl_name,
... |
######
#
# HX-2014-08:
# for Python code translated from ATS
#
######
######
#beg of [basics_cats.py]
######
######
import sys
######
############################################
#
def ATSCKiseqz(x): return (x == 0)
def ATSCKisneqz(x): return (x != 0)
#
def ATSCKptrisnull(xs): return (xs == None)
def ATSCKptriscons(... |
import sys
import subprocess
import re
def main():
if len(sys.argv) <= 1:
print('Usage: %s [ --apply ] filename1.rs filename2.rs ...'
% sys.argv[0])
elif sys.argv[1] == '--apply':
for filename in sys.argv[2:]:
patch(filename)
else:
for filename in sys.argv... |
import math
import time
from util import hook, urlnorm, timesince
expiration_period = 60 * 60 * 24 # 1 day
ignored_urls = [urlnorm.normalize("http://google.com")]
def db_init(db):
db.execute("create table if not exists urlhistory"
"(chan, url, nick, time)")
db.commit()
def insert_history... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
External inventory script for Abiquo
====================================
Shamelessly copied from an existing inventory script.
This script generates an inventory that Ansible can understand by making API requests to Abiquo API
Requires some python libraries, ensure ... |
from __future__ import absolute_import, division, print_function
import numpy as np
from numpy.testing import (assert_equal, assert_array_equal,
assert_array_almost_equal, assert_almost_equal)
from nose.tools import raises
from skxray.core.cdi import (_dist, gauss, find_support,
... |
import os, glob, random
from cStringIO import StringIO
from test.test_support import (verbose, findfile, is_resource_enabled,
TestFailed)
from tokenize import (tokenize, generate_tokens, untokenize,
NUMBER, NAME, OP, STRING)
# Test roundtrip for `untokenize`. `f` i... |
from django import template
from contactos.models import Contact
from django.db.models import Q
from subdomains.templatetags.subdomainurls import url as subdomainsurls, UNSET
register = template.Library()
def show_contacts_for(person, writeitinstance):
contacts = Contact.objects.filter(Q(person=person), Q(writeit... |
from itertools import product, permutations
import numpy as np
from numpy.testing import assert_array_less, assert_allclose
from pytest import raises as assert_raises
from scipy.linalg import inv, eigh, norm
from scipy.linalg import orthogonal_procrustes
from scipy.sparse.sputils import matrix
def test_orthogonal_p... |
"""Text-processing ops.
@@skip_gram_sample
@@skip_gram_sample_with_text_vocab
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,wildcard-import
from tensorflow.contrib.text.python.ops import *
# pylint: enable=unused-import... |
# Scan <Menus.h>, generating menugen.py.
import sys
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner
def main():
input = "Menus.h"
output = "menugen.py"
defsoutput = TOOLBOXDIR + "Menus.py"
scanner = MyScanner(input, output, defsoutput)
scanner.s... |
from boto.ec2.cloudwatch.alarm import MetricAlarm
from boto.ec2.cloudwatch.dimension import Dimension
class Metric(object):
Statistics = ['Minimum', 'Maximum', 'Sum', 'Average', 'SampleCount']
Units = ['Seconds', 'Microseconds', 'Milliseconds', 'Bytes', 'Kilobytes',
'Megabytes', 'Gigabytes', 'Te... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import social.apps.django_app.default.fields
from django.conf import settings
import social.storage.django_orm
from social.utils import setting_name
user_model = getattr(settings, setting_name('USER_MODEL'), None)... |
"""
Read/Write AMQP frames over network transports.
2009-01-14 Barry Pederson <<EMAIL>>
"""
# Copyright (C) 2009 Barry Pederson <<EMAIL>>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundatio... |
# Some registry helpers.
import win32api
import win32con
import sys
import os
error = "Registry utility error"
# A .py file has a CLSID associated with it (why? - dunno!)
CLSIDPyFile = "{b51df050-06ae-11cf-ad3b-524153480001}"
RegistryIDPyFile = "Python.File" # The registry "file type" of a .py file
RegistryIDPycFile... |
from PySide2 import QtCore
from PySide2.QtCore import QObject
from PySide2.QtGui import QMouseEvent
from PySide2.QtWidgets import QMenu, QActionGroup, QAction
from pivy import coin
from pivy.coin import SoEventManager, SoScXMLStateMachine, SoRenderManager, SoGLRenderAction
from .eventhandlers import EventManager
cl... |
"""Gradients for operators defined in math_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.framework import types
from tensorflow.python.ops import array_ops
from tensorflow.python... |
from django import dispatch
# This signal is sent before a release_component object is updated. The argument contains
# the original value.
releasecomponent_pre_update = dispatch.Signal(providing_args=['request', 'release_component'])
# This signal is sent after a release_component object is updated in the database.... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import AnonymousUser
from shopit.forms.account import AccountDetailsForm, AccountPasswordForm, AccountRegisterForm
from shopit.models.customer import Customer
from ..utils import ShopitTestCase
class Ac... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*-_
############################
# File Name: demo.py
# Created Time: 2016-09-01 13:54:34
############################
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import myinfo
userna... |
import multiprocessing
import os
import time
import unittest
import uuid
from unittest import mock
from unittest.mock import patch
import pytest
from airflow import settings
from airflow.exceptions import AirflowException
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.jobs.local_tas... |
from ctypes import *
from ctypes.util import find_library
import numpy as np
import os
# flags copied from fftw3.h
FFTW_MEASURE = 0
FFTW_ESTIMATE = 1 << 6
V1_V2_INPUT_PARAMETERS = [
{"size": 8192, "sparsity": 50},
{"size": 16384, "sparsity": 50},
{"size": 32768, "sparsity": 50},
{"size": 65... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from textwrap import dedent
from pytest import fail
from pants.backend.python.tasks.python_isort import IsortPythonTask
from pants.base.exceptions import T... |
import openerp.addons.web.http as http
from openerp.addons.web.http import request
class google_calendar_controller(http.Controller):
@http.route('/google_calendar/sync_data', type='json', auth='user')
def sync_data(self, arch, fields, model, **kw):
"""
This route/function is called when ... |
import os,zipfile,shutil
from os import curdir,sep
from tkMessageBox import showinfo,showerror
from bin import osenv as _osenv
from lang import de_DE, en_EN
from conf import setlang
from conf import check as _check
support_cldir = "support-client"
ltrans = ()
if setlang.langn == "de_DE":
ltrans = de_DE()
elif set... |
"""Listens on a local TCP socket for incoming Metrics """
from __future__ import print_function
import socket
import os
import sys
import time
from collectors.lib import utils
try:
from _thread import *
except ImportError:
from thread import *
try:
from collectors.etc import tcp_bridge_conf
except Impor... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(494, 243)
Form.setAutoFillBackground(False)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import socialregistration.models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
migrations.swappable_dependency(settings.A... |
from __future__ import absolute_import, division, unicode_literals
try:
from collections import OrderedDict
except ImportError:
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDict = dict
import re
from pip._vendor.six import text_type
from . import _base
from ..utils... |
import datetime
from warnings import warn
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.contrib.auth.signals import user_logged_in, user_logged_out
SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'
REDIRECT_FIELD_NAME = 'next... |
"""
Cached, database-backed sessions.
"""
import logging
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import caches
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from django.utils.encoding imp... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_vlan
short_description: Manage VLANs on a BIG... |
import codecs
from itertools import izip
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
def split_list(items, pred):
"""
... |
from ...const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from . import Rule
#-------------------------------------------------... |
"""Wordcount exercise
Google's Python class
The main() below is already defined and complete. It calls print_words()
and print_top() functions which you write.
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
... |
import operator
from . import libmp
from .libmp.backend import basestring
from .libmp import (
int_types, MPZ_ONE,
prec_to_dps, dps_to_prec, repr_dps,
round_floor, round_ceiling,
fzero, finf, fninf, fnan,
mpf_le, mpf_neg,
from_int, from_float, from_str, from_rational,
mpi_mid, mpi_delta, ... |
import maya.cmds as cmds
import maya.OpenMaya
import IECore
import IECoreMaya
## \todo Reimplement this in terms of the new Panel base class.
## \todo Prefix methods which aren't intended to be public to make them either private or protected.
class ParameterPanel :
panels = {}
@staticmethod
def trashDropCallback... |
"""Routine to "compile" a .py file to a .pyc (or .pyo) file.
This module has intimate knowledge of the format of .pyc files.
"""
import _py_compile
import os
import sys
import traceback
__all__ = ["compile", "main", "PyCompileError"]
class PyCompileError(Exception):
"""Exception raised when an error occurs whi... |
from mat import Mat
from vec import Vec
from vecutil import list2vec
from matutil import listlist2mat
from machine_learning_lab import signum
from machine_learning_lab import fraction_wrong
#v = signum(Vec({1,2,3},{1:2, 2:-1}))
#ref = Vec({1,2,3},{1:1,2:-1,3:1})
#print(v==ref)
A1 = listlist2mat([[10, 7, 11, 10, 14],... |
# pylint: disable=C0111,R0903
"""Displays and changes the current keyboard layout
Requires the following executable:
* setxkbmap
Parameters:
* layout.lang: pipe-separated list of languages to cycle through (e.g. us|rs|de). Default: en
"""
import bumblebee.util
import bumblebee.input
import bumblebee.output
... |
"""Print help text."""
# :license: MIT, see LICENSE for more details.
import click
from click import formatting
from SoftLayer.CLI import core as cli_core
from SoftLayer.CLI import environment
from SoftLayer.shell import routes
@click.command()
@environment.pass_env
@click.pass_context
def cli(ctx, env):
"""Pri... |
"""
DowCommerce class to process credit card payments with DowCommerce.com
Modifications to support Dow Commerce API from code originally written by John Conde
http://www.johnconde.net/blog/integrate-the-authorizenet-aim-api-with-python-3-2/
BSDv3 License
Modifed by Dave Stoll <EMAIL>
- modifed to support Dow Commer... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import os
import pipes
import subprocess
import traceback
try:
import MySQLdb
except I... |
from azure.graphrbac import GraphRbacManagementClient
from c7n_azure.actions.base import AzureBaseAction
from c7n_azure.filters import FirewallRulesFilter
from c7n_azure.provider import resources
from c7n_azure.session import Session
from c7n.filters import Filter
from c7n.utils import type_schema
from c7n_azure.utils... |
"""
This script computes the absolute trajectory error from the ground truth
trajectory and the estimated trajectory.
"""
import sys
import numpy
import argparse
import associate
def align(model,data):
"""Align two trajectories using the method of Horn (closed-form).
Input:
model -- first trajectory ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils._text import to_native
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
try:
import gitlab
HAS_GITLAB = True
ex... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
get_element_by_id,
int_or_none,
parse_iso8601,
str_to_int,
)
class IzleseneIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://(?:... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible.executor.module_common import modify_module
from ansible.module_utils.six import PY2
from test_module_common import templar
FAKE_OLD_MODULE = b'''#!/usr/bin/python
import sys
print('{"result": "%s"}' ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.conf import settings
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.geoip import HAS_GEOIP
from django.utils import unittest
from django.utils.unittest import skipUnless
from django.utils import six
if HAS_GEO... |
#!"C:\Users\hog\Documents\Visual Studio 2010\Projects\ArdupilotMega\ArdupilotMega\bin\Debug\ipy.exe"
"""
setup.py for installing F2PY
Usage:
python setup.py install
Copyright 2001-2005 Pearu Peterson all rights reserved,
Pearu Peterson <<EMAIL>>
Permission to use, modify, and distribute this software is given unde... |
from default_settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': PROJECT_ROOT + '/db/des_import3.db', # Or path to database file if using sqlite3.
... |
"""
Helper utilities for python scripts that use pymysql
"""
import inspect
import logging
from socket import error as socket_error
import pymysql
from pymysql.constants import ER
from nupic.support.decorators import retry as make_retry_decorator
# Client mysql error codes of interest; pymysql didn't have constant... |
import os
from django.conf import settings
from django.test import TransactionTestCase
from django.test.utils import override_settings
from weblate.utils.backup import backup, get_paper_key, initialize, prune
from weblate.utils.data import data_dir
from weblate.utils.tasks import database_backup, settings_backup
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.