code
stringlengths
1
199k
import json pvs = open('/Users/NealSu/GoogleDisk/MyWorkInHaozu/Data/pvuv','r').readlines() import re pv_counts = {} out_rate = {} in_rate = {} rate_counts = {} regex = ['\?.*','\d', '.*?//', '\.haozu.com/\w{2}', '\.haozu.com'] for line in pvs: date,uid,category,subcategory,url = line[:-1].split('\t') if 'sem' n...
import math def part1(): f = open("input-1a.txt") lines = f.readlines() freq = 0 for l in lines: i = int(l) freq += math.floor(i / 3) - 2 print(freq) def part2(): f = open("input-1a.txt") lines = f.readlines() total = 0 for l in lines: test = 0 i =...
from PyQt4 import QtGui class PripDatasetItem(QtGui.QListWidgetItem): def __init__(self, key, name): QtGui.QListWidgetItem.__init__(self, None) self._key = key self._name = name self.setText(name)
import requests import json """ Activpik API Client (c) Kalyzée """ class Oauth2ClientCredentialsAuth(requests.auth.AuthBase): """Basic Oauth2 Client for Activpik API Goal : Retrieve acces_token with given client_id and client_secret """ def __init__(self, access_token_url, client_id, client_sec...
import CTK import validations from Rule import RulePlugin from util import * from copy import copy URL_APPLY = '/plugin/exists/apply' NOTE_EXISTS = N_("Comma separated list of files. Rule applies if one exists.") NOTE_IOCACHE = N_("Uses cache during file detection. Disable if directory contents change frequent...
import os import re import sys import urllib from JsUnpacker import JsUnpackerV2 from default import activado, mensagemprogresso, abrir_url_cookie, TVCoresURL, abrir_url_tommy, mensagemok, \ RTPURL, ResharetvURL, debug from downloader import downloader from requests import abrir_url, abrir_url_cookie, abrir_url_tom...
import autofig from nose.tools import assert_raises def test_unit_inconsistencies(): autofig.reset() autofig.plot(x=[1,2,3], y=[1,2,3], c=[1,2,3], cunit='solRad') autofig.plot(x=[1,2,3], y=[1,2,3], c=[1,2,3], cunit='m') assert(len(autofig.gcf().axes[0].cs)==1) autofig.reset() autofig.plot(x=[1,2...
__all__ = ('ui', 'config', 'globals', 'utils', 'dbus_manager', 'main', 'defaults', 'gdm', 'jsonrequester')
"""We have an upload server, maybe we should be able to download too? Uploaded files can be exported, to one export file per project/contractor/measurement type combination. These files can be generated at the press of a button, and downloaded afterwards. Most measurement types will all use the same exporter, one that ...
""" EVE Swagger Interface An OpenAPI for EVE Online OpenAPI spec version: 0.4.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class GetKillmailsKillmailIdKillmailHashItem(object): """ NOTE: This class is auto g...
""" Access Point ============ Access point base class. """ import abc import datetime import decimal import uuid from ..item import Item, ItemWrapper, ItemStub from ..request import And, Condition DEFAULT_PARAMETER = object() class NotOneMatchingItem(Exception): """Not one object has been returned.""" value = _...
import time import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) gains = (2/3, 1, 2, 4, 8, 16) print('|{:6.2f}x {:6.2f}x'.format(gains[0], gains[0]), end='') for gain in ...
from openstack.compute.v2 import _proxy from openstack.compute.v2 import availability_zone as az from openstack.compute.v2 import extension from openstack.compute.v2 import flavor from openstack.compute.v2 import hypervisor from openstack.compute.v2 import image from openstack.compute.v2 import keypair from openstack.c...
"""Occurrence data parser """ import csv import json import os import sys from LmBackend.common.lmobj import LMError, LMObject from LmCommon.common.lmconstants import ( LMFormat, OFTInteger, OFTReal, OFTString, ENCODING) from LmCommon.common.log import TestLogger try: from LmServer.common.localconstants import ...
from functools import reduce COMMON_WORDS_MAP = { 'A': 'a', 'Dei': 'dei', 'Del': 'del', 'Di': 'di', 'Ed': 'ed', 'E': 'e', 'F.Lli': 'F.lli', 'In': 'in', 'Responsabilita\'': 'Responsabilità', 'Sas': 'S.A.S.', 'Sigla': 'sigla', 'Snc': 'S.N.C.', 'Societa\'': 'Società', 'S.P.A.': 'S.p.A.', 'Spa...
from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range pickle_file = '../notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels']...
import os import pickle import hashlib import functools import shutil import settings import kernel.utils as utils CCH_DIR = settings.CCH_BASE_DIR CCH_MAX_SIZE = settings.CCH_MAX_SIZE * 1024 * 1024 # Given in Mo… HASH_TYPE = settings.CCH_HASH_TYPE HASH_READ_CHUNK = 65536 class DiskCache(object): """ An helper ...
import json from django.test import TestCase, Client class MapNotesTest(TestCase): fixtures = ['mapnotes_data.json'] def test_get_notes_map(self): c = Client() response = c.get("/annotations/1?bbox=-180.0,-90.0,180.0,90.0") note_json = json.loads(response.content) self.assertEqua...
""" This module contains unittests for :mod:`~bet.sampling.basicSampling:` """ import unittest import os import bet import numpy.testing as nptest import numpy as np import scipy.io as sio import bet.sampling.LpGeneralizedSamples as lp def test_Lp_generalized_normal(): """ Tests :meth:`bet.Lp_generalized_sample...
""" Rotated pyramids on top of substrate """ import bornagain as ba from bornagain import deg, nm def get_sample(): """ Returns a sample with rotated pyramids on top of a substrate. """ # Define materials material_Particle = ba.HomogeneousMaterial("Particle", 0.0006, 2e-08) material_Substrate = ...
timbitsLeft = int(input()) # step 1: get the input totalCost = 0 # step 2: initialize the total cost bigBoxes = int(timbitsLeft / 40) totalCost = totalCost + bigBoxes * 6.19 # update the total price timbitsLeft = timbitsLeft - 40 * bigBoxes # calculate timbits still needed if timbitsLeft >= 20: ...
import sqlite3 with open('schema.sql', 'r') as f: conn = sqlite3.connect('poolheight.db') c = conn.cursor() c.executescript(f.read()) conn.commit() c.close()
""" API operations on a history. .. seealso:: :class:`galaxy.model.History` """ import pkg_resources pkg_resources.require( "Paste" ) from galaxy import exceptions from galaxy.web import _future_expose_api as expose_api from galaxy.web import _future_expose_api_anonymous as expose_api_anonymous from galaxy.web import _...
import datetime from django.urls import reverse from django.utils import timezone from oppia.test import OppiaTransactionTestCase from tests.reports import utils class SearchesViewTest(OppiaTransactionTestCase): fixtures = ['tests/test_user.json', 'tests/test_oppia.json', 'tests/test...
__author__ = 'chris' #Nov 1 2014 Chris Hamm # Added the basic connection code # Server now stores the IP addresses of all the connect nodes # Server now prompts user for how many nodes there will be # Server waits for all nodes to connect # Multiple new status lines have been...
import os import sys import subprocess import argparse import time import shutil import datetime from mission_directories.mission import Mission from mission_directories.mission import get_mission from bnr_map_manager import get_locations_root def main(): parser = argparse.ArgumentParser(description="Run analytics ...
import unittest import uno from testcollections_base import CollectionsTestBase from com.sun.star.beans import PropertyValue def getSheetCellRangesInstance(spr): return spr.createInstance("com.sun.star.sheet.SheetCellRanges") class TestXNameContainer(CollectionsTestBase): # Tests syntax: # obj[key] = val...
import sys import logging import os from abstract_step import * logger = logging.getLogger("uap_logger") class Bcl2FastqSource(AbstractSourceStep): def __init__(self, pipeline): super(Bcl2FastqSource, self).__init__(pipeline) # set # of cores for cluster, it is ignored if run locally self.se...
__docformat__ = 'restructuredtext' import sys import os.path import traceback import getopt from gi.repository import Gtk from gi.repository import GdkPixbuf from gi.repository import Gdk from gi.repository import GLib from gi.repository import GObject from samba import credentials from samba.dcerpc import srvsvc, secu...
import threading import time import random import datetime import logging import json import config log = logging.getLogger(__name__) try: if (config.max31855 == config.max6675): log.error("choose (only) one converter IC") exit() if config.max31855: from max31855 import MAX31855, MAX31855Error l...
import numpy as np import scipy.stats as stats def activityFlowXtoY(activity,connectivity): """ Activity flow mapping between component (e.g., region or network) X to component Y Parameters: activity - a sample (e.g., miniblocks) X feature (e.g., regions/vertices) matrix connectivity - a fun...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from six import string_types from ansiblite import constants as C from ansiblite.errors import AnsibleParserError from ansiblite.playbook.attribute import FieldAttribute from ansiblite.playbook.base import Base from ansiblite.playbo...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.parsing import DataLoader class DictDataLoader(DataLoader): def __init__(self, file_mapping=dict()): assert type(file_mapping) == dict self._file_mapping = file_mapping self._build_...
import urllib.parse from bs4 import BeautifulSoup import requests import requests.exceptions from cloudbot import hook from cloudbot.util import urlnorm @hook.command("down", "offline", "up") def down(text): """<url> - checks if <url> is online or offline :type text: str """ if not "://" in text: ...
from yanntricks import * def NOCGooYRHLCn(): pspict,fig = SinglePicture("NOCGooYRHLCn") mx = -0.5 Mx = 7 x0 = 5 dx = 1 x=var('x') f = phyFunction(-((x+0.5)/3)**2+4+x-3).graph(mx,Mx) f.parameters.color="brown" P=f.get_point(x0) P.put_mark(0.4,P.advised_mark_angle(pspict),"$f(x)$",...
""" A simple example showing how to use classification """ import csv import importlib from nupic.data.datasethelpers import findDataset from nupic.frameworks.opf.modelfactory import ModelFactory from generate_data import generateData from generate_model_params import createModelParams from settings import \ NUMBER_O...
"""Distutils extensions and utilities""" from distutils.command.clean import clean from distutils.command.install_data import install_data from distutils.command.install_lib import install_lib from distutils.core import setup as DS_setup from distutils.dep_util import newer from distutils.log import info, warn from dis...
""" PlayStation 1 standard image format Implemented according to: http://triple-tech.org/Wiki/Tim http://rewiki.regengedanken.de/wiki/.TIM """ import struct MAGIC = b'\x10\x00\x00\x00' # 4 bytes, second byte is version, only ver. 0 known to exist BPP4 = 0x08 # 4 bits paletted BPP8 = 0x09 # 8 bits paletted BPP16 = 0x02 ...
__author__ = "Rafael Ferreira da Silva" from Pegasus.db.modules import Analyzer as BaseAnalyzer from Pegasus.db.modules import SQLAlchemyInit class Analyzer(BaseAnalyzer, SQLAlchemyInit): """Load into the JDBCRC SQL schema through SQLAlchemy. Parameters: - connString {string,None*}: SQLAlchemy connection ...
import collections import dataclasses import pytest from lenses import bind, lens, maybe def test_lens_get(): assert lens.get()(10) == 10 assert lens[1].get()([1, 2, 3]) == 2 def test_lens_collect(): assert lens.Each()[1].collect()([[1, 2], [3, 4]]) == [2, 4] def test_lens_get_monoid(): assert lens.Each...
from django.contrib.auth.decorators import login_required from workflow import render from django.conf import settings import datetime from workflow.timemachine import cookie from django import shortcuts @login_required def index( request ): return render.render( request, "timemachine/index.html", dateFormat = sett...
"""Sub-package containing the matrix class and related functions.""" from defmatrix import * __all__ = defmatrix.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench
import turtle from turtle import* """def drawZigZag(size,depth): if (depth==0): return lt(90) fd(size/2) rt(90) fd(size) back(size) lt(90) back(size) rt(90) back(size) fd(size) lt(90) fd(size) rt(90) drawZigZag(size,depth-1) """ def Drawzigzag(size, de...
from __future__ import absolute_import, division, print_function, \ unicode_literals from sqlalchemy.schema import Column, ForeignKey, Index, MetaData, \ PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.types import Boolean, DateTime, Float, Integer, \ LargeBinary, Unicode, UnicodeText from .ty...
import random import sys MAX_LEN = 9 TEST_LEN = 100000 REMOVE_THRESHOLD = 6 all_db = {} db = {} input_lines = [] output_lines = [] (WRITE, REMOVE, READ) = range(3) for i in xrange(TEST_LEN): test_len = random.randint(1, MAX_LEN) chars = [] for j in xrange(test_len): chars.append(chr(random.randint(3...
from django.contrib import admin from .models import Officer, Supervisor admin.site.register(Officer) admin.site.register(Supervisor)
from gnuradio import gr, gr_unittest import random class test_packing(gr_unittest.TestCase): def setUp(self): self.fg = gr.flow_graph () def tearDown(self): self.fg = None def test_001(self): """ Test stream_to_streams. """ src_data = (0x80,) expected_...
"""Perdew-Zunger SIC to DFT functionals. Self-consistent minimization of self-interaction corrected functionals (Perdew-Zunger). """ import sys from math import pi, sqrt, cos, sin, log10, exp, atan2 import numpy as np from ase.units import Bohr, Hartree from gpaw.utilities.tools import dagger from gpaw.utilities.blas i...
from django.conf.urls import url from .views import * urlpatterns = [ # Admin home page url(r'^admin_home_page/', admin_home_page, name ="admin_home_page"), url(r'^submit_new_form/', submit_new_form, name ="submit_new_form"), url(r'^new_form_instance/([^/]*)/([^/]*)', new_form_instance, name ="new_form_...
''' @Author: zhaoyang.liang @Github: https://github.com/LzyRapx @Date: 2020-02-14 21:44:54 ''' """ Functions implementing maths in linear algebra. function list: dot_mod(A, B, mod=0): return matrix multiplication of A * B % mod matrix multiplication, avoid overflow in numpy ...
"""A centralized data management structure that allows multiple named FIFO streams. SensorGraph is organized around data streams, which are named FIFOs that hold readings. For the purposes of embedding SensorGraph into a low resource setting you can limit the number of readings stored in any given FIFO as needed to pu...
from django.db import migrations, models from django.db import migrations def forward(apps, schema_editor): # User profile Projects were unique for each (User, Organization) pair. Make # them unique per User by keeping only the first one for each User. Project = apps.get_model("siteapp", "Project") prof...
from lib.plots.AbstractPlot import AbstractPlot class MeanSequencePlot(AbstractPlot): def __init__( self, means, stds ): self.means = means self.stds = stds params = dict() params['xlim'] = [0,len(means)] maxi = max(abs(means))+max(stds)+100 params['ylim'] = [-maxi,ma...
bl_info = { "name": "Texture Atlas", "author": "Andreas Esau, Paul Geraskin, Campbell Barton", "version": (0, 2, 1), "blender": (2, 67, 0), "location": "Properties > Render", "description": "A simple Texture Atlas for unwrapping many objects. It creates additional UV", "wiki_url": "http://wi...
from distutils.core import setup import py2exe setup(windows=['mops.py'], packages=['mops'], options={"py2exe": { "includes": ['redis', 'win32api', 'win32con', 'requests', 'psutil' ] } } # single executable doesn't seem to work #options = {'py2exe': {'bund...
from ui.settings import Settings from ui.torrent_settings_dialog import TorrentPreferencesDialog from ui.settings_dialog import SettingsDialog from ui.ui_threads import DataConsumer from ui.checkbox_dialog import CheckboxedMessageBox from core.util import Utility from core.torrent_info_getter import InfoGetter from cor...
from moviepy.video.fx.all import speedx from operator import attrgetter from itertools import cycle def score9(videosizer, videopool, videoon, solver): print("SECTION 9 VIDEO") assert solver.finished() su = solver.sudoku recs = 3 row = solver.sudoku.rows[8] box = solver.sudoku.boxes[8] colum...
import os import shlex from docmanager.action import Actions from docmanager.cli import parsecli def test_docmanager_aliascmd_0(capsys): """Tests the 'alias' command """ testdir = os.path.dirname(__file__) configfile = os.path.join(testdir, "testfiles/dm-test.conf") cmd = "alias --own {} set my alia...
from __future__ import unicode_literals import os import tempfile from collections import Iterator from unicodedata import normalize import requests try: import urllib3 except ImportError: from requests.packages import urllib3 import rows try: urllib3.disable_warnings() except AttributeError: # old vers...
import unittest import pylcdproc import time import lcdtesthelper class TestHBargraphLCD(lcdtesthelper.StaticLCDTest): max_width = None @classmethod def instantiateLCD(klass, appname="TestHBargraphLCD", host=lcdtesthelper._default_test_host(), debug=False): return pylcdproc.HB...
from django.http import JsonResponse from django.views.generic import CreateView, ListView, DeleteView, UpdateView from django.contrib.messages.views import SuccessMessageMixin from lib.messages import DeleteMessageMixin from .personas.models import EstadoCivil from .afiliados.models import Plan from .forms import Plan...
""" HipparchiaServer: an interface to a database of Greek and Latin texts Copyright: E Gunderson 2016-21 License: GNU GENERAL PUBLIC LICENSE 3 (see LICENSE in the top level directory of the distribution) """ import multiprocessing from flask import Flask hipparchia = Flask(__name__) """ https://docs.python.org/3.8...
icinga_api_endpoint = "https://127.0.0.1:4665/v1/objects" enable_consul = False consul_host = "localhost" domain_name = "example.com" icinga_auth = ("root", "icinga") icinga_headers = {"Accept": "application/json"} excluded_machines = ['docker-icinga2'] excluded_services = ['ssh', 'ping4'] host = None monitoring_profil...
import sys import pickle import pandas as pan from nltk import pos_tag, word_tokenize def add_pos_tags_to_english_docs(docs): output = [] for doc in docs: if not (type(doc) is str): output.append([]) continue sys.stdout.write("*") tagged_toks = pos_tag(word_tokeni...
import itertools import random import functools import os from AutoTestCase import AutoTestCase from TestOperation import TestOperation from TestScript import TestScript from utils import BINOPS, nats, tail, binop, head, isEmpty, COLORS,\ DIRS, BOOLS, randint, randomIntList, randomList, flatten, group, copy_file im...
import inspect import itertools import os import posixpath import re from tempfile import NamedTemporaryFile from zipfile import ZipFile from flask import g, request, session from flask.helpers import get_root_path from werkzeug.utils import secure_filename from indico.core.config import config from indico.core.plugins...
import sys from PIL import Image if len(sys.argv) != 2: print "Please specify a source filename" sys.exit(-1) sourcefilename = sys.argv[1] name = sourcefilename.split(".")[0] image = Image.open(sourcefilename) image = image.convert("1") (xsize, ysize) = image.size if ysize != 20: print "Image height must be...
"""Tests to check that Routing Service classes are working 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 Foundation, either version 3 of the License, or any later version. :Copyright: 2014-2020 Javier...
"""! @brief Examples of usage and demonstration of abilities of ROCK algorithm in cluster analysis. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ from pyclustering.cluster.rock import rock; from pyclustering.samples.definitions import SIMPLE_SAMPLES; from pyclustering.samp...
import nose from rhuilib.util import * from rhuilib.rhui_testcase import * from rhuilib.rhuimanager import * from rhuilib.rhuimanager_cds import * from rhuilib.rhuimanager_client import * from rhuilib.rhuimanager_repo import * from rhuilib.rhuimanager_sync import * from rhuilib.rhuimanager_entitlements import * from rh...
import odoo.tests @odoo.tests.common.at_install(False) @odoo.tests.common.post_install(True) class TestUi(odoo.tests.HttpCase): def test_01_admin_forum_tour(self): self.phantom_js("/", "odoo.__DEBUG__.services['web_tour.tour'].run('question')", "odoo.__DEBUG__.services['web_tour.tour'].tours.question", logi...
""" Created on Tue Feb 25 05:46:36 2020 @author: deborahkhider Contains all relevant mapping functions """ __all__=['map_all'] import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import numpy as np import pandas as pd from .plotting import savefig, showfig def set_proj(projecti...
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_SvnLogBrowserDialog(object): def setupUi(self, SvnLogBrowserDialog): SvnLogBrowserDialog.setObjectName("SvnLogBrowserDialog") SvnLogBrowserDialog.resize(700, 600) self.verticalLayout = QtWidgets.QVBoxLayout(SvnLogBrowserDialog) self...
""" This module defines the :class:`GeoAxes` class, for use with matplotlib. When a Matplotlib figure contains a GeoAxes the plotting commands can transform plot results from source coordinates to the GeoAxes' target projection. """ from __future__ import (absolute_import, division, print_function) import collections i...
import models models.init() from models import connection from models import User, Log, Group import config def setup_user_collection(): col = connection[User.__database__][User.__collection__] User.generate_index(col) def setup_log_collection(): db = connection[Log.__database__] #http://www.mongodb.org/display...
import struct import re data = list() j = 0 x = list() y = list() wi = 0.0 wi = struct.pack('d', wi) fh3 = open('dgflipped_Cartesian.bin', 'wb') while 1: j = j + 1 #assign the filename to read (B000xx.txt) readfile = 'B{0:05d}.txt'.format(j) #assign the filename to write (datain.xx.bin) writefile = 'dgflipped...
from systems.provided.futures_chapter15.estimatedsystem import futures_system from sysdata.configdata import Config my_config = Config("examples.breakout.breakoutfuturesestimateconfig.yaml") system = futures_system(config=my_config) system.config.notional_trading_capital = 100000 system.set_logging_level("on") system.a...
import unittest import threading import os import sys import time import traceback import uuid from sets import Set from datetime import datetime from time import mktime from workflow import Workflow from provisioner import Provisioner from provisioner import BudgetException from provisioner import get_nmax from provis...
def menu(prompt, choices): print '\n\n{0}\n'.format(prompt) count = len(choices) for i in range(count): print '({0}) {1}'.format(i + 1, choices[i]) response = 0 while response < 1 or response > count: response = raw_input(' Type a number (1-{0}): '.format(count)) if respon...
''' The ``pysyncml.context`` package provides the entry point into most pysyncml operations via the :class:`pysyncml.Context <pysyncml.context.Context>` class. ''' import sqlalchemy.ext.declarative from sqlalchemy.orm.exc import NoResultFound from . import model, codec, router, protocol, synchronizer class Context(obje...
__author__ = 'Christopher Nelson' class Replicate: def __init__(self, name, required_concurrent): """ Creates a new rule that requires a job to run on multiple nodes. The rule requires that the job run on different nodes. :param name: The tag name to evaluate. :param required...
"""Configuration parameters stored in a module namespace. This file is loaded during the program initialisation before the main module is imported. Consequently, this file must not import any other modules, or those modules will be initialised before the main module, which means that command line options may not have b...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bookvoyage.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is r...
from __future__ import unicode_literals from sqlalchemy.dialects.postgresql import JSON from sqlalchemy.ext.declarative import declared_attr from indico.core.db import db from indico.util.locators import locator_property from indico.util.string import format_repr, return_ascii, text_to_repr def _get_next_position(conte...
""" ❏DChars❏ : dchars/languages/grc/transliterations/betacode/__init__.py """
from itertools import * def print_board( b, X, Y, xchar ): for y,row in enumerate( b[ i : (i+2*X+3) ] for i in xrange(0,(2*X+3)*(2*Y+3),2*X+3) ): if y<1 or y>=2*Y+2: continue for x,i in enumerate( row ): if x<1 or x>=2*X+2: continue if x%2==y%2==1: print '+', # corners ...
import logging import os import uuid from django.db import models from django.db.models import signals from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.contrib.contenttypes import generic from django.contrib.staticfiles ...
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.db.models import Q from django.db import models, transaction from django.db.utils import OperationalError def get_user_file(instance, filename): return 'users/{0}_{1}_{2}'.format(instance.name, instance...
from final_types import FinalType from stations import * from datetime import timedelta, date import structures globalValues = {} globalFields = [ "EventServiceProvider", "EventCode" ] currentStructure = structures.defaultNavigoStructure def interpretDate(value): if len(value)==0: return "Empty date...
from __future__ import generator_stop from tatsu._config import __version__ from tatsu._config import __toolname__ from tatsu.tool import ( # pylint: disable=W0622 main, compile, parse, to_python_sourcecode, to_python_model, ) assert __version__ assert __toolname__ assert compile assert parse asser...
from unittest import TestCase from Cryptography import Cryptography class TestCryptography(TestCase): def setUp(self): self.c = Cryptography() self.msg = "My dirty secret message." self.key = "key1234" def test_validate(self): encrypted = self.c.encrypt(self.msg, self.key) ...
import KmerUtil class Scales: _250NM = "250nm" _100NM = "100nm" _25NM = "25nm" class Purifications: HPLC = "HPLC" NONE = "STD" PAGE = "PAGE" class IdtOrder: def __init__(self,ProductName,Sequence,Scale=Scales._25NM, Purification=Purifications.NONE): """ Recor...
try: import simplejson as json except ImportError: import json import uuid import datetime from trytond.model import ModelSQL, fields from trytond.config import config from .. import backend from ..transaction import Transaction __all__ = [ 'Session', 'SessionWizard', ] class Session(ModelSQL): "Ses...
from __future__ import unicode_literals from headphones import logger import time import re import os import json import headphones import requests from base64 import b64encode import traceback delugeweb_auth = {} delugeweb_url = '' deluge_verify_cert = False scrub_logs = True def _scrubber(text): if scrub_logs: ...
''' SCons tool for bundling files into the formats zip, tar.gz and tar.bz2. ''' import os, tarfile, zipfile def build_tar(target_fname, sources, prefix, mode): print 'creating tar file:', target_fname tar = tarfile.open(target_fname, mode=mode) for src in sources: path = str(src) tar.add(pat...
from PyQt5.QtCore import pyqtSignal, QThread, QObject from umlfri2.application.threadmanager import ThreadManager class QTThreadManager(QObject, ThreadManager): class __Thread(QThread): def __init__(self, callback): super().__init__() self.__callback = callback def run(self):...
import contextlib import textwrap from pathlib import Path from subprocess import CalledProcessError from unittest import mock from unittest.mock import call import fixtures import pytest import testtools from testtools.matchers import Equals from snapcraft.internal import repo from snapcraft.internal.repo import error...
import shutil import re import os from gettext import gettext as _ from gi.repository import Gtk from sensors import SensorManager from sensors import ISMError VERSION = '0.7.1~stable' def raise_dialog(parent, flags, type_, buttons, msg, title): """It raise a dialog. It a blocking function.""" dialog = Gtk.Mess...
__author__ = 'Alexander' "User forgets to declare dimensions and fact tables " import pygrametl from pygrametl.datasources import SQLSource from pygrametl.tables import Dimension, FactTable import sqlite3 input_conn = sqlite3.connect('input.db') input2_conn = sqlite3.connect('input2.db') output_conn = sqlite3.connect('...
from __future__ import print_function from sys import argv, exit, stderr from os import mkdir, makedirs, chdir, system, getcwd from os.path import getsize from re import search from json import loads from struct import pack from errno import EEXIST if len(argv) < 5: print("Usage: bundle.py <info json> <assembly for...