content
stringlengths
4
20k
import random FILE = open('/usr/share/dict/british-english') NUM_RECORDS = 10000 POST_LENGTH = 250 TITLE_LENGTH = 15 words = FILE.readlines() count = len(words) - 1 sql_threads1 = "INSERT INTO askbot_thread " \ "(last_activity_at, title, approved, tagnames, favourite_count, language_code, added_at, last_activity_by_...
import datetime from merc import errors from merc import feature from merc import message class SvInfoFeature(feature.Feature): NAME = __name__ install = SvInfoFeature.install @SvInfoFeature.register_server_command class SvInfo(message.Command): NAME = "SVINFO" MIN_ARITY = 4 def __init__(self, ts_versio...
#!/usr/bin/env python # -*- encoding: utf-8 -*- from lxml import etree from pycaldav.lib.namespace import nsmap class BaseElement(object): children = None tag = None value = None attributes = None def __init__(self, name=None, value=None): self.children = [] self.attributes = {} ...
import pyamf from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext_lazy as _ from misc.views import pyamf_format from issue.models import Issue from square.models import Square,...
from __future__ import unicode_literals from docutils import nodes from docutils.parsers.rst import directives, Directive class Slideshare(Directive): """ Embed Slideshare slides in posts. Based on the YouTube directive by Brian Hsu and Vimeo directive vy Kura: https://gist.github.com/1422773 SLIDE...
""" Best score: 0.992 Best parameters set: clf__C: 7.0 clf__penalty: 'l2' vect__max_df: 0.5 vect__max_features: None vect__ngram_range: (1, 2) vect__norm: 'l2' vect__use_idf: True """ from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model.logistic import LogisticRegression from skl...
""" How to use PDF Reader - Add these lines to your py try: addon_pdf = xbmc.translatePath('special://home/addons/plugin.image.pdfreader/resources/lib') sys.path.append(addon_pdf) from pdf import pdf # For pdf pdf = pdf() # For pdf from pdf import cbx # For cbr and cbz cbx = cbx() # For cbr and cbz excep...
from pysollib.gamedb import registerGame, GameInfo, GI from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import CautiousDefaultHint from pysollib.util import KING from pysollib.stack import \ AC_RowStack, \ InitialDealTalonStack, \ OpenStack, \ SS_Fou...
import rdflib from pyontutils import combinators as cmb class AnnotationMixin: @property def __graph(self): if hasattr(self, 'out_graph'): return self.out_graph elif hasattr(self, 'graph'): return self.graph else: raise AttributeError('no graph or ou...
from oedes.optical.databases.refractiveindex import RefractiveIndexInfoMaterial, RefractiveIndexInfoMaterialWarning import os path = os.path.dirname(__file__) Glass = RefractiveIndexInfoMaterial( os.path.join( path, 'glass.yml'), ignore_warnings=True, name='glass') Al = RefractiveIndexInfoMater...
#!/usr/bin/env python """ ================= dMRI: Camino, DTI ================= Introduction ============ This script, camino_dti_tutorial.py, demonstrates the ability to perform basic diffusion analysis in a Nipype pipeline:: python dmri_camino_dti.py We perform this analysis using the FSL course data, which c...
r""" Logging objects (:mod: `qiita_db.logger`) ==================================== ..currentmodule:: qiita_db.logger This module provides objects for recording log information Classes ------- ..autosummary:: :toctree: generated/ LogEntry """ # -------------------------------------------------------------...
from boson.openstack.common import cfg from boson.openstack.common import jsonutils from boson.openstack.common import log as logging CONF = cfg.CONF def notify(_context, message): """Notifies the recipient of the desired event given the model. Log notifications using openstack's default logging system""" ...
""" Django settings for xops_m project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os #...
import time def paint_state_statehistory(row): if row["statehist_state"] == -1: return "state svcstate statep", "UNMON" is_host = row["service_description"] == "" state = row["statehist_state"] if is_host: if state in nagios_short_host_state_names: name = nagios_short_stat...
''' Python question by HackerRank Let's learn about list comprehensions! You are given three integers X, Y and Z representing the dimensions of a cuboid along with an integer N. You have to print a list of all possible coordinates given by on a 3D grid where the sum of i+j+k is not equal to N. Here, 0 <= i <= X; 0 <=...
import numpy as np from .shader_object import ShaderObject VARIABLE_TYPES = ('const', 'uniform', 'attribute', 'varying', 'inout') class Variable(ShaderObject): """ Representation of global shader variable Parameters ---------- name : str the name of the variable. This string can also contain...
from abc import ABCMeta, abstractmethod from collections.abc import Iterable from math import pi from numbers import Real import sys from xml.etree import ElementTree as ET import numpy as np import openmc.checkvalue as cv from openmc.stats.univariate import Univariate, Uniform class UnitSphere(metaclass=ABCMeta): ...
"""Tracker models.""" from django.contrib.auth.models import AbstractUser from django.db.models import (Count, DateField, DateTimeField, FloatField, ForeignKey, BooleanField, CharField, ManyToManyField, Model, ...
# encoding: utf-8 import types from functools import wraps from django.http import HttpResponse from django.conf import settings class on_view(object): def __init__(self, fn): self.wrapper = fn def decorate_fn(self, fn): return wraps(self.wrapper(fn)) def decorate_cls(self, cls):...
#!/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 decimal import Decimal from django.db import models from django.db.models import Sum from thing.models.itemgroup import ItemGroup from thing.models.marketgroup import MarketGroup class Item(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) item_group...
#coding: utf-8 from __future__ import unicode_literals import codecs from pymorphy.backends.base import DictDataSource from pymorphy.constants import PRODUCTIVE_CLASSES class MrdDataSource(DictDataSource): """ Источник данных для морфологического анализатора pymorphy, берущий информацию из оригинальных mr...
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils import shp2_geojson_obj from utils import create_shply_multigeom from utils import out_geoj in_shp_line = "../geodata/topo_line.shp" in_shp_overlap = "../geodata/topo_line_overlap.shp" shp1_data = shp2_geojson_obj(in_shp_line) shp2_data = shp2_geojson_obj(in_s...
from enable.component_editor import ComponentEditor from pyface.tasks.traits_dock_pane import TraitsDockPane from pyface.tasks.traits_task_pane import TraitsTaskPane from traits.api import Button, Bool, Int, Float from traitsui.api import View, Item, UItem, VGroup, HGroup, spring, \ Tabbed from pychron.core.ui.lcd...
import logging import os import re import shlex import subprocess as sp import sys import time import zipfile # Create zip archive and append files for retrieval def zip_files(files): fList = files compression = zipfile.ZIP_DEFLATED time_str = time.strftime("%Y%m%d-%H%M%S") zf_name = '/root/diagnostic...
#!/usr/bin/env python # -*- coding: utf-8 -*- # java2python.mod.basic -> functions to revise generated source strings. from itertools import count from logging import info, warn from os import path from re import sub as rxsub from java2python.lib import FS def shebangLine(module): """ yields the canonical pytho...
# -*- coding: utf-8 -*- """ Akvo RSR is covered by the GNU Affero General Public License. See more details in the license.txt file located at the root folder of the Akvo RSR module. For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. """ import json from akvo.rsr.models i...
# Interface MathDoku from fonctions import * from bruteforce import * from numpy import array donnees = {} taille=int(input('Taille de la grille ? ')) n = int(input('Nombre de blocs dans la grille \n')) grille=array([[0 for i in range(taille)] for j in range(taille)]) try: for i in range(1,n+1): print('Vo...
from jsonrpclib import Server """ Specify settings """ username = '' password = '' server = Server('https://' + username + ':' + password + '@www.factweb.nl/jsonrpc/call/jsonrpc') def product(): """ Get product data """ json_data = server.get('product', 31) print "Received JSON data from ser...
"""Generate template values for a callback interface. Extends IdlTypeBase with property |callback_cpp_type|. Design doc: http://www.chromium.org/developers/design-documents/idl-compiler """ from idl_types import IdlTypeBase from v8_globals import includes import v8_types import v8_utilities CALLBACK_INTERFACE_H_INC...
# -*- coding: utf-8 -*- """ Created on Sun May 09 22:23:22 2010 Author: josef-pktd Licese: BSD """ import numpy as np from numpy.testing import assert_almost_equal from scipy import stats from statsmodels.sandbox.distributions.extras import ( ExpTransf_gen, LogTransf_gen, squarenormalg, absnormalg, negsquareno...
import codecs import pkg_resources import cryptopals.challenge_1 as challenge_1 import cryptopals.challenge_2 as challenge_2 import cryptopals.challenge_3 as challenge_3 import cryptopals.challenge_4 as challenge_4 import cryptopals.challenge_5 as challenge_5 import cryptopals.challenge_7 as challenge_7 def test_ch...
import subprocess, os, shutil, tempfile, re from ipykernel.kernelbase import Kernel class SwiftKernel(Kernel): # Jupiter stuff implementation = 'Swift' implementation_version = '1.1.1' language = 'swift' language_version = '3.0.2' language_info = {'mimetype': 'text/plain', 'file_extension': 'sw...
import inspect, os, sys # Our local modules from trepan.processor.command.base_cmd import DebuggerCommand from trepan.processor import cmdproc as Mcmdproc class JumpCommand(DebuggerCommand): """**jump** *lineno* Set the next line that will be executed. The line must be within the stopped or bottom-most executio...
import numpy as np # ======================================================== def read_gmt_boundary(filename): ''' Read boundary data from text files that are extracted by GMT Input: filename is the filename for the boundary data file Output: lat_list is a list of latitudes ...
"""Support for Hydrawise sprinkler sensors.""" import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.hydrawise import ( DATA_HYDRAWISE, HydrawiseEntity, DEVICE_MAP, DEVICE_MAP_INDEX, SENSORS) from homeassistant.components.sensor import PLATFORM_...
import pygame import sys from pygame.locals import * import player import winsound pygame.init() pygame.mixer.init(frequency=22050, size=-16, channels=1, buffer=4096) WHITE = 255, 255, 255 WIDTH = 1920 HEIGHT = 1080 BLUE = 0, 188, 255 LBLUE = 0, 100, 200 BLACK = 0, 0, 0 GREY = 32, 78, 81 clock = pygam...
from __future__ import with_statement import os import re import urllib from django.conf import settings from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME from django.contrib.auth.forms import AuthenticationForm from django.contrib.sites.models import Site, RequestSite from django.contrib.auth.models im...
import wsme from wsme import types as wtypes from ironic.common import exception from ironic.common import utils from ironic.openstack.common import strutils class MacAddressType(wtypes.UserType): """A simple MAC address type.""" basetype = wtypes.text name = 'macaddress' @staticmethod def vali...
""" SampleCIView - simple OpenGL based CoreImage view """ from Cocoa import * from Quartz import * import CGL from OpenGL.GL import * # XXX: this may or may not be a bug in the OpenGL bindings from OpenGL.GL.APPLE.transform_hint import * import objc # The default pixel format _pf = None class SampleCIView (NSOpen...
"""Climate platform that offers a climate device for the TFIAC protocol.""" from concurrent import futures from datetime import timedelta import logging from pytfiac import Tfiac import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice from homeassistant.components.climate....
"""Tests for the smart protocol utility functions.""" from StringIO import StringIO from dulwich.errors import ( HangupException, ) from dulwich.protocol import ( PktLineParser, Protocol, ReceivableProtocol, extract_capabilities, extract_want_line_capabilities, ack_type, SINGLE_AC...
import pkg_resources import time class TrackResult: number = None filename = None pregap = 0 # in frames pre_emphasis = None peak = 0 quality = 0.0 testspeed = 0.0 copyspeed = 0.0 testduration = 0.0 copyduration = 0.0 # 4 byte CRCs for the test and copy reads testcrc =...
# -*- coding: utf-8 -*- __author__ = "Konstantin Klementiev" __date__ = "1 Nov 2019" import os, sys; sys.path.append(os.path.join('..', '..')) # analysis:ignore import numpy as np import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerBase import xrt.backends.raycing.sources as rs from xrt.bac...
from setuptools import setup, find_packages import os # The version of the wrapped library is the starting point for the # version number of the python package. # In bugfix releases of the python package, add a '-' suffix and an # incrementing integer. # For example, a packaging bugfix release version 1.4.4 of the # j...
# -*- coding: utf-8 -*- from __future__ import print_function, division import os import numpy as np import numpy.random as npr import spacy import util # Determinants with arbitrary probabilities DETERMINANTS = ['', 'A ', 'The '] P_DETERMINANTS = [0.4, 0.3, 0.3] class TitleGenerator(object): """Generates the ...
import argparse import cgi import json import logging import os import subprocess import sys import tempfile import time _SRC_DIR = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) sys.path.append(os.path.join(_SRC_DIR, 'third_party', 'catapult', 'devil')) from devil.android import devi...
import os from telemetry.page.actions.gesture_action import GestureAction from telemetry.page.actions import page_action class PinchAction(GestureAction): def __init__(self, selector=None, text=None, element_function=None, left_anchor_ratio=0.5, top_anchor_ratio=0.5, scale_factor=None,...
""" Utility functions for Flow compatibility with RLlib. This includes: environment generation, serialization, and visualization. """ import json from copy import deepcopy import os from flow.core.params import SumoLaneChangeParams, SumoCarFollowingParams, \ SumoParams, InitialConfig, EnvParams, NetParams, InFlow...
import re import sys from glob import glob from os import linesep from shutil import copy from os.path import exists, dirname, join as joinpath, basename import six __all__ = ['TextFile', 'TextFileError'] class TextFileError(Exception): pass class LineFilter: def __init__(self, id=None, startswith=None, conta...
"""Implements data model for the library. This module implements basic data model objects that are necessary for interacting with the Security Key as well as for implementing the higher level components of the U2F protocol. """ import base64 import json from pyu2f import errors class ClientData(object): """FIDO ...
import xml.etree.ElementTree as ET import xml.dom.minidom as pxml import os def convert(tree,fileName=None): """ Converts input files to be compatible with merge request #1533 The InterfacedPostProcessor has been removed, and the subType of given PostProcessor has been replaced with text from method node...
# this is a very raw and rough example of how to use the Plugin object in the SOAP API # to create / get / delete dashboards def plugin_zip(p): '''maps columns to values for each row in a plugins sql_response and returns a list of dicts''' return [ dict(zip(p.sql_response.columns, x)) for x in p.sql_re...
""" gevent compatibility for inotifyx General usage: >>> import os >>> import gevent_inotifyx as inotify >>> fd = inotify.init() >>> try: ... wd = inotify.add_watch(fd, '/path', inotify.IN_CREATE) ... events = inotify.get_events(fd) ... for event in events: ... print...
import os from twisted.protocols.basic import LineReceiver from twisted.internet import defer from twisted.internet.protocol import Factory from pllm import util from pllm.vision import process class VisionClientProtocol(LineReceiver): identmap = dict() def lineReceived(self, line): dec = util.decd...
import re from pyfaf.actions import Action from pyfaf.opsys import systems from pyfaf.queries import (get_sf_prefilter_btpath_by_pattern, get_sf_prefilter_pkgname_by_pattern, get_sf_prefilter_sol, get_opsys_by_name) from pyfaf.storage impo...
from setuptools import setup, find_packages long_description = (open('README.rst').read() + open('CHANGES.rst').read() + open('TODO.rst').read()) setup( name='django-model-utils', version='1.4.0.post1', description='Django model mixins and utilities', long_des...
from django.db import models class Credentials(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) description = models.CharField(max_length=200, blank=True, null=True) def __unicode__(self): return u'%s' % (self.username) cla...
import shade def main(): argument_spec = openstack_full_argument_spec( password=dict(required=True, type='str'), project=dict(required=True, type='str'), role=dict(required=True, type='str'), user=dict(required=True, type='str') ) module = AnsibleModule(argument_spec) ...
from checks.wmi_check import WinWMICheck from utils.containers import hash_mutable from utils.timeout import TimeoutException class WMICheck(WinWMICheck): """ WMI check. Windows only. """ def __init__(self, name, init_config, agentConfig, instances): WinWMICheck.__init__(self, name, init_...
#!usr/bin/env python #coding=utf-8 import wave import matplotlib.pyplot as plt import numpy as np import math import struct def read_wave_data(file_path): #读入wav文件 #open a wave file, and return a Wave_read object f = wave.open(file_path,"rb") #read the wave's format infomation,and return a tuple ...
from helpers import nullable_float, splitCode, transformFlag, nullable, \ nullable_int, agency_name_lookup, recovery_act, datestamp, \ first_char from federal_spending.usaspending.models import Contract FIELDS = [ ('unique_transaction_id', None), ('transaction_status', None), ('obligatedamount', nulla...
# -*- coding: utf8 -*- import os import pexpect from util import unaccent class CuentasUnix(object): def crear(self,u,clave=False): """ Crea usuario local de Unix """ if u.dependencia: outh = os.popen("/usr/sbin/useradd -m -s /bin/false -c \"%s %s, %s\" %s" % (unaccent(u.nombre), u...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model, Field from mezzanine.utils.importing import import_dotted_path # Backward compatibility with Django 1.5's "get_user_model". try: from django.contrib.auth import get_user_model except Impor...
import csv import random import math import operator def loadDataset(filename, split, trainingSet=[] , testSet=[]): with open(filename, 'rb') as csvfile: lines = csv.reader(csvfile) dataset = list(lines) for x in range(len(dataset)-1): for y in range(14): dataset[x][y] = float(dat...
''' Imports operators dynamically while keeping the package API clean, abstracting the underlying modules ''' from airflow.utils import import_module_attrs as _import_module_attrs # These need to be integrated first as other operators depend on them _import_module_attrs(globals(), { 'check_operator': [ 'Ch...
import re import unittest from netaddr import IPNetwork, IPAddress from tests.st.test_base import TestBase, HOST_IPV6 from tests.st.utils.docker_host import DockerHost """ Test the calicoctl container <CONTAINER> ip add/remove commands w/ auto-assign Tests the use of (libcalico) pycalico.ipam.IPAMClient.auto_assign...
from subprocess import call #interface to command LangevinNoisePositive import scipy.optimize as spo import scipy.io as sio import numpy as np import matplotlib.pyplot as plt plt.ion() #interactive plotting fig = plt.figure() ax1 = fig.add_subplot(131) ax1.set_title('010 loading') ax1.set_ylim([0,35]) ax2 = fig.add...
import os, jinja2 from flask import Flask from urllib import unquote from datetime import datetime #from flask.ext.login import LoginManager, current_user #login_manager = LoginManager() # obtain the base path of the application BASE_PATH = os.path.dirname( # service base directory os.path.dirname( ...
''' Created on Jun 13, 2013 @author: sergey ''' import logging from AnnoSyncEntity import AnnoSyncEntity from google.appengine.ext import db from datetime import datetime from model.Users import Users class FeedbackComment(AnnoSyncEntity): JSON_SCREENSHOT_KEY = "screenshot_key" JSON_COMMENT = "comment" ...
#!/usr/bin/env python from __future__ import print_function import argparse import lockfile import os import pkgutil import signal import sys import logbook from daemon.pidfile import TimeoutPIDLockFile from geventdaemon import GeventDaemonContext from logbook import NullHandler from logbook.more import ColorizedStd...
#!/usr/bin/env python from aircraft import Aircraft import util, time, math from math import degrees, radians from rotmat import Vector3, Matrix3 class Motor(object): def __init__(self, angle, clockwise, servo): self.angle = angle # angle in degrees from front self.clockwise = clockwise # clockwis...
""" MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_m...
from setuptools import setup, find_packages import DTL setup( name='DTL', version=DTL.__version__, author='Kyle Rockman', author_email='<EMAIL>', install_requires=open('requirements.txt').read().splitlines(), packages = find_packages(), package_data = { # If any subfolder contains th...
from rest_framework import generics from rest_framework import permissions as drf_permissions from modularodm import Q from framework.auth.oauth_scopes import CoreScopes from website.models import Institution, Node, User from api.base import permissions as base_permissions from api.base.filters import ODMFilterMixi...
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed i...
# -*- coding: utf-8 -*- import logging # We are patching queue_entry.mount_sample at the end of this file. import queue_entry import qutils from mxcube3 import app as mxcube from queue_entry import QueueSkippEntryException, CENTRING_METHOD def sc_contents_init(): mxcube.SC_CONTENTS = {"FROM_CODE": {}, "FROM_LOC...
"""Abstract classes.""" from __future__ import absolute_import, unicode_literals import abc from .five import with_metaclass, Callable __all__ = ['Thenable'] @with_metaclass(abc.ABCMeta) class Thenable(Callable): # pragma: no cover """Object that supports ``.then()``.""" __slots__ = () @abc.abstract...
import numpy as np import tensorflow as tf import time batch_size = 128 epochs = 100 learning_rate = 0.005 momentum = 0.9 time_step = 28 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape([x_train.shape[0], time_step, 784 // time_step]).astype('float32') ...
import random import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.orm import exc from neutron.common import constants as q_const from neutron.common import utils as n_utils from neutron.db import agents_db from neutron.db import l3_agentschedulers_db as l3agent_sch_db from neutron.db import model_base ...
"""Unit tests for FrameGatewayFactoryDefaultRequest.""" import unittest from pyvlx.api.frame_creation import frame_from_raw from pyvlx.api.frames import FrameGatewayFactoryDefaultRequest class TestFrameRebootRequest(unittest.TestCase): """Test class FrameGatewayFactoryDefaultRequest.""" # pylint: disable=to...
import csv from pattern.web import URL, DOM, plaintext, strip_between from pattern.web import NODE, TEXT, COMMENT, ELEMENT, DOCUMENT #For the 2013 datasheet, use this code: url = URL('http://www.satp.org/satporgtp/countries/pakistan/database/majorincidents.htm') dom = DOM(url.download(cached=True)) myarray = [] t...
filters = [('Beatiful', 'Beautiful'), ('Deehunter', 'Deerhunter'), ('Monae, Janelle', 'Janelle Monae')] # Filters to make calculations more accurate def filterAlbumString(title, filters=[]): ''' filterAlbumString: Filters the title of an album with standard filters so that common typos are corrected and they can...
import sys from random import randrange, sample if sys.version_info[0] >= 3 or sys.version_info[1] >= 7: from fractions import Fraction from randfloat import un_randfloat, bin_randfloat, tern_randfloat else: def un_randfloat(): return [0.0] def bin_randfloat(): return [(0.0, 0.0)] def tern_randfloat...
#!/usr/bin/python #code by IV LO w Czestochowie, Jan Konopka, Bartlomiej Meller, Milos Galas, Szymon Zycinski import socket import sys from datetime import datetime import MySQLdb import urllib import http.client # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the s...
import cv2 #@UnusedImport import cv2.cv as cv #@UnusedImport import numpy as np #@UnusedImport import sys import scipy.weave as weave class Exec: """Create and edit a filter on the fly for testing purposes""" def __init__(self): self.code = "" self.is_python = True self._ccode = N...
"""Test the client module components.""" from threading import Barrier from time import sleep from unittest import main import zmq from cylc.flow.cfgspec.glbl_cfg import glbl_cfg from cylc.flow.network.server import SuiteRuntimeServer, PB_METHOD_MAP from cylc.flow.network.client import SuiteRuntimeClient from cylc.f...
"""Unit tests for BigQuery sources and sinks.""" # pytype: skip-file from __future__ import absolute_import import base64 import datetime import logging import random import time import unittest from decimal import Decimal from functools import wraps from future.utils import iteritems from nose.plugins.attrib import...
from osv import osv, fields import time def _links_get(self, cr, uid, context=None): obj = self.pool.get('res.request.link') ids = obj.search(cr, uid, [], context=context) res = obj.read(cr, uid, ids, ['object', 'name'], context) return [(r['object'], r['name']) for r in res] class res_request(osv.osv...
import test_utils from nose.tools import ok_ from nose.plugins.skip import SkipTest class SecurityTests(test_utils.TestCase): """ These tests are based on the following risk considerations: https://wiki.mozilla.org/Webpagemakerapi#Risk_considerations """ def test_documents_require_doctype...
# -*- coding: utf-8 -*- import time from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.tools import float_is_zero from datetime import datetime from dateutil.relativedelta import relativedelta class ReportAgedPartnerBalance(models.AbstractModel): _name = 'report.account.repor...
import json from glob import glob import os import re import argparse import csv def get_arguments(): ''' argparse object initialization and reading input and output file paths. input files: input path to location where new comments json files are stored (-i) output file: the output csv file containing...
import types import fontTools.ttLib import opentype_feature_freezer def test_rename_ttf(shared_datadir): font = fontTools.ttLib.TTFont() font.importXML(shared_datadir / "Empty_TTF.ttx") remapper_options = types.SimpleNamespace( inpath="None", outpath=None, rename=True, u...
#!/usr/bin/env python # -*- coding: utf-8 -*- #----------------------- # Name: tmdb_request.py # Python Library # Purpose: Wrapped urllib2.Request class pre-configured for accessing the # TMDb v3 API #----------------------- from tmdb_exceptions import * from locales import get_locale from cache import Cache ...
# Part of Cosmos by OpenGenus Foundation class DoublyLinkedList: class Node: def __init__( self, data, prevNode, nextNode ): self.data = data self.prevNode = prevNode self.nextNode = nextNode def __init__( self, data=None ): self.first = None ...
import pints import pints.toy import unittest import numpy as np class TestMultimodalGaussianLogPDF(unittest.TestCase): """ Tests the multimodal log-pdf toy problems. """ def test_basic(self): """ Tests instantiations and calls in 2D and 3D across varying numbers of modes ...
#!/home/unnikrishnan/work/va/venv/bin/python3 # # The Python Imaging Library # $Id$ # from __future__ import print_function import sys if sys.version_info[0] > 2: import tkinter else: import Tkinter as tkinter from PIL import Image, ImageTk # # an image viewer class UI(tkinter.Label): def __init__(s...
#!/usr/bin/env python # Script for testing upload a file to Fedora to get an upload id for use as # a datastream location. # Example of using a callback method on the upload api call. # Requires progressbar import argparse import os from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor from progress...
from cwr.app import db STATUS_READY = 0 STATUS_WIP = 1 LOCALES = [ 'en-US', #'en-GB', #'ru-RU', 'fr-FR', #'fr-CA', 'de-DE', #'es-MX', 'es-ES', ] COUNTRIES = [ 'US' ] class Extension(db.Model): id = db.Column(db.String(40), primary_key=True) avg_rank = db.Column(db.Float(...