content
string
#!/usr/bin/env python3 ''' Write a function with the following header to format the integer with the specified width. defformat(number,width): The function returns a string for the number with prefix 0 s. The size of the string is the width. For example, format(34, 4) returns "0034" and format(34, 5) returns "00034" ....
from functools import partial from warnings import warn import numpy as np from ._utils import check_random_state def bio_f_score(y_true, y_pred): """F-score for BIO-tagging scheme, as used by CoNLL. This F-score variant is used for evaluating named-entity recognition and related problems, where the go...
from django.conf.urls.defaults import * from haystack.views import SearchView from haystack.forms import SearchForm as DefaultSearchForm from pages.models import Page, slugify class CreatePageSearchView(SearchView): def extra_context(self): context = super(CreatePageSearchView, self).extra_context() ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import struct import re from serial import Serial import time from PySide.QtCore import QObject, Signal from pprint import pprint import os class Setting (object): settings = None _types = { bool: lambda x: x.lower () in ('true', 'yes', '1')...
"""Spanner read-write transaction support.""" from google.protobuf.struct_pb2 import Struct from google.cloud._helpers import _pb_timestamp_to_datetime from google.cloud.spanner_v1._helpers import _make_value_pb from google.cloud.spanner_v1._helpers import _metadata_with_prefix from google.cloud.spanner_v1.proto.tran...
from abc import ABCMeta, abstractmethod import client as riq from requests import HTTPError import math class RIQChild(object) : __metaclass__ = ABCMeta _cache = [] _cache_index = 0 _page_index = 0 _page_length = 200 _fetch_options = {} _batch_size = 50 _parent = None _object_clas...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tests for the Pyzotero module This file is part of Pyzotero. The MIT License (MIT) Copyright (c) 2015 Stephan Hügel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to ...
""" AvcHashStats - File ``/sys/fs/selinux/avc/hash_stats`` ====================================================== This parser reads the content of ``/sys/fs/selinux/avc/hash_stats``. """ from .. import parser, CommandParser, LegacyItemAccess from ..parsers import get_active_lines from insights.specs import Specs @...
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Metadata for Earthquake Impact Function on Building. Contact : <EMAIL> .. note:: This program 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 Founda...
import os import ycm_core # These are the compilation flags that will be used in case there's no # compilation database set (by default, one is not set). # CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. flags = [ '-Wall', '-Wextra', '-Werror', '-Weffc++', '-Wno-long-long', '-Wno-variadic-...
import six from cupy import elementwise from cupy.math import ufunc add = ufunc.create_arithmetic( 'add', '+', '|', '''Adds two arrays elementwise. .. seealso:: :data:`numpy.add` ''') reciprocal = elementwise.create_ufunc( 'cupy_reciprocal', ('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', '...
import signal import socket import math import RPi.GPIO as GPIO from time import sleep # SIGINT Handler def shutdown(signal, frame): print '\n Stopping UDP...' sock.close() print ' Stopping PWM...' portsurge.stop() stbdsurge.stop() portheave.stop() #changed vert to portheave stbdheav...
from settings import RED, YELLOW, GREEN, WHITE from random import randint class Scheme(object): visual_generic = "{}|{}|{}\n{}|{}|{}\n{}|{}|{}" def __init__(self, scheme, mine_class): if not (0 < scheme < 512): raise ValueError("Scheme must be between 1 and 511") self.scheme = sch...
# -*- coding: utf8 -*- import re from urlparse import urljoin from functools import partial from scrapy.selector import HtmlXPathSelector from scrapy.http import Request from scrapy.spider import BaseSpider from mscrap.loaders import LegisladorItemLoader _RE_RESOURCE_ID = re.compile(r'http://webappl.hcdn.gov.ar/di...
# Задача 6, Вариант 12 # Создайте игру, в которой компьютер загадывает название одного из восьми соборов Московского кремля, а игрок должен его угадать. # Мамедов Р.А. # 30.03.2016 import random print("Отгадайте название одного из соборов Московского кремля") print("У вас три попытки") sobor = int(input("Введите чис...
import email import os from email.message import Message from email.mime.text import MIMEText from typing import Dict, Optional import ujson from django.conf import settings from django.core.management.base import CommandParser from zerver.lib.email_mirror import mirror_email_message from zerver.lib.email_mirror_help...
""" EasyBuild support for installing MATLAB, implemented as an easyblock @author: Stijn De Weirdt (Ghent University) @author: Dries Verdegem (Ghent University) @author: Kenneth Hoste (Ghent University) @author: Pieter De Baets (Ghent University) @author: Jens Timmerman (Ghent University) @author: Fotis Georgatos (Uni....
''' Language tests ============== ''' import unittest from weakref import proxy class BaseClass(object): uid = 0 # base class needed for builder def __init__(self, **kwargs): super(BaseClass, self).__init__() self.proxy_ref = proxy(self) self.children = [] self.parent = N...
from about_dialog import AboutDialog from application_window import ApplicationWindow from beep import beep from clipboard import clipboard, Clipboard from confirmation_dialog import confirm, ConfirmationDialog from constant import OK, CANCEL, YES, NO from dialog import Dialog from directory_dialog import DirectoryDial...
from codecs import open from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) # Get version info ABOUT = {} with open(path.join(HERE, "datadog_checks", "teamcity", "__about__.py")) as f: exec(f.read(), ABOUT) # Get the long description from the README file with open(path.j...
from __future__ import absolute_import import six from django.core.urlresolvers import reverse from sentry.models import OrganizationAccessRequest from sentry.testutils import APITestCase class UpdateOrganizationAccessRequestTest(APITestCase): def test_owner_can_list_access_requests(self): self.login_a...
# -*- coding: utf-8 -*- """ Created on Sun May 28 17:37:50 2017 @author: azkei """ # Creating a DataFrame and writing it to JSON # Generate DataFrame frame = pd.DataFrame(np.arange(16).reshape(4,4), index=['white','black','red','blue'], columns=['up','down','right','left']) # ...
"""Yaml specific loader for including other yaml files.""" # Copyright (c) 2018 Thomas Lehmann # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitat...
import os from markets.models import Market, Logo from geography.models import Country from products.models import Category from django.core.files.uploadedfile import SimpleUploadedFile CURRENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) def create_market(**variable_data): market_data = get_market_d...
import uasyncio as asyncio from utime import ticks_add, ticks_diff, ticks_ms from micropython import schedule from . import launch # Usage: # from primitives.delay_ms import Delay_ms class Delay_ms: verbose = False # verbose and can_alloc retained to avoid breaking code. def __init__(self, func=None, args=(),...
import configparser import os.path as path from collections import OrderedDict class Config: """ Description: reading configuration file and returning compiled information from said file. Methods: - _check_against_config : reads configuration file and performs various tests on file. - construct_ur...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ import os class WatchModel: """ """ def __init__(self, ename, etype, evalue): """ """ self.expression = ename self.type = etype self.value = evalue self.children = [] def __str__(self): """ ...
from uuid import uuid4 from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required from xmodule.modulestore import Location from xmodule.modulestore.django import modulestore from xmodule.modulestore.inheritance import own_metadata from util.json_request import expec...
import os.path import builtins import sys sys.path.append("remsci/") import unittest from unittest.mock import patch, Mock, MagicMock, mock_open from libpipe.cmds.base import BaseCmd from libpipe.pipes.base import BasePipe import logging from remsci.lib.utility import customLogging customLogging.config() log = loggi...
# -*- coding: utf-8 -*- # This file should be kept compatible with both Python 2.6 and Python >= 3.0. import itertools import os import platform import re import sys import time from optparse import OptionParser out = sys.stdout TEXT_ENCODING = 'utf8' NEWLINES = 'lf' # Compatibility try: xrang...
config.declare_permission_section('nagvis', _('NagVis')) config.declare_permission( 'nagvis.*_*_*', _('Full access'), _('This permission grants full access to NagVis.'), [ 'admin' ] ) config.declare_permission( 'nagvis.Map_view_*', _('View all maps'), _('Grants read access to all maps.'), ...
#!/usr/bin/env python class MyFasterGraph: def __init__(self, graph = None): self.edges = {} self.nodes = {} if graph is not None: for node in graph.nodes(): node = str(node) self.add_node(int(node)) for edge in graph.edges(): edge = map(int, edge) self.add_edge(edge[0],edge[1]) de...
# Module: Operations.Subset.Subsetter # # The purpose of this module remove molecules from (or keep them in) # an input .bnx file based on their attributes from Operations.BioNano.files import BnxFile class Subsetter(object): def __init__(self, input_file, output_file): self.input_file=input_file self.output_fil...
import logging import tkp.db import tkp.db.quality as dbquality from tkp.quality.restoringbeam import beam_invalid from tkp.quality.rms import rms_invalid, rms_with_clipped_subregion from tkp.telescope.lofar.noise import noise_level from tkp.utility import nice_format logger = logging.getLogger(__name__) def reject_...
import os import re import time import json from flask import request, jsonify, url_for from binascii import b2a_hex, a2b_hex from hashlib import sha512 from bson.objectid import ObjectId from pymongo.errors import DuplicateKeyError from . import app, config from cms.api import ( util, make_error_response, ...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django import forms import selectable.forms as selectable from example.core.models import Fruit, Farm from example.core.lookups import FruitLookup, OwnerLookup class FarmAdminForm(forms....
# -*- 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 field 'Plan.engine_equivalent_plan' db.add_column(u'physical_pla...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import date from ac_tagging.widgets import TagAutocompleteTagIt from alibrary import settings as alibrary_settings from alibrary.models import Playlist from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper...
"""Support for aliases(5) configuration files API Stability: Unstable @author: U{Jp Calderone<mailto:<EMAIL>>} TODO:: Monitor files for reparsing Handle non-local alias targets Handle maildir alias targets """ import os import tempfile from twisted.mail import smtp from twisted.internet import protocol...
from django import forms as django_forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from horizon import forms, messages from django.utils.encoding import smart_text try: from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Layout, HTML ...
# encoding: utf-8 # pylint: disable=too-few-public-methods """ User schemas ------------ """ from flask_marshmallow import base_fields from flask_restplus_patched import Schema, ModelSchema from .models import User class BaseUserSchema(ModelSchema): """ Base user schema exposes only the most general fields....
"""Test for the custom coders example.""" # pytype: skip-file from __future__ import absolute_import import logging import tempfile import unittest from apache_beam.examples.cookbook import group_with_coder from apache_beam.testing.util import open_shards # Patch group_with_coder.PlayerCoder.decode(). To test that...
import datetime from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse fro...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Major.code' db.add_column('classes_major', 'code', self.gf('django.db.models.fi...
""" Extra HTML Widget classes """ import datetime import re from django.forms.widgets import Widget, Select from django.utils import datetime_safe from django.utils.dates import MONTHS from django.utils.safestring import mark_safe from django.utils.formats import get_format from django.conf import settings __all__ =...
#!/usr/bin/python """ (C) Copyright 2020-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ import time from ior_test_base import IorTestBase class DaosAggregationBasic(IorTestBase): # pylint: disable=too-many-ancestors """Test class Description: Run IOR with same file opti...
import logging try: from colorlog import ColoredFormatter except: pass import os def getLogger(name): return logging.getLogger(__name__) def set_format(frmt, frmt_col=None, datefmt=None): if frmt_col: try: formatter = ColoredFormatter(frmt_col, datefmt=datefmt) return...
""" Linear operations. """ import torch import torch.nn as nn import torch.nn.functional as F from darts.api import Model OPS = { 'none' : lambda c, stride, affice: Zero(), 'skip_connect' : lambda c, stride, affine: Identity(), 'linear_block' : lambda c, stride, affine: LinearBlock(c, c, affine=...
from setuptools import setup, find_packages with open('README.rst') as file: long_description = file.read() with open('requirements.txt') as file: requirements = file.read() requirements = requirements.split('\n') setup( name='sdcurses', version='0.0.1', description="A curses interface for the Sm...
import unittest import chunks.base_chunk import chunks.ufd_chunk import chunks.cfd_chunk import chunks.cbd_chunk class TestChunkTyping(unittest.TestCase): def test_UFD_chunking(self): """ Generate the UFD chunk type and ensure that it behaves properly :return: """ chunks.uf...
class GnrCustomWebPage(object): def main(self, root, **kwargs): root.data('labelDelBottone', 'pippo') root.data('disab', False) root.textbox(value='^valoredamettere') root.textbox(value='^labelDelBottone') root.checkbox(value='^disab') root.button('^labelDelBottone', ...
"""Plumbing functions powering our validation facilities.""" from copy import deepcopy from typing import Any, List, Optional, Tuple from .exceptions import Error from .types import type_fixers, type_matches from .utils import JSONDict, location_in_dict, nested_set def _rec_merge_ours( *, theirs: JSONDict, ours...
from typing import Any, Dict, Set from snapcraft import project from snapcraft.internal.project_loader import grammar from snapcraft.internal import pluginhandler, repo from ._package_transformer import package_transformer class PartGrammarProcessor: """Process part properties that support grammar. Stage p...
#!/usr/bin/env python # -*- coding: utf-8 -*- #...the usual suspects. import os, inspect #...for the unit testing. import unittest #...for the logging. import logging as lg # The wrapper classes to test. from nod import NOD from odd import ODD class TestNODvsODD(unittest.TestCase): def setUp(self): pa...
from Nametag import * import NametagGlobals from NametagConstants import * from pandac.PandaModules import * import math class Nametag3d(Nametag): WANT_DYNAMIC_SCALING = True SCALING_FACTOR = 0.055 SCALING_MINDIST = 1 SCALING_MAXDIST = 50 BILLBOARD_OFFSET = 3.0 SHOULD_BILLBOARD = True IS_...
import requests, os from django.template.loader import get_template from django.template import Context from django.conf import settings class Mailer(object): def __init__(self, subject=None, message=None, fr=None, recipients=[]): self.html = get_template("htmlmail.djhtml") self.txt = get_template...
import time import threading import os from DataAcqThread import DataAcqThread import zmq from DonkiOrchestraLib import CommunicationClass import traceback import socket import multiprocessing from InfoServer import infoServerThread from DataServer import DataServer THREAD_DELAY_SEC = 1 DEBUG = False class directo...
# /usr/bin/env python2 # coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from qpth.qp import QPFunction torch.set_default_tensor_type('torch.DoubleTensor') class LSTMModel(nn.Module): ''' nn.LSTM Parameters: ...
import os from setuptools import setup import sys base_path = '%s/opt/newrelic-plugin-agent' % os.getenv('VIRTUAL_ENV', '') data_files = dict() data_files[base_path] = ['LICENSE', 'README.rst', 'etc/init.d/newrelic-plugin-agent.deb', 'etc/init....
"""Tests for builtin_functions module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import six from tensorflow.contrib.autograph.converters import builtin_functions from tensorflow.contrib.autograph.converters import converter_test_base f...
#!/usr/bin/env python # # 3 - Left Motor Servo # 4 - Right Motor Servo # 5 - Pan Servo # 14 (A0) - Analog Sensor # 15 (A1) - Left Whisker # 16 (A1) - Right Whisker SIMULATE = 1 SENSOR_PIN = 14 L_BUMP = 15 R_BUMP = 16 SENSOR_THRESH = 400 DELAY_VAL = 700 # Delay for turning if SIMULATE: import...
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, no...
# coding: utf-8 """ Management command to user map on CartoDB """ import json import time import urllib from django.core.management.base import BaseCommand from django.db.models import Sum from settings.models import SettingProperties from settings import constants from urllib.parse import urlencode, quote_plus fro...
import fauxfactory from utils.wait import wait_for from jdbc_driver_methods import DB2_105_JDBC, MSSQL_2014_JDBC, MYSQL_57_JDBC from jdbc_driver_methods import POSTGRESPLUS_94_JDBC, POSTGRESQL_94_JDBC from jdbc_driver_methods import SYBASE_157_JDBC, ORACLE_12C_JDBC, MARIADB10_JDBC from cfme.middleware.datasource import...
from zeit.cms.content.interfaces import WRITEABLE_ALWAYS import mock import zeit.cms.content.interfaces import zeit.cms.testing import zeit.connector.interfaces import zope.component class TestRemoveOnCheckin(zeit.cms.testing.ZeitCmsTestCase): def test_objects_without_properties_should_not_fail(self): im...
from JumpScale import j class system_errorconditionhandler(j.tools.code.classGetBase()): """ errorcondition handling """ def __init__(self): self._te = {} self.actorname = "errorconditionhandler" self.appname = "system" def describeCategory(self, category, language, de...
#!/usr/bin/env python import roslib roslib.load_manifest('learning_tf') import rospy import math import tf import geometry_msgs.msg import turtlesim.srv if __name__ == '__main__': rospy.init_node('turtle_tf_listener') leader_frame = rospy.get_param('~leader_frame') listener = tf.TransformListener() ros...
import flask from flask import jsonify from flask import Response, request import random import time import copy import types import uuid from functools import wraps from passlib.hash import sha256_crypt from hashids import Hashids hashids = Hashids(min_length=11) ################## # Decorators COMMAND_KEYWORD = '...
""" """ from __future__ import absolute_import from ...properties import Bool, Int, String, Enum, Instance, List from ...enums import ButtonType from ..widget import Widget class AbstractGroup(Widget): """ Abstract base class for all kinds of groups. ``AbstractGroup`` is not generally useful to instantiate o...
#!/usr/bin/env python from __future__ import unicode_literals import ast import re from setuptools import setup, find_packages _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('modelimport/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8'))...
from django.db import models from django.contrib.auth.models import User import datetime from django.core.urlresolvers import reverse class Field(models.Model): label = models.CharField(max_length=200, blank=True) FIELD_TYPES = ( ('T', 'Text'), ('I', 'Image'), ('A', 'Audio'), ('...
# coding: utf-8 from setuptools import setup, find_packages try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: from distutils.command.build_py import build_py import os with open('README.rst') as file: long_description = file.read() MAJOR = 1 MINOR = 13 MICRO = 0 ...
"""Document path related helpers.""" import os from os import path from typing import TYPE_CHECKING from fava.helpers import FavaAPIException if TYPE_CHECKING: from fava.core import FavaLedger def is_document_or_import_file(filename: str, ledger: "FavaLedger") -> bool: """Check whether the filename is a doc...
import argparse, pyfiglet, sys class git(object): @staticmethod def parse_args(cmdname): parser = argparse.ArgumentParser(description="Have you been told to 'get %s'? Now you can!" % cmdname) parser.add_argument("name", metavar="NAME", type=str, nargs="?", default=None, ...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals from ksztalty import Ksztalty, Ksztalt from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QCheckBox, QButtonGroup, QVBoxLayout from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QSlider, QLCDNumber, QSplitter from P...
from django.test import TestCase, override_settings @override_settings(ROOT_URLCONF='tests_app.tests.functional.examples.etags.remove_etag_gzip_postfix.urls') class RemoveEtagGzipPostfixTest(TestCase): @override_settings(MIDDLEWARE_CLASSES=( 'django.middleware.gzip.GZipMiddleware', 'django.middle...
""" Module responsible for generating mutations on a given tree sequence. """ from __future__ import division from __future__ import print_function import json import sys import tskit import _msprime import msprime.simulations as simulations # Alphabets for mutations. BINARY = 0 NUCLEOTIDES = 1 class InfiniteSite...
from tempest.api.compute import base from tempest.common.utils import data_utils from tempest import exceptions from tempest import test class KeyPairsNegativeTestJSON(base.BaseV2ComputeTest): _interface = 'json' @classmethod def setUpClass(cls): super(KeyPairsNegativeTestJSON, cls).setUpClass() ...
import sys import connectionfactory """Simulator starter. Usage ./start_simulator <command> <id> command :== <start|restart|stop> type :== <TCP|UDP|Serial> id :== <0|1> Initializes and starts the a simulator. Writes all logging data to /tmp/type_simulator_<id>.log """ if __name__ == "__main_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ] operations = [ ...
from __future__ import print_function, division import os import sys from unittest import TestCase import warnings import numpy as np from numpy.testing import assert_allclose, assert_equal, assert_raises from numpy.testing.decorators import skipif import pandas as pd try: import matplotlib.pyplot as plt mis...
#!/usr/bin/env python3 """Classes and functions for testing the behavior of DTMs.""" import types from unittest.mock import patch import nose.tools as nose import automata.base.exceptions as exceptions import automata.tm.exceptions as tm_exceptions import tests.test_tm as test_tm from automata.tm.dtm import DTM cl...
#!/usr/bin/env python """ Program to produce graphs from the output of the as_toroidal program """ import matplotlib.pyplot as plt from pylab import * import sys import os import math from scipy import special from matplotlib.colors import LinearSegmentedColormap #Use a monospace font to avoid change in the size of pl...
import os, time from . import file_writer, renderer from ... colors import COLORS from .. import exception, log DEFAULT_RENDER = { 'color': COLORS.Black, 'pixel_width': 12, 'pixel_height': None, 'ellipse': True, 'vertical': False, 'frame': 2, 'padding': 2, } class MovieWriter: """Writ...
""" Search and get metadata for articles in Pubmed. """ from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import xml.etree.ElementTree as ET import requests import logging # Python 3 try: from functools import lru_cache # Python 2 except ImportError: from f...
"""Integration tests for Recommendations AI transforms.""" from __future__ import absolute_import import random import unittest from nose.plugins.attrib import attr import apache_beam as beam from apache_beam.testing.test_pipeline import TestPipeline from apache_beam.testing.util import assert_that from apache_beam...
import unittest import os from streamlink import Streamlink, NoPluginError from streamlink.plugin.plugin import HIGH_PRIORITY, LOW_PRIORITY from streamlink.plugins import Plugin from streamlink.session import print_small_exception from streamlink.stream import AkamaiHDStream, HLSStream, HTTPStream, RTMPStream from tes...
import os import gtk import sys from emmalib import dialogs class SaveResultCsv(gtk.ToolButton): def __init__(self, query, emma): """ @param query: QueryTab @param emma: Emma """ self.emma = emma self.query = query super(SaveResultCsv, self).__init__() ...
from django.db import models from django.conf import settings from datetime import date # Create your models here. class CreditCard(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) default = models.BooleanField(default=True) first_name = models.CharField("Payer f...
"""Convert Mozilla .lang files to Gettext PO localization files. """ from translate.storage import mozilla_lang as lang, po class lang2po: def __init__(self, duplicatestyle="msgctxt"): self.duplicatestyle = duplicatestyle def convertstore(self, thelangfile): """converts a file to .po format...
#!/usr/bin/python3 import json from hashlib import pbkdf2_hmac import binascii PathToNormalConfigFile = "/etc/virtberry/config.json" PathToUsersConfigFile = "/etc/virtberry/users.json" class User: def __init__(self, userid): self.username = userid self.password = get_user_attributes(self.username,...
from threading import Timer from enum import Enum import i2cMock from utils import * def from_int16(tab): return struct.unpack('h', ensure_string(tab[0:2]))[0] def from_uint16(tab): return struct.unpack('H', ensure_string(tab[0:2]))[0] def from_int32(tab): return struct.unpack('i', ensure_string(tab...
import getopt import hashlib import sys import os.path try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) ...
import cProfile import pstats import multiprocessing as mp from os import path, remove from shutil import rmtree from sys import exit from time import time, sleep import argparse import plyvel import ujson as json from imposm.parser import OSMParser from shapely.geometry import Polygon import shapely.speedups from set...
import abc import functools import re from StringIO import StringIO from IPython.core.splitinput import LineInfo from IPython.utils import tokenize2 from IPython.utils.openpy import cookie_comment_re from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError #-----------------------------------------...
''' Grid Layout =========== .. only:: html .. image:: images/gridlayout.gif :align: right .. only:: latex .. image:: images/gridlayout.png :align: right .. versionadded:: 1.0.4 The :class:`GridLayout` arranges children in a matrix. It takes the available space and divides it into columns a...
from __future__ import absolute_import, unicode_literals import os import unittest import gobject gobject.threads_init() from mopidy import exceptions from mopidy.audio import scan from mopidy.internal import path as path_lib from tests import path_to_data_dir class ScannerTest(unittest.TestCase): def setUp(...
from dustcurve import pixclass from dustcurve import globalvars import numpy as np import multiprocessing import ctypes import sys import mmap from multiprocessing.sharedctypes import Array nslices=6 def fetch_args(fnames, dname): """ returns: ldata= the likelihood arguments for running emcee's PTSampler ("lo...
import example_pb2 import Arcus import time socket = Arcus.Socket() socket.registerMessageType(2, example_pb2.ObjectList) socket.registerMessageType(5, example_pb2.ProgressUpdate) socket.registerMessageType(6, example_pb2.SlicedObjectList) def onStateChanged(newState): print('State Changed:', newState) def onE...
import os, sys if __name__ == "__main__": # The first parameters to the script represents the name of the simulator, then we have the list of tests if not os.path.exists(sys.argv[1]): print 'Error: Simulator executable file ' + sys.argv[1] + ' does not exist.' failedBenchs = {} for test in sys....