code
stringlengths
1
199k
"""Support for transport.opendata.ch.""" from __future__ import annotations from datetime import timedelta import logging from opendata_transport import OpendataTransport from opendata_transport.exceptions import OpendataTransportError import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA...
from __future__ import (unicode_literals, absolute_import, division, print_function) import logging import os import tempfile import requests from py3compat import text_type from django.template import loader, Context from rtfw import (Paragraph, Table, BorderPS, FramePS, Cell, ...
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("Integrations"), "icon": "icon-star", "items": [ { "type": "doctype", "name": "Bcommerce Setting", "description": _("Connect Bcommerce with ERPNext"), "hide_count": True } ] } ...
import sys from setuptools import setup, find_packages DESCRIPTION = "tornadis is an async minimal redis client for tornado " \ "ioloop designed for performances (use C hiredis parser)" try: with open('PIP.rst') as f: LONG_DESCRIPTION = f.read() except IOError: LONG_DESCRIPTION = DESCRIPTI...
import sqlite3 from scrapy import log class Sqlite3Pipeline(object): # Connect to DB and creates if necessary. def __init__(self): self.connection = sqlite3.connect('./data.db') self.cursor = self.connection.cursor() self.cursor.execute('CREATE TABLE IF NOT EXISTS scrapedata ' ...
"""data manager """ import csv import random def read_edges_from_txt(filepath, sep=" ", one_origin=False): edges = [] with open(filepath) as f: for line in f: n1, n2 = line.strip().split(sep) edges.append((int(n1), int(n2))) if one_origin: edges = [(i-1, j-1) for i, j...
import datetime import os from bs4 import BeautifulSoup from hashlib import md5 from download import download from pymongo import MongoClient from config import * headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"} class meizitu(down...
from .conditions import Any, All, GlobalRelativeValue, GlobalAbsoluteValue, LocalAbsoluteValue, \ LocalRelativeValue, GB, MB, KB, CustomCondition, Not from .default import install_force_gc_collect from .memthread import MemoryPressureManager from .dump_frames_on import dump_memory_on, install_dump_memory_on from .g...
import hashlib import unittest import tempfile from dataserv_client import encryptedio class TestConfig(unittest.TestCase): def test_roundtrip(self): input_path = "tests/fixtures.json" encrypted_path = tempfile.mktemp() output_path = tempfile.mktemp() print("encrypted_path", encrypte...
from sqlalchemy.engine.default import DefaultDialect from sqlalchemy import exc import os from . import json_dbapi class JsonDialect(DefaultDialect): def __init__(self, **kwargs): super(JsonDialect, self).__init__(**kwargs) @classmethod def dbapi(cls): return json_dbapi name = 'json' ...
import subprocess import shutil import os filedSite = input("Enter the file path (start from year): ") projectNumber = input("Enter the project number: ") newProject = input("Is this a new project? (Type Y for yes): ") finderWindow = input("Want to open a new Finder window? (Type y for yes): ") def linkedIt(filePath): ...
import unittest def fizzbuzz(a): if a % 15 == 0: return 'FizzBuzz' elif a % 3 == 0: return 'Fizz' elif a % 5 == 0: return 'Buzz' else: return a class FizzBuzzTest(unittest.TestCase): #テストプログラム def test_fizzbuzz(self): self.assertEqual('Fizz', fizzbuzz(3)) ...
"""Testing the Graph module.""" import pytest ADD_NODE_TABLE = [ [[1, 2, 3, 7], {1: [], 2: [], 3: [], 7: []}], [[1], {1: []}], [["test"], {"test": []}], [["test", "this", "works"], {"test": [], "this": [], "works": []}] ] EDGES_TABLE = [ [[[1, 2, 1]], [(1, (2, 1))]], [[[1, 2, 4], [3, 2, 1]], [(1...
"""Test file loaders."""
from ipykernel.kernelbase import Kernel from os import unlink, environ import base64 import imghdr import re import signal import urllib import sys import traceback from powershell_kernel import subprocess_repl, powershell_proxy from powershell_kernel.util import get_powershell __version__ = '0.1.4' version_pat = re.co...
'''DeviceName facade. Returns the following depending on the platform: * **Android**: Android Device name * **Linux**: Hostname of the machine * **OS X**: Hostname of the machine * **Windows**: Hostname of the machine Simple Example -------------- To get the unique ID:: >>> from plyer import devicename >>> devi...
from .system_info_inspection import RemoteHostSystemInfoGetter
from collections import namedtuple LinkedMetadata = namedtuple('LinkedMetadata', [ 'title', 'path', 'image_resource', 'description' ])
import sys from setuptools import setup if sys.version_info.major == 2: raise ValueError('This package does not support Python 2') elif sys.version_info.major == 3: if sys.version_info.minor < 5: raise ValueError('This package requires Python 3.5 or newer') else: raise ValueError('Python version not...
desc="""top N rows of query""" setup=""" """ cleanup=""" """ notes=""" This select the first N rows of a query. If you are looking for the SELECT...LIMIT clause this is it. <p> Note that ROWNUM starts at 1 and not 0. """ output=""" """ import sys import cx_Oracle def demo(conn,curs): # the first 5 rows of the subq...
import unittest import os from collections import defaultdict from mpinterfaces.utils import * from pymatgen import Structure from pymatgen.io.vasp.inputs import Kpoints from pymatgen.symmetry.bandstructure import HighSymmKpath __author__ = "Michael Ashton" __copyright__ = "Copyright 2017, Henniggroup" __maintainer__ =...
""" Created on Sat Jan 25 22:48:45 2014 @author: xm """ import unittest import monk.core.entity as entity class EntityTests(unittest.TestCase): pass if __name__ == '__main__': unittest.main()
from typing import Set, List, Dict, Union, Optional from hwt.doc_markers import internal from hwt.hdl.statements.assignmentContainer import HdlAssignmentContainer from hwt.hdl.statements.statement import HdlStatement from hwt.hdl.value import HValue from hwt.synthesizer.rtlLevel.mainBases import RtlSignalBase @internal...
""" """ import yaml import mailbox import logging from email.header import decode_header from ..utils.format import format_basic, format_text, format_address class EmailParser(): MAX_LENGTH = 10000 def __init__(self, email_file): self.email_file = email_file def get_payload_text(self, msg): ...
''' returns files in a directory Created on 29 May 2014 @author: chris ''' import os def open_file_list(file_dir): files_tmp = os.listdir(file_dir) files_tmp.sort() files_tmp = [ file_dir + i for i in files_tmp ] return files_tmp
from spindrift.sequence import sequence, Step def fn_a(callback, value): callback(0, value) def fn_b(callback, value, fn_a=None): if value == 'ohno': return callback(1, 'yikes') if value == 'boom': raise Exception('boom') callback(0, fn_a + value) def test_basic(): done = False d...
from django.conf.urls import url from .views import MemberFormView, MemberSearchView, MemberSignIn, Members, MemberViewSet apiRoutes = ( (r'members', MemberViewSet), ) urlpatterns = [ url(r'^new/$', MemberFormView.as_view(), name='member_new'), url(r'^search/(?P<query>[\w|\W]+)/$', MemberSearchView.as_view(...
import os, sys from jarray import array from java.awt.image import DataBuffer from javax.media.jai import RasterFactory from geoscript import core, util from geoscript.proj import Projection from geoscript.geom import Bounds, Point from geoscript.feature import Feature from geoscript.layer.band import Band from org.ope...
from argparse import ArgumentParser import time from zhelpers import zmq STATE_PRIMARY = 1 STATE_BACKUP = 2 STATE_ACTIVE = 3 STATE_PASSIVE = 4 PEER_PRIMARY = 1 PEER_BACKUP = 2 PEER_ACTIVE = 3 PEER_PASSIVE = 4 CLIENT_REQUEST = 5 HEARTBEAT = 1000 class BStarState(object): def __init__(self, state, event, peer_expiry)...
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('images', '0002_image_total_likes'), ] operations = [ migrations.RemoveField( model_name='image', name='total_likes', ), ]
""" Heagy et al., 2017 1D FDEM and TDEM inversions ============================================== Here, we perform a 1D inversion using both the frequency and time domain codes. The forward simulations are conducted on a cylindrically symmetric mesh. The source is a point magnetic dipole source. This example is used in...
class Solution(object): def combine(self, nums, k): """ :type n: int :type k: int :rtype: List[List[int]] """ from itertools import combinations return map(list, list(combinations(nums, k))) def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = set() for...
XXXXXXXXX XXXXX XXXX XXXXXXXXX XXX XXXXXXXXXX XXXXXXXX X XXXXXXXXX XXXXXXXX XXX XXXXXX XXXXXXXXX XXX XXXXXXXXXX XXX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXX XXX XXXXXXXXXXXXX XXXXXXX XXXXXXXX XXXXXXXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXX...
import numpy as np import ffthompy.projections as proj from ffthompy.materials import Material from ffthompy.postprocess import postprocess, add_macro2minimizer from ffthompy.general.solver import linear_solver from ffthompy.general.solver_pp import CallBack, CallBack_GA from ffthompy.general.base import Timer from fft...
from setuptools import setup, find_packages setup( name="QtCompat", version="0.1", packages=find_packages(), scripts=[], # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine install_requires=[], package_data={ }, # metadat...
import subprocess, os, re, sys import time script_name = 'kwgensow4git.py' git_history_from = '2005-01-01' def get_owners_from_git_history(repo_root, since): cmd = ('git', 'log', '--since=' + since, '--name-status', '--pretty=format:%h >>>%ae<<<') #print 'git log command is: ', cmd p = subprocess.Popen(cmd,...
from . import colors from . import stats
import _plotly_utils.basevalidators class UidValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="uid", parent_name="box", **kwargs): super(UidValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs...
import theano from theano import tensor import numpy from blocks.bricks import Tanh, Softmax, Linear, MLP, Identity, Rectifier from blocks.bricks.lookup import LookupTable from blocks.bricks.recurrent import LSTM from blocks.filter import VariableFilter from blocks.roles import WEIGHT from blocks.graph import Computati...
""" This is an Astropy affiliated package. """ from ._astropy_init import * if not _ASTROPY_SETUP_: from . ham import * from . spam import * from . import pyastro16
from flask import Flask, request, Response, render_template from configLoader import ConfigLoader from emailRequestHandler import EmailRequestHandler import os.path app = Flask(__name__) @app.route("/") def home(): response = Response("{\"message\": \"Please check API documentation\"}", status=400, mimetype='applicati...
import time import numpy as np from numpy.fft import fft, fftfreq from .core import check_for_primes, SuperFreqResult from ._naff import naff_frequency from .simpsgauss import simpson from .log import logger __all__ = ['SuperFreq', 'find_frequencies', 'find_integer_vectors', 'closest_resonance', '...
from template import Template from loader import Loader from context_manager import context_manager as cystache_context_manager
from day_03 import move, get_visits def test_move(): assert move(">", (0, 0)) == (1, 0) assert move("<", (0, 0)) == (-1, 0) assert move("^", (0, 0)) == (0, 1) assert move("v", (0, 0)) == (0, -1) step_1 = move("^", (0, 0)) step_2 = move(">", step_1) step_3 = move("v", step_2) step_4 = mov...
__all__ = ['authentication']
def fvoigt(damp,vv): """ Extract spectral data from the Kitt Peak FTS-Spectral-Atlas as provided by H. Neckel, Hamburg. INPUTS: DAMP: A scalar with the damping parameter VV: Wavelength axis usually in Doppler units. OUTPUTS: H: Voigt function F: Faraday-Voigt function NOTES: A rational approximatio...
import sys PY2 = int(sys.version[0]) == 2 if PY2: text_type = unicode # flake8: noqa binary_type = str string_types = (str, unicode) # flake8: noqa basestring = basestring # flake8: noqa else: text_type = str binary_type = bytes string_types = (str,) basestring = (str, bytes)
import numpy as np import matplotlib.pyplot as plt import matplotlib import figurefirst as fifi layout = fifi.FigureLayout('example_svgitem_layout.svg') layout.make_mplfigures() cdict1 = {'r1':0.3,'r2':0.1,'r3':0.9} cdict2 = {'path1':0.3,'path2':0.1,'path3':0.9} for key,patch in layout.svgitems['svggroup'].items(): ...
import epics import time import numpy as np pvname = 'DCLS:ARR:PROF19' mypv=epics.PV(pvname, auto_monitor = True) time.sleep(1) def onChanges(pvname = None, value = None, **kws): print "Intensity on %s is %.3f" % (pvname, np.sum(mypv.get())) mypv.add_callback(onChanges) while True: time.sleep(1)
from datetime import datetime import re from urllib.parse import quote as urlquote import attr THRESHOLD_RE = re.compile( r"^Threshold Crossed: " r"1 datapoint " r"\[(?P<actual_value>\d+)\.0 \((?P<date>\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})\)\] " r"was " r"(?P<operator>(?:greater|less) than(?: or equa...
from math import log import arrow import re from emoji import demojize from . import prs from . import comments from . import users from . import repos import settings def get_votes(api, urn, pr): """ return a mapping of username => -1 or 1 for the votes on the current state of a pr. we consider comments and r...
import os import subprocess from unittest import TestCase import requests class Test404Server(TestCase): PORT = 8000 def setUp(self): # Start the server, be sure to include the proper Python files on the # path. env = os.environ.copy() env["PYTHONPATH"] = os.getcwd() self...
import sys import os sys.path.insert(0, os.path.abspath('.')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', ] templates_path = ['docs/_templates'] source_suffix = '.rst' master_doc = 'index' project = u'cascadict' copyright = u'2015, Josef Nevrl...
from django.test import TestCase, client from django.core import mail from django.core.urlresolvers import reverse from django.utils.html import strip_tags from django.template.loader import render_to_string from django.contrib.auth.models import User, Group from django.contrib.gis.geos.geometry import GEOSGeometry fro...
"""Axis network device abstraction.""" import asyncio import async_timeout import axis from axis.configuration import Configuration from axis.errors import Unauthorized from axis.event_stream import OPERATION_INITIALIZED from axis.mqtt import mqtt_json_to_event from axis.streammanager import SIGNAL_PLAYING, STATE_STOPP...
import re, os from os import path from lxml import etree class PostalCodeValidator (object): """ Verifies that a given postal code is valid or invalid. """ def __init__(self, postal_data_path=None): """Initialize (and load) validator. If postal_data_path is supplied, PostalCodeValidat...
from django.conf import settings def from_settings_or_default(name, default): """Get attribute from settings by name or return default value""" return getattr(settings, name, default) DEFAULT_IMPORT = { 'django.db.models': [ 'Avg', 'Case', 'Count', 'F', 'Max', ...
import os import json from boto.s3.connection import S3Connection, Key PROJECT_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) print "PROJECT_PATH: " + str(PROJECT_PATH) SECRETS_PATH = os.path.join(PROJECT_PATH, "secret.json") LOCAL = os.environ.get("LOCAL") if LOCAL: SECRETS_DICT = json.loads(op...
import argparse from helpers.main_helper import setup_logging from helpers.python_ext import readfile from module_generation.verilog_to_aiger_via_yosys import verilog_to_aiger def main(): parser = argparse.ArgumentParser(description='Convert Verilog to AIGER', formatter_class=ar...
from __future__ import absolute_import import logging import random from flask import Flask from flask.ext.restful import Resource, Api class <%= className %>Flask(Flask): def __init__(self, *args, **kwargs): super(<%= className %>Flask, self).__init__(*args, **kwargs) def boot(self): return sel...
c = get_config() c.Exporter.preprocessors = ['km3pipe.style.LatexPreprocessor']
x = 4 print 1 != x < 9 print 1 != x > 9 print 4 != x < 9 print 4 == x > 9 print 4 == x < 9 print 4 == x < 9 < 14 print 4 == x < 9 < 14 > 10 print 4 == x < 9 < 14 < 10
import suspect import suspect.io.tarquin import pytest import unittest.mock import builtins from unittest.mock import patch import os import numpy def test_write_dpt(): data = suspect.MRSData(numpy.zeros(1), 1e-3, 123.456) mock = unittest.mock.mock_open() with patch.object(builtins, 'open', mock): s...
from nutils import mesh, function, solver, util, export, cli, testing import numpy, treelog def main(etype:str, btype:str, degree:int, nrefine:int): ''' Adaptively refined Laplace problem on an L-shaped domain. .. arguments:: etype [square] Type of elements (square/triangle/mixed). btype [h-std] ...
from math import log2 class Solution: def isPowerOfTwo(self, n: int) -> bool: if n <= 0: return False k = int(log2(n)) return n == 2 ** k
""" rackddnsm ~~~~~ Dynamic DNS metadata for Rackspace Cloud DNS, Manages TXT records containing metadata in the format of title,desc,data. :copyright: (c) 2015 by Alex Edwards. :license: MIT, see LICENSE for more details. """ import re from rackddnsm.configuration import Settings from rackddnsm...
""" spaceshooter.py Author: Avery Wallis Credit: Original Spacewar Code, Daniel, Payton, Ethan Assignment: Write and submit a program that implements the spacewar game: https://github.com/HHS-IntroProgramming/Spacewar """ from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame from ggame import LineStyle, ...
r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource i...
from .stylesheet import interpolate_stylesheet from .value import interpolate_value
import xlsxwriter class Saver: def __init__(self): pass def save(self, data, save_format = None, filename = None): self.save_format = save_format if save_format else "xlsx" self.filename = filename if filename else "result."+self.save_format if self.save_format == "xlsx": self.__save_xlsx(data) else: ...
from django.contrib import admin from .models import Jobs, Skills, Certificates, Projects class JobsManage(admin.ModelAdmin): list_display = ('name', 'first_day', 'last_day', 'place', 'description') admin.site.register(Jobs, JobsManage) class SkillsManage(admin.ModelAdmin): list_display = ('name', 'fa') admin.s...
""" Difficulty: Code: """ def strip_nonalphanum(word): output = '' for letter in word: if letter.isalphanum(): output += letter return output def word_count_engine(doc): word_count = {} for word in doc.split(): # strip (non)alphanum word = strip_nonalphanum(wo...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
class Solution: def findErrorNums(self, nums): """ :type nums: List[int] :rtype: List[int] """ record = [0] * (len(nums) + 1) for num in nums: record[num] += 1 dup, miss = 0, 0 for idx, val in enumerate(record): if val == 2: ...
import math def isPrime(n): if n==1: return False for i in range(2,int(math.sqrt(n))+1): if (n/float(i))%1 == 0: return False return True primes = [] i=1 while len(primes) < 10001: i+=1 if isPrime(i): primes.append(i) print primes[-1]
"""database definition for Post and Category model""" from django.contrib.auth.models import User from django.db import models from django.utils.text import slugify from taggit.managers import TaggableManager class Category(models.Model): """data definition for blog post's category""" name = models.CharField(ma...
import os DEFAULT_GDB_TIMEOUT_SEC = 1 DEFAULT_TIME_TO_CHECK_FOR_ADDITIONAL_OUTPUT_SEC = 0.2 USING_WINDOWS = os.name == "nt" class GdbTimeoutError(ValueError): """Raised when no response is recieved from gdb after the timeout has been triggered""" pass
a = "simple \\ string \ foo \' \" \a \b \c \f \n \r \t \v \5 \55 \555 \05 \005" a : source.python : source.python = : keyword.operator.assignment.python, source.python : source.python " : punctuation.definition.string.begin.python, source.python, string.qu...
"""Installer unit tests.""" import os import shutil import sys import tempfile import unittest from six import StringIO from six.moves import configparser try: from unittest.mock import patch except ImportError: from mock import patch import run class ConfigFileTestCase(unittest.TestCase): """Test configura...
try: import cPickle as pickle except: import pickle from django.db import models from edtf import parse_edtf, EDTFObject from edtf.natlang import text_to_edtf DATE_ATTRS = ( 'lower_strict', 'upper_strict', 'lower_fuzzy', 'upper_fuzzy', ) class EDTFField(models.CharField): def __init__( ...
"""Update encrypted deploy password in Travis config file """ from __future__ import print_function import base64 import json import os from getpass import getpass import yaml from cryptography.hazmat.primitives.serialization import load_pem_public_key from cryptography.hazmat.backends import default_backend from crypt...
""" Tube rack table. Created on Jan 9, 2015 """ from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import Table def create_table(metadata, rack_tbl): "Table factory." tbl = Table('tube_rack', metadata, Column('rack_id', Integer, ...
__VERSION__="ete2-2.2rev1056" import sys import os import time import cgi from hashlib import md5 import cPickle ALL = ["WebTreeApplication"] class WebTreeApplication(object): """ Provides a basic WSGI application object which can handle ETE tree visualization and interactions. Please, see the webp...
r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource i...
import json import os import platform import socket import ssl import subprocess import time from http.client import HTTPSConnection from json import JSONDecodeError from os import PathLike from typing import IO, Any, Callable, List, Optional, Tuple, Union from urllib.parse import urlunparse import structlog from mirak...
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.utils import ChromeType from selene import have, be, by from selene.support.shared import browser, config def setup_module(): browser.config.driver = w...
def baesoo(a): if a % 3 == 0: if a % 5 == 0: return '3과 5의 공배수입니다' return '3의 배수입니다' elif a % 5 == 0: return '5의 배수입니다' else: return a def dan(a): return "\t".join((str(a * x) for x in range(1, 10)))
from __future__ import print_function, unicode_literals from django.contrib.auth.backends import ModelBackend from .models import SQRLIdentity class SQRLModelBackend(ModelBackend): """ Custom SQRL Authentication backend which honors ``only_sqrl`` when enabled. SQRL, by its spec, allows users to send ``only_...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('shapes', '0004_auto_20150725_2215'), ] operations = [ migrations.AlterField( model_name='shapepoint', name='shape_pt_lat', ...
import numpy as np def unit_vector(vector): """ Returns the unit vector of the vector. """ return vector / np.linalg.norm(vector) def angle_between(v1, v2): v1_u = unit_vector(v1) v2_u = unit_vector(v2) angle = np.arccos(np.dot(v1_u, v2_u)) if np.isnan(angle): if (v1_u == v2_u).all(): ...
""" Created on 9 juil. 2015 @author: GRENON Loïc """ from PyQt4 import QtCore, QtGui COLOR_ROLE = QtCore.Qt.UserRole class LogReaderTableModel(QtGui.QStandardItemModel): def __init__(self, headerData, parent=None, *args): super(QtGui.QStandardItemModel, self).__init__(parent, *args) self.headerData ...
r""" Suite of tools for extracting time series observations from the US-IOOS opendap server: http://opendap.co-ops.nos.noaa.gov/dods/IOOS/ Created on Mon Jul 02 10:18:47 2012 @author: mrayson Example -------- >>> startt = "201001" >>> endt = "201201" >>> latlon = [-95.60,-93.7,28.8,30] >>> varlist = ['waterlevel', 'con...
"""Python geospatial and remote sensing toolkit""" __all__ = [ "ali", "basemaputils", "geomutils", "geotiff", "hdf5", "hyperion", "hyperionutils", "irutils", "landsat", "landsatutils", "mtlutils", "raster", "rasterhelpers", "usgsl1", "vector", ] alwaysUseG...
import configparser import flightdata import screenshot class Error(Exception): pass DRIVERS = { 'dump1090': dict( data=flightdata.Dump1090DataParser, map=screenshot.Dump1090Display), 'virtualradarserver': dict( data=flightdata.VRSDataParser, ...
import amsoil.core.pluginmanager as pm from amsoil.core import serviceinterface import amsoil.core.log rest_logger = amsoil.core.log.getLogger('rest') class FlaskREST: def __init__(self, flaskapp): self._flaskapp = flaskapp @ serviceinterface def registerREST(self, unique_service_name, handler, endp...
''' Created on Apr 26, 2015 @author: uri ''' from projenv import Environ, EnvVar import os.path if __name__ == '__main__': import unittest import pickle import logging pickle_modules = [pickle] try: import cPickle pickle_modules.append(cPickle) except: pass logger=log...
''' ''' import sys def main(): if len(sys.argv) < 2: sys.stderr.write("Missing args: %s\n" % ":".join(sys.argv)) sys.exit(1) # distribution vector v = {} # Read in the vector with open(sys.argv[1]) as f: for line in f: (key, value) = line.strip().split("\t") v[key] = float(value) # N...
from openerp import models,fields,api from openerp.tools.translate import _ class is_mold_project(models.Model): _name='is.mold.project' _order='name' #Ordre de tri par defaut des listes _sql_constraints = [('name_uniq','UNIQUE(name)', 'Ce projet existe déjà')] @api.model def _get_group_chef_de_p...
from invoke import Collection, task, run from okcupyd import tasks ns = Collection() ns.add_collection(tasks, name='okcupyd') @ns.add_task @task(default=True) def install(): run("python setup.py install") @ns.add_task @task def pypi(): """Upload to pypi""" run("python setup.py sdist upload -r pypi") @ns.add...
import tensorflow as tf import numpy as np import util class BeliefNet: def __init__(self, unit_size): self.unit_size = unit_size self.W = tf.Variable(util.random_uniform(unit_size, unit_size), dtype=tf.float32) s = np.zeros((1, unit_size), dtype=np.float32) s[0, 0] = 1 shift...