content stringlengths 4 20k |
|---|
"""Creates an estimator to train the Transformer model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tempfile
import random
import numpy.random
from six.moves import xrange # pylint: disable=redefined-bui... |
from contextlib import contextmanager
from dataclasses import dataclass
from pants.base.build_environment import get_buildroot
from pants.base.workunit import WorkUnitLabel
from pants.task.testrunner_task_mixin import PartitionedTestRunnerTaskMixin, TestResult
from pants.util.memo import memoized_property
from pants.u... |
from twisted.internet import defer
from synapse.api.errors import AuthError, SynapseError, Codes
from synapse.types import RoomAlias
from .base import ClientV1RestServlet, client_path_pattern
import simplejson as json
import logging
logger = logging.getLogger(__name__)
def register_servlets(hs, http_server):
... |
#!/usr/bin/env python
"""
Copyright 2015-2017 Knights Lab, Regents of the University of Minnesota.
This software is released under the GNU Affero General Public License (AGPL) v3.0 License.
"""
import click
import os
from ninja_utils.utils import verify_make_dir
from ninja_utils.parsers import FASTA
from dojo.datab... |
from games.abstract_game import AbstractGame
import subprocess
import json
import numpy as np
from threading import Lock
from constants import *
import platform
class Torcs(AbstractGame):
MAX_NUMBER_OF_TORCS_PORTS = 10
master_lock = Lock()
port_locks = [Lock() for _ in range(MAX_NUMBER_OF_TORCS_PORTS)]
... |
"""
EasyBuild support for pomkl compiler toolchain (includes PGI compilers, OpenMPI,
Intel Math Kernel Library (MKL), and Intel FFTW wrappers).
:author: Stijn De Weirdt (Ghent University)
:author: Kenneth Hoste (Ghent University)
:author: Bart Oldeman (McGill University, Calcul Quebec, Compute Canada)
"""
from easybu... |
from __future__ import absolute_import, division, print_function
from collections import defaultdict
from future.builtins import zip
import numpy as np
from skbio.tree import TreeNode
def _walk_clades(trees, weights):
"""Walk all the clades of all the trees
Parameters
----------
trees : list of Tr... |
from bitmovin.errors import InvalidTypeError
from bitmovin.resources.models.encodings.drms import PlayReadyDRMAdditionalInformation
from bitmovin.utils import Serializable
class CENCPlayReadyEntry(Serializable):
def __init__(self, la_url=None, pssh=None, additional_information=None):
super().__init__()
... |
import OpenGL.GL as GL
import pygame
import numpy
import math
vertex_shader = """
#version 330
in vec2 position;
in vec2 coord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec2 texcoord;
void main()
{
vec4 pos = vec4(position.xy, 1.0f, 1.0f);
gl_Position = projection * view * model ... |
'''
JSON related utilities.
This module provides a few things:
1) A handy function for getting an object down to something that can be
JSON serialized. See to_primitive().
2) Wrappers around loads() and dumps(). The dumps() wrapper will
automatically use to_primitive() for you if needed.
3) Th... |
import os
import zipfile
import datetime
from django.core.management.base import BaseCommand, CommandError
from django.utils.text import slugify
from django.template.loader import render_to_string
from django.contrib.staticfiles import finders
from tracker.models import Grant, FinanceStatus
class GrantDumper(object):... |
"""
A widget and supporting classes for watching the events sent to some other widget.
"""
import wx
from wx.lib.mixins.listctrl import CheckListCtrlMixin
#----------------------------------------------------------------------------
# Helpers for building the data structures used for tracking the
# various event bind... |
# Code shared by distutils and scons builds
import sys
from os.path import join
import warnings
import copy
import binascii
from distutils.ccompiler import CompileError
#-------------------
# Versioning support
#-------------------
# How to change C_API_VERSION ?
# - increase C_API_VERSION value
# - record the ha... |
import os
import subprocess
from tempfile import mkstemp
from shutil import move
from os import remove, close
######### CHECK IF UPGRADED ###############
#updateToLatest = False
#inputCorrect = False
#while inputCorrect == False:
# update = raw_input("Do you want to upgrade Raspbian to latest update (might take up ... |
import glob
import markdown
import os
import re
from xml.etree import ElementTree
#--------------------------------------
# configuration: set constant to None if you do not want to use the featrue
# if not None replace title becomes DEFAULT_APP_TITLE (translation)
DEFAULT_APP_TITLE = "A Photo Manager"
# all paths a... |
import tables as tb
import sys
import networkx as nx
import numpy as np
import pandas as pd
class MaxEdgeFinder(object):
"""docstring for MaxEdgeFinder"""
def __init__(self, handle, node_idx):
super(MaxEdgeFinder, self).__init__()
self.handle = handle
self.df = None # full transmission store; conventionally I... |
import os
from alembic import config as alembic_config
from neutron.db.migration import cli as n_cli
CONF = n_cli.CONF
def get_alembic_config():
config = alembic_config.Config(os.path.join(os.path.dirname(__file__),
'alembic.ini'))
config.set_main_option('scr... |
#TODO: Set dbkey to proper UCSC build, if known
import urllib
from galaxy import datatypes, config
import tempfile, shutil
def exec_before_job( app, inp_data, out_data, param_dict, tool=None):
"""Sets the name of the data"""
data_name = param_dict.get( 'name', 'HbVar query' )
data_type = param_dict.get( '... |
import csv
from urlparse import urlparse
from django import http
from django.conf import settings
from django.contrib import admin
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.core.files.storage import default_storage as storage
from django.db.models.loading impor... |
__author__ = 'alan'
from . import rssapp_blueprint
from flask import render_template
from os import path
from logging import getLogger
from flask_rss import customlogg
from settings import Configuration
import rss
logger = getLogger(__name__)
config = Configuration()
@rssapp_blueprint.route('/')
def index():
try:... |
#!/usr/bin/env python
import random
import string
def read_file(file):
read_data = []
with open(file, 'r') as f:
for line in f:
read_data.append(line)
f.closed
return read_data
def sanitize_input(trigramList):
translator = str.maketrans({key: None for key in string.punctuati... |
import os
import unittest
import IECore
import Gaffer
import GafferImage
class GradeTest( unittest.TestCase ) :
checkerFile = os.path.expandvars( "$GAFFER_ROOT/python/GafferTest/images/checker.exr" )
# Test that when gamma == 0 that the coresponding channel isn't modified.
def testChannelEnable( self ) :
i = ... |
#!/usr/bin/env python
'''code description'''
# pylint: disable = I0011, E0401, C0103
class Solution(object):
'''Solution description'''
def func(self, nums, target):
'''
Solution function description
'''
if nums is None or len(nums) < 3:
return 0
if len(nums)... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import xlsxwriter
from mongodb import db, conn
def export_to_xlsx(collect, pre_book_name, skip_num, limit_num):
# create a workbook
book_name = pre_book_name + str(skip_num//limit_num+1) + '.xlsx'
workbook = xlsxwriter.Workbook(book_name) # create a workshee... |
from third_party.odict import OrderedDict
from safe.impact_functions.core import (
FunctionProvider, get_hazard_layer, get_exposure_layer, get_question)
from safe.storage.vector import Vector
from safe.common.utilities import (ugettext as tr, format_int)
from safe.common.tables import Table, TableRow
from safe.engi... |
import inspect
import torch
deserialized_objects = {}
restore_location = torch.serialization.default_restore_location
def _check_container_source(container_type, source_file, original_source):
current_source = inspect.getsource(container_type)
if original_source != current_source:
if container_type.dum... |
"""Base Transitland Entity."""
import json
import mzgeohash
import geom
import util
import errors
class Entity(object):
"""A Transitland Entity."""
# OnestopID prefix.
onestop_type = None
def __init__(self, **data):
"""Set name, Onestop ID, and geometry."""
if 'onestop_id' in data:
data['one... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
De-duplicate available sensors from different vendors if they are too close
geographically. When two sensors in close proximity are found, hide the lower
ranking one based on the PRIORITY list.
"""
import argparse
import itertools
from geopy.distance import distance
impor... |
"""
Copyright 2015-2020 Knights Lab, Regents of the University of Minnesota.
This software is released under the GNU Affero General Public License (AGPL) v3.0 License.
"""
import unittest
import shutil
import pkg_resources
import os
import tempfile
from shogun.utils import hash_file, read_checksums
#TODO: Implement ... |
import jinja2
import os
import json
from pprint import pprint
from operator import itemgetter
import sys
import subprocess
import shutil
import platform
import pdb
addresses = {}
sourceDir = ""
deployDir = ""
startDir = os.path.split(os.path.realpath(__file__))[0] #Don't use os.getcwd() as script may be invoked from a... |
#STANDARD LIB
from datetime import datetime
from decimal import Decimal
from itertools import chain
import warnings
#LIBRARIES
from django.apps import apps
from django.conf import settings
from django.db.backends.utils import format_number
from django.db import IntegrityError
from django.utils import timezone
from go... |
from django.contrib.auth import get_user_model
from cmj.agenda.models import Evento
from cmj.cerimonial.models import Perfil, EnderecoPerfil, EmailPerfil,\
TelefonePerfil, LocalTrabalhoPerfil, DependentePerfil, OperadoraTelefonia,\
NivelInstrucao, EstadoCivil, Contato, FiliacaoPartidaria, Dependente,\
Loca... |
"""
test.test_utils
~~~~~~~~~~~~~~~
Tests for the utils module of pdlearn.
"""
import pytest
import pdlearn.utils
import pandas as pd
import numpy as np
LIST = [1, 2]
ZERO_D_ARRAY = np.array(0)
ONE_D_ARRAY = np.array([1, 2])
TWO_D_ARRAY = np.array(
[
[1, 2],
[3, 4]
])
SERIES = pd.Series(... |
class Node(object):
def __init__(self, value, succeeding=None, previous=None):
self.value = value
self.succeeding = succeeding
self.previous = previous
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push... |
from openstack.tests.unit import base
import uuid
from openstack.load_balancer.v2 import flavor_profile
IDENTIFIER = uuid.uuid4()
EXAMPLE = {
'id': IDENTIFIER,
'name': 'acidic',
'provider_name': 'best',
'flavor_data': '{"loadbalancer_topology": "SINGLE"}'}
class TestFlavorProfile(base.TestCase):
... |
#!/usr/bin/env python
import subprocess
from ConfigParser import ConfigParser, NoOptionError
import os
import time
import sys
import re
from contextlib import closing
DMSETUP_CMD = "/usr/sbin/dmsetup"
PVS_CMD = "/sbin/pvs"
VGS_CMD = "/sbin/vgs"
LVS_CMD = "/sbin/lvs"
PVCREATE_CMD = "/sbin/pvcreate"
VGCREATE_CMD = "/sbi... |
import LowVoltage as _lv
import LowVoltage.testing as _tst
class BatchWriteItemLocalIntegTests(_tst.LocalIntegTestsWithTableH):
def test_simple_batch_put(self):
r = self.connection(_lv.BatchWriteItem().table("Aaa").put(
{"h": u"1", "a": "xxx"},
{"h": u"2", "a": "yyy"},
... |
import logging
logging.basicConfig(level=logging.ERROR)
import sys
import os
DIR = os.path.abspath(os.path.normpath(os.path.join(__file__,
'..', '..', '..', 'trytond')))
if os.path.isdir(DIR):
sys.path.insert(0, os.path.dirname(DIR))
import unittest
import doctest
from lxml import etree
import time
import optp... |
"""Module for computing evaluation scores.
"""
import math
def count_ngram(token_c, token_r, n):
"""Count n-grams of length n."""
clipped_count = 0
count = 0
r = 0
c = 0
# Calculate precision
ref_counts = []
ref_lengths = []
# Build dictionary of ngram counts
ngram_d = {}
ref_lengths.append(l... |
import os
from telemetry.core import util
from telemetry.page import page as page_module
from telemetry.page.actions import scroll
from telemetry.unittest import tab_test_case
class ScrollActionTest(tab_test_case.TabTestCase):
def setUp(self):
self._extra_browser_args.append('--enable-gpu-benchmarking')
sup... |
'''
Command line argument parser for neon deep learning library
This is a wrapper around the configargparse ArgumentParser class.
It adds in the default neon command line arguments and allows
additional arguments to be added using the argparse library
methods. Lower priority defaults can also be read from a configura... |
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from . import schemes
from . import transport as t
__all__ = ['Request']
class Request(object):
"""A TChannel request.
This is sent by callers and received by registered handlers.
:ivar body:
The payload... |
from mongoengine import Document, StringField, IntField
from django.conf import settings
from crits.core.crits_mongoengine import CritsBaseAttributes, CritsSourceDocument
from crits.core.crits_mongoengine import CritsActionsDocument
from crits.core.fields import getFileField
from crits.pcaps.migrate import migrate_pca... |
"""
Unit tests for the
`iris.aux_factory.OceanSigmaFactory` class.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests... |
import hashlib
from flask import url_for, jsonify
from core.manager import BaseManager
from core.plugins.lib.proxies import PluginViewProxy
from core.util import api_url_for, get_cls
from core.database.models import PluginView
from core.views.permissions import ViewPermissionsManager
class InvalidViewException(Except... |
# -*- coding: utf-8 -*-
from errno import EEXIST
import logging
from pkg_resources import resource_filename, resource_listdir
from path import Path
DEMO_BED_NAME = 'hgnc.min.bed'
log = logging.getLogger(__name__)
def setup_demo(location, force=False):
"""Copy demo files to a directory.
\b
LOCATION: dir... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import csv
from datetime import date, datetime, timedelta
import translitcodec
from enrollme import EnrollMeClient
import settings
WEEKDAYS = dict(Pn=0, Wt=1, Sr=2, Cz=3, Pt=4, Sb=5, Nd=6)
TODAY = date.today()
WEE... |
import json
import logging
from django.conf import settings
from .models import Map, MapLayer
logger = logging.getLogger(__name__)
def _layer_json(layers, sources):
"""
return a list of layer config for the provided layer
"""
server_lookup = {}
def uniqify(seq):
"""
get a list ... |
import sys, struct, re, string, traceback, os, glob, pprint
_recordsz_re = re.compile("(?P<ty>[^0-9]+)(?P<sz>[0-9]+)\.dbb")
NUL = '\x00'
NULNUL = NUL+NUL
HDR_SZ = 8
SKR_MARKER = struct.pack("4B", 0x6c, 0x33, 0x33, 0x6c)
SKR_MARKER_LEN = 4
SKR_RECSZ_LEN = 4
SKR_HDR_LEN = SKR_MARKER_LEN+SKR_RECSZ_LEN
SKR_SE... |
from datetime import date
from optparse import make_option
from django.core.management.base import NoArgsCommand
from uwcs_website.memberinfo.models import Term
from uwcs_website.events.models import EventType, Location
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option... |
"""
Test helpers for testing course block transformers.
"""
from mock import patch
from course_modes.models import CourseMode
from lms.djangoapps.courseware.access import has_access
from openedx.core.djangoapps.content.block_structure.tests.helpers import clear_registered_transformers_cache
from openedx.core.djangoapp... |
from api.urls import router
from django.core.management.base import BaseCommand
import requests
import logging
logger = logging.getLogger('urltest')
class Command(BaseCommand):
"""
Command class responsible for checking urls.
"""
help = "urltest <host> [options]. Checking http_response for every lin... |
"""
Contains basic hyperparameter optimizations.
"""
import numpy as np
import os
import itertools
import tempfile
import shutil
import collections
import logging
from functools import reduce
from operator import mul
from typing import Dict, List, Optional
from deepchem.data import Dataset
from deepchem.trans import T... |
""" Loss functions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
# TODO: check to see if we can separate generator
class GanTypes:
jsd = "jsd" # Jensen-Shannon Divergence aka Maximum Likelihood Estimate.
emd = "emd" ... |
import gnupg
import os
from gnupg._util import _which
__author__ = 'fbernitt'
class GnuPGInitializer(object):
""" Initializes GnuPG and generates a keypair
see: https://www.gnupg.org/documentation/manuals/gnupg-devel/Unattended-GPG-key-generation.html
"""
def create_key_pair(self, gnupg_home, em... |
"""
************************************************************************
FOR THE TIME BEING WHATEVER MODIFICATIONS ARE APPLIED TO THIS FILE
SHOULD ALSO BE APPLIED TO sdk_repository IN ANY OTHER PARTNER REPOS
************************************************************************
"""
import itertools
import json
im... |
import math
import random
from stamp.metagenomics.plugins.statisticalTests.Fishers import Fishers
from stamp.metagenomics.plugins.statisticalTests.GTest import GTest
from stamp.metagenomics.plugins.statisticalTests.GTestYates import GTestYates
from stamp.metagenomics.plugins.statisticalTests.DiffBetweenProp import Dif... |
import cosmos
import time
import os
import subprocess, commands
def isvmalive(name):
cmd = "xl list | grep \"%s\" | grep \"sc\"" % name
domid = cosmos.domid(name)
ret, output = commands.getstatusoutput(cmd)
print output
if len(output) > 0:
return domid
return 0
xen_config = "./etc/xen/... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
from django.db import models
from django_extensions.db.fields import ShortUUIDField
from enumfields import EnumIntegerField, Enum
# lapse models
class AutoLapseOutputSizes(Enum):
ORIGINAL = 0
BIGGISH = 1
DEFAULT = 2
PREVIEW = 3
# have these be auto-genned anyway?
THUMB = 4
THINYTHUMB = 5
... |
import unittest
from datetime import datetime, timedelta
import os
import glob
import numpy as np
from opendrift.readers import reader_netCDF_CF_generic
from opendrift.readers import reader_ROMS_native
from opendrift.models.openoil import OpenOil
from opendrift.models.physics_methods import verticaldiffusivity_Large1... |
"""Functions to export documents and items."""
import csv
import datetime
import os
from collections import defaultdict
import openpyxl
import yaml
from doorstop import common, settings
from doorstop.common import DoorstopError
from doorstop.core.types import iter_documents, iter_items
LIST_SEP = '\n' # string sep... |
#
# STFLAME1 - A detached flat flame stabilized at a stagnation point
#
# This script simulates a lean hydrogen-oxygen flame stabilized in
# a strained flowfield at an axisymmetric stagnation point on a
# non-reacting surface. The solution begins with a flame attached
# to the inlet (burner), and the mass ... |
# -*- coding: utf-8 -*-
"""fix nullable.
Revision ID: 4d165186b4ed
Revises: 7fde00129eb6
Create Date: 2016-01-14 14:44:45.878579
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '4d165186b4ed'
down_revision = '7fde00129eb6'
branch_labels = None
depends_on = None... |
'''
This case can not execute parallelly
@author: quarkonics
'''
import os
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operatio... |
"""Functional tests for depthwise convolutional operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.compiler.tests import xla_test
from tensorfl... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import json
import os
from pants.base.exceptions import TaskError
from pants.task.repl_task_mixin import ReplTaskMixin
from pants.util.contextutil import pushd, tempo... |
#!usr/bin/env python3
#
#
#
#
#
## this will be the main test file until I have a more complete version then this will probably become the main file
#dependenicesL
from iNR import IrSensor, PttNormThreadLocks
import socket
from pathlib import Path
#from datasave import InitalSavedData
import stored
import os
from m... |
from django.test import TestCase
from django.core.urlresolvers import reverse, resolve
from django.test.client import RequestFactory
from django.http import Http404
from contacts_and_people.models import (
Site, Person, Building, Entity, Membership
)
from contacts_and_people.views import contacts_and_people
fr... |
#!/usr/bin/env python
#@file runner.py
import os
import sys
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '..\..\Python_functions'))
#sys.path.insert(0,'C:\Users\ArminAskari\Desktop\Berkeley 2013-2017\Research\CVT\ArminModify\Python_functions')
from getTrajectory import *
import optparse
import subproc... |
"""tests for utils.py"""
# pylint: disable=protected-access, missing-function-docstring
import os
from unittest.mock import MagicMock, call, patch
from ncbitax2lin import utils
def test_maybe_backup_file_when_file_path_does_not_exist() -> None:
with patch("os.path.exists", return_value=False) as mock_exists:
... |
__author__ = 'kevin'
import sys
from os import path as ospath
PRINT_FRIENDLY = True
class BColors:
def __init__(self):
pass
if PRINT_FRIENDLY:
BOLD = '\033[1m'
UNDERLINE = '\033]4m'
ENDC = '\033[0m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033... |
import warnings, thread
try:
from bsddb import db
except ImportError:
from bsddb3 import db
from os import makedirs
from os.path import exists, join
from time import sleep
import logging
from rdflib.store import NO_STORE
from rdflib.store.Sleepycat import Sleepycat
if db.version() < (4,3,29):
warnings.war... |
from MaKaC.webinterface.rh import conferenceModif
from MaKaC.webinterface.rh import conferenceDisplay
def index( req, **params ):
return conferenceModif.RHConfModifParticipants( req ).process( params )
def obligatory ( req, **params ):
return conferenceModif.RHConfModifParticipantsObligatory( req ).process( ... |
from Analyser_Osmosis import Analyser_Osmosis
sql10 = """
SELECT
nodes.id,
ST_AsText(nodes.geom)
FROM
nodes
LEFT JOIN ways ON
nodes.id = ANY (ways.nodes) AND
ways.tags?'power' AND
ways.tags->'power' IN ('line', 'minor_line', 'cable')
WHERE
nodes.tags?'power' AND
nodes.ta... |
#!/usr/bin/env python
'''
Contains classes for common routines for loading all Coordinated Canyon
Experiment data
Mike McCann
MBARI 26 April 2016
'''
import os
import sys
import webob
# Insert Django App directory (parent of config) into python path
sys.path.insert(0, os.path.abspath(os.path.join(
... |
"""Adapted from a portion of the model published in:
Input-output behavior of ErbB signaling pathways as revealed by a mass action
model trained against dynamic data. William W Chen, Birgit Schoeberl, Paul J
Jasper, Mario Niepel, Ulrik B Nielsen, Douglas A Lauffenburger & Peter K
Sorger. Mol Syst Biol. 2009;5:239. Epu... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import base64
from mo_dots import Data, get_module
from mo_logs import Log
from mo_math.randoms import Random
from mo_math.vendor.aespython import key_expander, aes_cipher, cbc_mode
DEBUG = False
def enc... |
from avango.menu.widget import WidgetBase
import avango.menu.Preferences
import avango.osg
class PushButton(WidgetBase):
Title = avango.SFString()
IconFilenames = avango.MFString()
IconSize = avango.SFFloat()
IconPadding = avango.SFFloat()
IconColor = avango.osg.SFVec4()
IconDisabledColor = ava... |
from . import base
from .generic_poll_text import GenPollUrl
from xml.dom import minidom
from six.moves.urllib.parse import urlencode
QUERY_URL = 'http://query.yahooapis.com/v1/public/yql?'
WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
class YahooW... |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import matplotlib.pyplot as plt
try :
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except :
"Catch error"
cla... |
from . import base
from .decorators import *
import tuned.logs
from . import exceptions
from tuned.utils.commands import commands
import tuned.consts as consts
import os
import re
log = tuned.logs.get()
class SystemdPlugin(base.Plugin):
"""
Plugin for tuning systemd options.
These tunings are unloaded only on pr... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Job'
db.create_table(u'jobs_job', (
(u'id', s... |
#!/usr/bin/python
"""
https://pr4e.dr-chuck.com/tsugi/mod/python-data/index.php?PHPSESSID=e27f39c636650815479d9305323ee38e
Welcome Hitesh Agrawal from Using Python to Access Web Data
Scraping Numbers from HTML using BeautifulSoup In this assignment you will write a Python program similar to http://www.pythonlearn.com/... |
from copy import copy
from eve.utils import ParsedRequest
from eve.versioning import resolve_document_version
from apps.archive.common import get_expiry, item_operations, ITEM_OPERATION, update_version
from apps.archive.common import insert_into_versions, is_assigned_to_a_desk, convert_task_attributes_to_objectId
fr... |
from flask import Flask, render_template, request
#from skimage.io import imread, imsave
#from skimage.transform import resize
from scipy.misc import imsave, imread, imresize
import numpy as np
from keras.models import model_from_json
import tensorflow as tf
import re
import sys
import os
import base64
app = Flas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import requests
import sys
import tempfile
import zipfile
from . import Command
class Deploy(Command):
"""Deploy a module on an Odoo instance"""
def __init__(self):
super(Deploy, self).__init_... |
scalapack = True
extra_compile_args += [
'-O3'
]
libraries = [
'gfortran',
'lapack_bgp',
'scalapack',
'blacs',
'lapack_bgp',
'goto',
'xlf90_r',
'xlopt',
'xl',
'xlfmath',
'xlsmp'
... |
import io
import re
import logging
import collections
from flask import json, current_app as app, request
from simplejson.errors import JSONDecodeError
from eve.utils import config
from superdesk.errors import SuperdeskApiError
from superdesk.services import BaseService
from superdesk.notification import push_notific... |
import os
from setuptools import setup
from swprobe import __version__ as version
name = "swprobe"
setup(
name = name,
version = version,
author = "Jasper Capel, Spil Games",
author_email = "<EMAIL>",
description = ("Middleware for exporting swift metrics to statsd"),
license = "Apache Licens... |
# Modified version of the BlinkyTape Python example code from github.com/Blinkinlabs/BlinkyTape_Python
# Created by Matt Dyson (mattdyson.org)
# Version 1.0 (20/12/13)
import serial
class BlinkyTape(object):
def __init__(self, port, ledCount = 60):
self.port = port
self.ledCount = ledCount
# Initialise ... |
from shutil import which
from unittest import TestCase
import mock
from thumbor.config import Config
from thumbor.context import Context, RequestParameters
from thumbor.optimizers.gifv import Optimizer
from thumbor.utils import EXTENSION
class GifvOptimizerTest(TestCase):
def setUp(self):
self.os_path_e... |
from django.db import models, connection
def DateRangeQueryMaker(startDate, endDate):
if (startDate == None) & (endDate == None):
return ""
elif (startDate == None) & (endDate != None):
return """AND (img_search.Timing =< '{0}')""".format(str(endDate))
elif (startDate != None) & (endDate ==... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
%reset
%pylab
%pdb off
# Can do "%pylab" or "%pylab inline"
# Cheat sheet:
# np.array([v1, v2])
# np.array([rVec[0], iVec[0], cVec[0]]) # makes a 3x3 matrix
# np.linspace(v1, v2, numPoints)
# np.concatenate(( a1, a2 ))
# <headingcell level=3>
# Impo... |
from __future__ import print_function, unicode_literals
import json
from orlo.orm import Release, Package, Platform, db
from orlo.config import config
from test_route_base import OrloTest
__author__ = 'alforbes'
class TestImport(OrloTest):
"""
Base import test class
Common methods and tests that should ... |
# -*- coding: utf-8 -*-
from invoke import task, run
DEFAULT_NAME = 'certs/betfair'
DEFAULT_BITS = 2048
@task
def generate_key(name=DEFAULT_NAME, bits=DEFAULT_BITS):
key_file = '{0}.key'.format(name)
cmd = 'openssl genrsa -out {0} {1}'.format(key_file, bits)
run(cmd)
@task
def generate_cert(name=DEFA... |
"""
Script that sets up an environment used in order to perform full (or partial)
toolchain builds. Dockerfiles for images known to work with this script
can be found in the docker/ directory and the tags for the produced images
can be seen in the KNOWN_DOCKER_TAGS variable.
This script uses a combination of docker op... |
""" Module to read and add special blocktool comments in the public header """
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import warnings
from ..core import Constants
def strip_symbols(line):
"""
helper function to strip symbols
... |
import argparse
import sys
import os
import time
import signal
import pkg_resources
import errno
import itertools
from prelude import ClientEasy, checkVersion, IDMEFCriteria, IDMEFPath
from preludecorrelator import idmef, pluginmanager, context, log, config, require, error
if sys.version_info >= (3, 0):
import b... |
"""
Tests psconvert.
"""
import os
from pygmt import Figure
def test_psconvert():
"""
psconvert creates a figure in the current directory.
"""
fig = Figure()
fig.basemap(R="10/70/-3/8", J="X4i/3i", B="a")
prefix = "test_psconvert"
fig.psconvert(F=prefix, T="f", A=True)
fname = prefix ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.