content string |
|---|
#!/usr/bin/env python
import sys, os, optparse
import chpl_platform, chpl_comm, chpl_compiler, utils
from utils import memoize
@memoize
def get(flag='target'):
if flag == 'network':
atomics_val = os.environ.get('CHPL_NETWORK_ATOMICS')
if not atomics_val:
if chpl_comm.get() == 'ugni':
... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tabs
from horizon.utils import memoized
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks.ports \
... |
"""
Corrupt known signal with point spread
======================================
The aim of this tutorial is to demonstrate how to put a known signal at a
desired location(s) in a :class:`mne.SourceEstimate` and then corrupt the
signal with point-spread by applying a forward and inverse solution.
"""
import os.path ... |
"""Demo of Essentia 'standard' mode.
This first demo will show how to use Essentia in standard mode.
This will require a little bit of knowledge of python (not that much!) and
will look like an interactive session in matlab.
We will have a look at some basic functionality:
- how to load an audio
- how to pe... |
# th30z@u1310:[Desktop]$ psql -h localhost -p 55432
# Password:
# psql (9.1.10, server 0.0.0)
# WARNING: psql version 9.1, server version 0.0.
# Some psql features might not work.
# Type "help" for help.
#
# th30z=> select foo;
# a | b
# ---+---
# 1 | 2
# 3 | 4
# 5 | 6
# (3 rows)
from cStringIO import Str... |
"""Test wallet load on startup.
Verify that a fujicoind node can maintain list of wallets loading on startup
"""
from test_framework.test_framework import FujicoinTestFramework
from test_framework.util import (
assert_equal,
)
class WalletStartupTest(FujicoinTestFramework):
def set_test_params(self):
... |
from scipy.spatial.distance import *
import scipy.io as sio
import numpy as np
#mat = sio.loadmat('../exact_match_closest_view_indices_1to100.mat')
#print mat
#closest_view_indicies = mat['closest_view_indices']
#closest_view_indicies = closest_view_indicies.squeeze()
#print closest_view_indicies
#print closest_view_i... |
import os
import datetime
from django.db import models
import utils
from conf import settings
class Account(models.Model):
"""Model for storing information about each account we want to
track.
"""
class Meta:
unique_together = (("type", "name", ), )
ordering = ("type", "name", )
... |
# If the numbers 1 to 5 are written out in words:
# one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19
# letters used in total.
# If all the numbers from 1 to 1000 (one thousand) inclusive
# were written out in words, how many letters would be used?
# NOTE: Do not count spaces or hyphens. For exam... |
import numpy as np
import lmfit
from kid_readout.analysis import mcfit
def fractional_freq_to_power(x, break_point, scale):
return scale * ((x / break_point + 1) ** 2 - 1)
def d_power_d_fractional_freq(frac_freq, break_point, scale):
return 2 * scale * (break_point + frac_freq) / break_point ** 2
def frac... |
__author__ = "Lorenzo Di Giuseppe"
__copyright__ = "Copyright 2014"
from gi.repository import Gtk
from controllers.RSATestController import RSAComunicationTest
from ui.Window import Content
from .Listener import AliceListener, BobListener
import threading
class ComunicationBox(Content):
title = "RSA comunica... |
import tacticenv
from pyasm.security import *
from pyasm.command import *
from sql import *
from search import *
import unittest
class TestCmd(Command):
def __init__(self, sobject):
self.sobject = sobject
def execute(self):
self.sobject.set_value("description", "whatever2")
self.s... |
import main
import robocup
import constants
## Returns list of all the robocup points to evaluate a function at
#
# @param num_width Number of bins width-wise
# @param num_length Number of bins length-wise
# @return List of 2d array of points to evaluate at
# Outer list is the X moving from left to right
# ... |
import os
import paleomix.common.rtools as rtools
import paleomix.tools.factory as factory
from paleomix.common.command import (
AtomicCmd,
AuxilleryFile,
InputFile,
OutputFile,
TempOutputFile,
)
from paleomix.common.formats.newick import Newick
from paleomix.node import CommandNode
from paleomix.p... |
"""
Argument management module.
"""
import logging
from os import getcwd
from re import compile
from pprint import pformat
from collections import OrderedDict
from distutils.dir_util import mkpath
from argparse import Action, ArgumentParser
from os.path import join, isabs, abspath, isfile
from . import __version__
fr... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models import permalink
from django.contrib.localflavor.us.models import PhoneNumberField
from tagging.fields import TagField
import tagging
class PlaceType(models.Model):
"""Place types model."""
title = mode... |
#!/usr/bin/env python3
import os
import sys
import pycalculix as pyc
model_name = 'import-dxf-1'
model = pyc.FeaModel(model_name)
model.set_units('m')
# set whether or not to show gui plots
show_gui = True
if '-nogui' in sys.argv:
show_gui = False
# set element shape
eshape = 'quad'
if '-tri' in sys.argv:
es... |
import datetime
import logging
import os
import sys
import dateparser
import parsedatetime
import redis
import telegram.error
from telegram import ChatAction, ParseMode
from telegram.ext import CommandHandler, Filters, MessageHandler, RegexHandler, Updater
from backend.backend import cache_date_format
from frontend.s... |
""" CType classes for C bool, this cannot represent unassigned, nor indicate exception.
"""
from .CTypeBases import CTypeBase, CTypeNotReferenceCountedMixin
class CTypeBool(CTypeNotReferenceCountedMixin, CTypeBase):
c_type = "bool"
# Return value only obviously.
helper_code = "CBOOL"
@classmethod
... |
# coding=utf-8
# fish_random.py 单元测试
# 2018.12.26 create by Hu Jun
import pytest
import datetime
from fishbase.fish_random import *
# 2018.12.26 v1.1.5 #163 create by Hu Jun
class TestFishRandom(object):
# test gen_random_str() tc
def test_gen_random_str_01(self):
assert 1 <= len(gen_random_str(1, 5... |
import argparse
import logging
import json
try:
from UserDict import UserDict
except ImportError: # pragma nocover
from collections import UserDict
class Arguments(UserDict, object):
def __init__(self, args=None):
self.log = logging.getLogger(__name__)
self.data = self._parse_arguments(arg... |
"""Routines to handle the string class registry used by declarative.
This system allows specification of classes and expressions used in
:func:`_orm.relationship` using strings.
"""
import weakref
from ... import exc
from ... import inspection
from ... import util
from ...orm import class_mapper
from ...orm import i... |
import re
import shlex
from distutils.version import LooseVersion
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.network import register_transport, to_list
from ansible.module_utils.network import NetworkError
from ansible.module_utils.shell import CliBase
from ansible.module_util... |
#!/usr/bin/env python
# Setup for wx (PyQt is default now in TraitsUI
from traits.etsconfig.api import ETSConfig
ETSConfig.toolkit = 'wx'
import wx
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from matpl... |
import csv
import datetime
try:
from hashlib import md5
except ImportError: # Python 2.4 compatibility
from md5 import new as md5
import os
import re
import sys
import urllib
def welcome():
""" """
print "#"*73
print """# Welcome to CommonsDownloader 0.1 by WikiTeam (GPL v3) ... |
import os
import logging
from itertools import chain
from uuid import uuid4
from datetime import datetime
import time
from os.path import splitext, basename
import numpy as np
from django.utils.datastructures import SortedDict
from django.contrib.gis.geos import Polygon
from eoxserver.core import Component, implement... |
"""Supporting definitions for the Python regression test."""
import sys
class Error(Exception):
"""Base class for regression test exceptions."""
class TestFailed(Error):
"""Test failed."""
class TestSkipped(Error):
"""Test skipped.
This can be raised to indicate that a test was deliberatly
skip... |
# Imports a csv file into the database
# See milk.csv as a sample
from webapp import db, models, types
from datetime import datetime
import csv
COL_DATE = 0
COL_TIME = 1
COL_PUMP = 2
COL_MOTHERS_MILK = 3
COL_POWDERED_MILK = 4
COL_COMMENT = 5
def try_import_entry(row, col, action):
if row[col]:
print 'Ad... |
from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QWidget, QStyleOption, QStyle
class DialogContainer(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.setStyleSheet("background-color: rgba(30, 30, 30, 0.75);")
self.dial... |
from ctypes import *
from ctypes.test import need_symbol
import unittest
import os
import ctypes
import _ctypes_test
class BITS(Structure):
_fields_ = [("A", c_int, 1),
("B", c_int, 2),
("C", c_int, 3),
("D", c_int, 4),
("E", c_int, 5),
... |
import cv2
import sys
import numpy as np
# ------------- CAMERA/PROJECTION PARAMETERS
focal_lenght = [3049.4772875915637, 3054.6162360490512]
principal_point = [1547.3066447988792, 994.90151571819047]
camera_matrix = np.matrix([[focal_lenght[0], 0., principal_point[0]], [0, focal_lenght[1], principal_point[1]], [0.... |
# encoding: utf-8
import curses
import weakref
import npyscreen
import email
import mimetypes
import os.path
class EmailTreeLine(npyscreen.TreeLine):
def display_value(self, vl):
return vl
if vl:
return vl.getContent().get_content_type()
else:
return ""
class Email... |
from gi.repository import GObject
import xpcom
from xpcom.components import interfaces
class ProgressListener(GObject.GObject):
_com_interfaces_ = interfaces.nsIWebProgressListener
def __init__(self):
GObject.GObject.__init__(self)
self._location = None
self._loading = False
... |
from __future__ import unicode_literals
import traceback
from requests.compat import urljoin
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.helper.common import convert_size, try_int
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class ExtraT... |
# flake8: noqa
# yapf: disable
# __import_begin__
from functools import partial
import numpy as np
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from filelock import FileLock
from torch.utils.data import random_split
import torchvision
import torchvision.trans... |
from __future__ import print_function
import os
import sys
from setuptools import setup, Extension
import numpy as np
import codecs
def read(fname):
with codecs.open(fname, 'r', 'latin') as f:
return f.read()
def read_to_rst(fname):
try:
import pypandoc
rstname = "{}.{}".format(os.path... |
"""Script to prepare a node for joining a cluster.
"""
import os
import os.path
import optparse
import sys
import logging
import OpenSSL
from ganeti import cli
from ganeti import constants
from ganeti import errors
from ganeti import pathutils
from ganeti import utils
from ganeti import serializer
from ganeti import... |
# -*- coding: Latin-1 -*-
"""
@file Path.py
@author Sascha Krieg
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-04-17
Contains paths which are needed frequently
SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors
All ri... |
"""Fake RPC implementation which calls proxy methods directly with no
queues. Casts will block, but this is very useful for tests.
"""
import inspect
# NOTE(russellb): We specifically want to use json, not our own jsonutils.
# jsonutils has some extra logic to automatically convert objects to primitive
# types so tha... |
import os
import re
import sys
from collections import Counter
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import models
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
eprint("Read files...")
with open('./replacements.txt') as f:
replacements = dict([x... |
from numpy import maximum
from numpy import zeros
from gwlfe.AFOS.GrazingAnimals.Loads.GrazingN import GrazingN
from gwlfe.AFOS.GrazingAnimals.Loads.GrazingN import GrazingN_f
from gwlfe.AFOS.GrazingAnimals.Loads.InitGrN import InitGrN
from gwlfe.AFOS.GrazingAnimals.Loads.InitGrN import InitGrN_f
from gwlfe.Memoizatio... |
"""
Utilities for working with lists of model instances which represent
trees.
"""
from __future__ import unicode_literals
import copy
import csv
import itertools
import sys
from django.utils.six import next, PY3, text_type
from django.utils.six.moves import zip
from django.utils.translation import ugettext as _
__al... |
from __future__ import division, print_function, absolute_import
import tflearn
from tflearn.data_utils import to_categorical, pad_sequences
import csv
import numpy as np
from sklearn import metrics, cross_validation
# import pandas
import tensorflow as tf
from tflearn.layers.recurrent import bidirectional_rnn, Basi... |
# Training pipeline loading images from filepaths.
import tensorflow as tf
import numpy as np
import random
import preprocess
from argparse import ArgumentParser
def main(args):
random.seed(100)
# Load test dataset, used for evaluation
test_folders = ['../datasets/test_datasetA',]
test_imgs, test_labels, test_... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class RestorePost(Choreography):
def __init__(self, temboo_session):
"""
Create a n... |
from __future__ import absolute_import
import unittest2
from oslo_config import cfg
from st2common.constants.api import DEFAULT_API_VERSION
from st2common.util.api import get_base_public_api_url
from st2common.util.api import get_full_public_api_url
from st2tests.config import parse_args
from six.moves import zip
pa... |
class IEC104Register(object):
def __init__(self, category_id, addr, val, relation):
self.category_id = category_id
self.addr = addr
self.val = val
self.relation = relation
def set_val(self, val):
self.val = val |
'''
Takes file names from the output/ folder and parses the information into
readable values and produces a graph. Use this module as an executable to
process all length frequency information for a single problem, such as:
python freqplot.py output/neutral_100_*.frq
Do not mix problems or problem sizes in a single r... |
import atexit
import coloredlogs
import logging
import os
import shutil
import signal
import socket
import sys
import urllib.parse
from aiohttp import web
from coloredlogs import syslog
from vj4 import app
from vj4.util import options
options.define('listen', default='http://127.0.0.1:8888', help='Server listening ad... |
"""
Catch built-ins: inline redefinition option
"""
traceMe = False
def trace(*args):
if traceMe: print('[' + ' '.join(map(str, args)) + ']')
def accessControl(failIf):
def onDecorator(aClass):
class onInstance:
def __init__(self, *args, **kargs):
self.__wrapped = aClass(*a... |
"""PVN (Pievienotās vērtības nodokļa, Latvian VAT number).
The PVN is a 11-digit number that can either be a reference to a legal
entity (in which case the first digit > 3) or a natural person (in which
case it should be the same as the personal code (personas kods)). Personal
codes start with 6 digits to denote the b... |
{
"name": "Sale delivery type",
"version": "1.0",
"author": "Pexego",
'website': 'www.pexego.es',
"category": "Sales",
"description": """
Sales delivery type
========================================
* Add the delivery type field to sales.
""",
"depends": ["base", "sale", "crm_claim_rma_... |
import re
from time import time
from gi.repository import GObject
from pychess.ic import IC_STATUS_OFFLINE, IC_STATUS_ACTIVE, IC_STATUS_PLAYING, IC_STATUS_BUSY, \
GAME_TYPES_BY_FICS_NAME, BLKCMD_FINGER
from pychess.Utils.const import WHITE, BLACK
from pychess.System.Log import log
types = "(?:blitz|standard|ligh... |
"""
Support for the Netatmo devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/netatmo/
"""
import logging
from datetime import timedelta
from urllib.error import HTTPError
import voluptuous as vol
from homeassistant.const import (
CONF_API_KE... |
import pytest
import os.path as osp
from sisl.io.vasp.chg import *
import numpy as np
pytestmark = [pytest.mark.io, pytest.mark.vasp]
_dir = osp.join('sisl', 'io', 'vasp')
def test_graphene_chg(sisl_files):
f = sisl_files(_dir, 'graphene', 'CHG')
grid = chgSileVASP(f).read_grid()
gridf32 = chgSileVASP(f... |
import json
import datetime
import tornado.web
from status.util import SafeHandler
class PricingBaseHandler(SafeHandler):
"""Base class that other pricing handlers should inherit from.
Implements most of the logic of the pricing that other classes should reuse
"""
# _____________________________ HEL... |
#-*- coding=utf-8 -*-
__author__ = 'bluven'
import logging
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.utils.translation import ugettext_lazy as _
from django.db.models import Q
from biz.idc.models import DataCe... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys, os, math
from foundation import Indication
from moving_average import MovingAverage, SMA
from scipy.stats import stats
from numpy import int32
class BollingerBands (Indication):
"""
t時点におけるボリンジャーバンドを表すクラスです.
"""
@classmethod
def isRealIndication(cls): retur... |
"""The tests for the Ring binary sensor platform."""
import os
import unittest
import requests_mock
from homeassistant.components.binary_sensor import ring
from homeassistant.components import ring as base_ring
from tests.components.test_ring import ATTRIBUTION, VALID_CONFIG
from tests.common import (
get_test_co... |
from setuptools import setup
from Cython.Build import cythonize
from Cython.Distutils import Extension
from distutils.command.build_ext import build_ext
import glob
import os
import os.path
import numpy
import mpi4py
package_basedir = os.path.abspath(os.path.dirname(__file__))
def build_pfft(prefix, compiler, cflags... |
# -*- encoding: utf-8 -*-
"""
Kupfer's Contacts API
Main definition and *constructor* classes.
Constructor classes such as EmailContact are used to conveniently construct
contacts with common traits. To *use* contacts, always use ContactLeaf, asking
for specific slots to be filled.
"""
import re
from kupfer import i... |
#The version 2, morph the common RefROI into individual space, then compute
#phase lock indices and connectivity under the individual space. Last morph
#the phase lock estimates into the common space. It is faster then version3
import numpy as np
import mne, sys, os
from mne.datasets import sample
from mne.fiff import ... |
from __future__ import unicode_literals
import os
import mock
import pytest
import six
from .. import lint as lint_mod
from ..lint import filter_whitelist_errors, parse_whitelist, lint
_dummy_repo = os.path.join(os.path.dirname(__file__), "dummy")
def _mock_lint(name):
wrapped = getattr(lint_mod, name)
re... |
"""Status formatter."""
from aquilon.worker.formats.formatters import ObjectFormatter
from aquilon.aqdb.model import HostLifecycle
from aquilon.aqdb.model.hostlifecycle import (Ready, Almostready, Build,
Rebuild, Decommissioned,
... |
from Tkinter import *
import sttsotpt
class sttscnsl:
def show(self,mainfrm):
txtfont=("FreeSerif", 10,"bold")
otptsttsfrm=Frame(mainfrm,relief=SOLID,borderwidth=1)
#---------------label for status console------------------------------------------------------------
oplblfrm=Frame(otptsttsfrm,relief=SOLID,h... |
import argparse
import sys
# NB: also update setup.py when changing
__version__ = '1.0.0.4'
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
args = get_args(argv)
src = args.src
dest = args.dest
src_offset = int(args.src_offset, 0)
dest_offset = args.dest_offset
append... |
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import time
import re
import ssl
import requests
from distutils.version import StrictVersion
from threading import Thread, Event
from queue import Queue
from flask_cors import CORS
from flask_cache_bust import init_cache_busting
from ... |
"""
Represents a single job to be run
"""
import os
import sys
import subprocess
import time
import logging
from exceptions import MissingInputFileError
from log import get_logger
def format_time(t = time.localtime()):
if isinstance(t, float):
t = time.localtime(t)
return time.strftime("%Y/%m/%d %... |
from pynestml.symbols.symbol import Symbol, SymbolKind
class FunctionSymbol(Symbol):
"""
This class is used to store a single function symbol, e.g. the definition of the function max.
Attributes:
param_types (list(TypeSymbol)): A list of the types of parameters.
return_type (type_symbol): ... |
#!/usr/bin/env python3
# StreamTools by Infected
from .rainbow import msg
from serial import Serial
from time import sleep
MAT_WIDTH = 64
MAT_HEIGHT = 16
class Stream:
def __init__(self, matrix=True, tty="/dev/ttyACM0"):
self.matrix = matrix
self.byte = bytes(1)
self.length = 1024
... |
#!/usr/bin/env python
"""
Some small edits to json output.
* Float decimals are truncated to three digits
* [x, y, z] vectors are displayed on one line
* Converts numpy arrays to lists and defined objects to dictionaries
* Atoms and bonds are on one line each (looks more like other chem formats)
"""
from itertools... |
from uuid import uuid4
from urlparse import urlparse
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
"""
General SQLAlchemy helpers for easy scaling.
`ObjectId` uuid4-based object id for sharding (32-bit).
`create_session_factory` SQLAlchemy Session Class maker.
`get_host_from_uri` fet... |
# -*- coding: utf-8 -*-
import unittest
from cwr.grammar.factory.config import rule_terminal
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
class TestConfigTerminalRule(unittest.TestCase):
def setUp(self):
self._rule = rule_terminal
def test_not_options(sel... |
from __future__ import print_function
import aaf
import aaf.mob
import aaf.define
import aaf.iterator
import aaf.dictionary
import aaf.storage
import unittest
import traceback
import os
cur_dir = os.path.dirname(os.path.abspath(__file__))
sandbox = os.path.join(cur_dir,'sandbox')
if not os.path.exists(sandbox):
... |
# FIXME[hack]: this is just using a specific keras network as proof of
# concept. It has to be modularized and integrated into the framework
import os
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
import tensorflow as tf
from tensorflow import keras
import numpy as np
print(f"nu... |
from django.db import models
from markitup.fields import MarkupField
from django.core.urlresolvers import reverse
from django.conf import settings
class Talk_Type(models.Model):
talk_types = (
('S', "Short_Talk"),
('L', "Long_Talk"),
('T', "Tutorial"),
)
name = models.CharField(... |
__author__ = "Sean Toner"
__license__ = "Apache License 2.0"
__version__ = "0.1"
__email__ = "<EMAIL>"
__status__ = "Alpha"
from subprocess import Popen, PIPE, STDOUT
import threading
import os
import shlex
from functools import wraps
try:
import queue
except ImportError:
import Queue as queue
from iridium.co... |
from typing import List
from mlagents.torch_utils import torch
from mlagents_envs.base_env import ActionSpec
from mlagents.trainers.torch.agent_action import AgentAction
from mlagents.trainers.torch.utils import ModelUtils
class ActionFlattener:
def __init__(self, action_spec: ActionSpec):
"""
A ... |
from awx.main.models import Instance, InstanceGroup
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
"""List instances from the Tower database
"""
def handle(self, **options):
super(Command, self).__init__()
for instance in Instance.objects.all():
... |
import unittest
import nose.tools
import numpy as np
from mia.utils import (preprocess_image, cluster_image, clusters_from_labels,
sort_clusters_by_density)
from ..test_utils import get_file_path
class UtilsRegressionTest(unittest.TestCase):
def test_load_real_image_and_mask(self):
... |
"""
@author: Ewan Higgs (University of Ghent)
"""
from common import XML_PREAMBLE, HADOOP_STYLESHEET, kv2xml
from vsc.utils import fancylogger
_log = fancylogger.getLogger(fname=False)
def _write_xml(outfile, options, template_resolver):
output = XML_PREAMBLE + HADOOP_STYLESHEET + "<configuration>\n"
for k, ... |
import configparser
import twython
class TweetVacAuthException(Exception):
"""An error with authorization occurred."""
class TweetVacHttpException(Exception):
"""An error with with a http request occurred."""
class TweetVac(object):
"""A vacuum for sucking down tweets using Twitter's API"""
def _... |
import logging
import os
import time
from core import path_util
path_util.AddAndroidPylibToPath()
from pylib.utils import shared_preference_utils
from telemetry.core import android_platform
from telemetry.core import util
from telemetry.page import shared_page_state
from contrib.vr_benchmarks.desktop_runtimes import op... |
from data import structure
cd = "from copy import deepcopy\n\n"
for tbl in structure.STRUCT:
# Class header
S2P = structure.SQL_TO_PY_TYPE
camelTbl = structure.CamelCase(tbl)
cd += "class %s():\n" % camelTbl
cd += " "*4 + "def __init__(self,dat):\n"
# Add data type checks
for field in st... |
#! /usr/bin/env python
from distutils.core import setup, Extension
from distutils.util import get_platform
import shutil
import os, sys
def buil_all():
packages=['miasm2',
'miasm2/arch',
'miasm2/arch/x86',
'miasm2/arch/arm',
'miasm2/arch/aarch64',
... |
# Stock Trading AI
def sellForProfit(stock):
""" If conditions are met then we return True to notify user
to sell stock
Conditions: if stock's current price has maintained a 10% PROFIT
for the last 3 checkups: sell stock """
criteria_met = True
ten_profit = stock.purchasePrice*1.1
... |
## Bot for adding Prop65 ID
from wikidataintegrator import wdi_core, wdi_login, wdi_helpers
from wikidataintegrator.ref_handlers import update_retrieved_if_new_multiple_refs
import pandas as pd
from pandas import read_csv
import requests
import time
from datetime import datetime
import copy
## Here are the object QI... |
try: import simplejson as json
except: import json
import os
import re
import codecs
import sys
if sys.version_info < (3, 0):
python3 = False
else:
python3 = True
# All strings are unicode in Python 3.
# See http://stackoverflow.com/questions/6812031/how-to-make-unicode-string-with-python3
if python3:
uni... |
# vim:ts=4:et:nowrap:fileencoding=utf-8
#
# imports
# PySol imports
from pysollib.gamedb import registerGame, GameInfo, GI
from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.util import ACE
from pysollib.stack import \
DealRowTalonStack, \
Yukon_SS_RowStack, \
i... |
#!/usr/bin/env python
# coding=utf-8
"""632. Square prime factors
https://projecteuler.net/problem=632
For an integer $n$, we define the _square prime factors_ of $n$ to be the
primes whose square divides $n$. For example, the square prime factors of
$1500=2^2 \times 3 \times 5^3$ are $2$ and $5$.
Let $C_k(N)$ be th... |
from django.test import TestCase
class AboutTest(TestCase):
# local urls won't work, coz templates refer to repository_index
#urls = 'about.urls'
def test_index(self):
r = self.client.get('/about/')
self.assertEqual(r.context['section'], 'about')
self.assertTemplateUsed(r, 'about/i... |
import datetime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from pyfea.orm.models import Base, Model, SourceFile
# Global application scope. Create a Session class, engine and so on.
Session = sessionmaker()
engine = create_engine("sqlite:///:memory:")
class TestModels:
def setu... |
import pygame, sys
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
win_width, win_height = 640, 480
windowSurfaceObj = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption('Sliding bar')
grayColor = pygame.Color(0, 0, 0)
bars_contrast = 0.1 # luminance contrast between... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import json
import re
from threading import Timer
import sublime
from .console_logging import getLogger
from .settings import get_settings_param
logger = getLogger(__name__)
def get_settings(view):
"""Get plugin settings.
:type view: ... |
"""
LiveCD stage1 target
"""
# NOTE: That^^ docstring has influence catalyst-spec(5) man page generation.
import os
import types
import string
from catalyst.support import (normpath,
touch, cmd)
from catalyst.fileops import ensure_dirs
from catalyst.base.stagebase import StageBase
class livecd_stage1(StageBase):... |
#!/usr/bin/env python3
import os.path
import sys
import itertools
import lxml.etree
# This utility scrapes the DICOM standard document in DocBook format, finds the appropriate tables,
# and extracts the data needed to build the lists of DICOM attributes, UIDs and value representations.
# If the files part05.xml, part... |
import sys
from oslo_config import cfg
from oslo_upgradecheck import common_checks
from oslo_upgradecheck import upgradecheck
from tacker._i18n import _
CONF = cfg.CONF
class Checks(upgradecheck.UpgradeCommands):
"""Contains upgrade checks
Various upgrade checks should be added as separate methods in thi... |
import tensorflow as tf
from .network import Network
from lstm.utils.config import cfg
class LSTM_train(Network):
def __init__(self, trainable=True):
self.inputs = []
self.data = tf.placeholder(tf.float32, shape=[None, None, cfg.NUM_FEATURES ], name='data') #N*t_s*features*channels
#sel... |
# -*- coding: 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):
# Adding model 'UserProfile'
db.create_table('user_profile', (
(u'id', self.gf('django.db.models... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.