code
stringlengths
1
199k
import os, concurrent.futures import const, rwlogging, dataloader from pool import Pool from rwlogging import log if const.STRATEGY_TYPE == 1: import maStrategy as strategy elif const.STRATEGY_TYPE == 2: import patternStrategy as strategy elif const.STRATEGY_TYPE == 3: import vmaStrategy as strategy path = os.path.d...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fileuploads', '0025_result_group_name'), ] operations = [ migrations.AlterField( model_name='result', name='group_name', ...
"""Searches for albums in the MusicBrainz database. """ from __future__ import division, absolute_import, print_function import musicbrainzngs import re import traceback from six.moves.urllib.parse import urljoin from beets import logging import beets.autotag.hooks import beets from beets import util from beets import ...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from le_utils.constants import format_presets from kolibri.core.content import hooks as content_hooks from kolibri.plugins import KolibriPluginBase from kolibri.plugins.hooks import register_hook from ko...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('smush', '0001_initial'), ] operations = [ migrations.CreateModel( name='Document', fields=[ ('id', models.AutoFie...
import socket import getpass from threading import Thread """This module taces care of the server-specific logic.""" class ClientConnection: """Base class which takes care of initializing the client \ for either chat or transfer.""" def __init__(self, server_ip, client_ip, callbacks): self.server_ip...
import dork_compose.plugin class Plugin(dork_compose.plugin.Plugin): def preprocess_config(self, config): config.services.append({ 'name': 'dork_tracker', 'image': 'alpine:3.4', 'command': 'tail -f /dev/null', 'volumes': [], 'labels': { ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "del_proj.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
"""Relative Components Analysis (RCA) RCA learns a full rank Mahalanobis distance metric based on a weighted sum of in-class covariance matrices. It applies a global linear transformation to assign large weights to relevant dimensions and low weights to irrelevant dimensions. Those relevant dimensions are estimated usi...
"""Module containing class `MetadataImporter`.""" from collections import defaultdict import datetime import logging from django.db import transaction from vesper.command.command import CommandSyntaxError from vesper.django.app.models import ( AnnotationConstraint, AnnotationInfo, Device, DeviceConnection, Devi...
from django import forms from tumblelog.fields import ImageURLField POST_TYPES = { 'photo': {'url': forms.URLField(label='Source URL', required=False), 'photo': ImageURLField(label='Photo URL'), 'text': forms.CharField(required=False, widget=forms.Textarea),}, 'video': {'html': forms...
from feature_extraction import feature_extraction_driver from model_training import training_driver from util.log import Log import sys class CommandEnum: PRE_PROCESSING = "-pre" POST_PROCESSING = "-post" TRAIN_FACTS = '-train' class Command: @staticmethod def execute(command_list): """ ...
import sys import bluetooth._bluetooth as bluez import ble def parse_events(sock, desired_event, loop_count=10): flt = bluez.hci_filter_new() bluez.hci_filter_all_events(flt) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) sock.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, flt) for i in range(loo...
import typing if typing.TYPE_CHECKING: # pragma: no cover import importlib.metadata as importlib_metadata else: try: import importlib.metadata as importlib_metadata except ImportError: import importlib_metadata __version__ = importlib_metadata.version(__name__.split(".", 1)[0]) __all__ = ["...
"""Function to counts on the fly the spike in sequences given as a parameter in the yaml file""" import os import sys import pandas as pd import bcbio.pipeline.datadict as dd from bcbio.utils import (file_exists, safe_makedir, is_gzipped, partition, rbind) import bcbio.utils as utils from bcbio.distributed.transaction ...
class CpuStoppedCall(Exception): pass instruction_map = {} instruction_names = {} DEBUG = False def instruction(alt=None): def decorator(func): number = 110 + len(instruction_map) instruction_map[number] = func instruction_names[alt or func.__name__] = number return func retu...
import six from blist import sorteddict from recordtype import recordtype from .authtree import MemoryPatriciaAuthTree from .core import Output from .hash import hash256 from .mixins import SerializableMixin from .serialize import BigCompactSize, LittleInteger, VarInt from .tools import compress_amount, decompress_amou...
from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class RawTransactionsTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 3 def setup_network(self, split=False): self.nod...
from espeak import espeak from mpd import MPDClient def say(msg): client = MPDClient() client.connect("localhost", 6600) s = client.status()['state'] if s == 'play': client.pause() client.close() client.disconnect() print(msg) espeak.set_voice("fr") espeak.synth(msg)
import collections import itertools import six from purplex.exception import TableConflictError, StartSymbolNotReducedError from purplex.grammar import Grammar, Production, END_OF_INPUT from purplex.lex import Lexer from purplex.token import Token END_OF_INPUT_TOKEN = Token(END_OF_INPUT, '', '', 0, 0) LEFT = 'left' RIG...
from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) long_description = """ Edgesense ========= This is the python library and scripts for the Edgsense social network...
from test.helper import ( execute_add, wait_for_processes, ) from test.helper import command_factory def test_remove_fails(daemon_setup): """Fail if removing a non existant key.""" response = command_factory('remove')({'keys': [0]}) assert response['status'] == 'error' def test_remove_running(daemon...
""" Implementacao do algoritmo de busca sentinela """ def busca_sentinela(list_to_search, value): """ Implementacao de um algoritmo de busca sentinela. Argumentos: value: Any. Valor a ser buscado na lista list_to_search: list. lista na qual o valor sera buscado Retorna o indice do valor em "list...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('download_manager', '0002_auto_20141202_0152'), ] operations = [ migrations.AddField( model_name='communityuser', name='country', ...
""" Karl Persson, Mac OSX 10.8.4/Windows 8, Python 2.7.5, Pygame 1.9.2pre Main class for Pulse game """ import sys import pygame from pygame.locals import * import Explosion, FileManager, GameObjects, HUD, LevelManager, Menues class PulseGame: def __init__(self): pygame.init() # Initializing file ma...
import sys import os import errno import paramiko from .base import BaseBackend from ..utils import filter_delete_filename_list from ..six import reraise class SFTPBackend(BaseBackend): """ ssh后端 """ host = None port = None username = None password = None remote_dir = None transport ...
import os basedir = os.path.abspath(os.path.dirname(__file__)) DEBUG = True PORT = 5000 HOST = "127.0.0.1" SQLALCHEMY_ECHO = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = "postgresql://{DB_USER}:{DB_PASS}@{DB_ADDR}/{DB_NAME}".format(DB_USER="test2", DB_PASS="abc@123", DB_ADDR="127.0.0.1", DB_NAM...
from peewee import * from .base import IS_MYSQL from .base import IS_SQLITE from .base import ModelTestCase from .base import TestModel from .base import db from .base import get_in_memory_db from .base import requires_sqlite class Package(TestModel): barcode = CharField(unique=True) class PackageItem(TestModel): ...
from Products.CMFCore.utils import getToolByName from Products.CMFPlone.utils import _createObjectByType, safe_unicode from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.exportimport.instruments.logger import Logger from bika.lims.idserver import renameAfterCreation from bika.lim...
from functools import wraps from flask import request def authenticate(func): @wraps(func) def auth_call(*args, **kwargs): if request.json: # TODO STEVE IMPLEMENT AUTH (Auth currently based on request.json existing) return func(*args, **kwargs) else: return "Authenticati...
try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys class UI(Frame): def __init__(self, master, im, value=128): Frame.__init__(self, master) self.image = im self.value = value self.canvas = Canvas(self, width=im.size[...
from datetime import datetime import constants from lib.connectwise_py.connectwise.agreement import Agreement from lib.connectwise_py.connectwise.contact import Contact from .connectwise import Connectwise class Member: def __init__(self, identifier, **kwargs): self.officeEmail = None self.identifie...
"""Template jinja filters.""" from datetime import datetime import copy import hashlib import json as json_lib import random import re import jinja2 import slugify from babel import dates as babel_dates from babel import numbers as babel_numbers from grow.common import json_encoder from grow.common import urls from gro...
import os ENV = os.environ.get('ACHOO_DEBUG') class Config(object): MSG = '(beta)' VERSION = '0.1' DEBUG = True if ENV == 'local' else False
import os, os.path as op import glob from nipype.utils.filemanip import split_filename list_to_reg = glob.glob("p0*_maths.nii") for in_file in list_to_reg: path, name, ext = split_filename(in_file) outfile = op.abspath(name + '_rl' + ext) blah = "mri_convert %s --out_i_count 200 --out_j_count 200 --out_k_co...
from utils.munin.base import MuninGraph class NBMuninGraph(MuninGraph): @property def graph_config(self): return { 'graph_category' : 'PyTune', 'graph_title' : 'PyTune Classifiers', 'graph_vlabel' : '# of classifiers', 'graph_args' : '-l 0', 'f...
from flask import Flask, render_template from flask_bootstrap import Bootstrap app = Flask(__name__) Bootstrap(app) app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') @app.route('/') def home(): return render_template('home.jade') @app.route('/a') def extra(): return render_template('parallax.jade') if _...
__requires__ = 'scikit-image==0.11.3' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('scikit-image==0.11.3', 'console_scripts', 'skivi')() )
"""Placeholder module, that's where the smart things happen.""" import logging import os import time import re from django import forms from django.core.mail import send_mail from django import template from django.template import TemplateSyntaxError from django.core.files.storage import default_storage from django.for...
try: from setuptools import setup except ImportError: from distutils.core import setup import os def dump_sibling_file(file_name): with open(os.path.join(os.path.dirname(__file__), file_name), 'r') as f: return f.read() setup( name = 'subdue', packages = ['subdue', 'subdue.co...
import logging import coreapi from django.http.response import FileResponse from django.http.response import Http404 from rest_framework import mixins from rest_framework import renderers from rest_framework import viewsets from rest_framework.filters import BaseFilterBackend from rest_framework.pagination import PageN...
import json from rhino import Mapper, Resource, ok from rhino.errors import BadRequest def read_json(f): try: obj = json.load(f) except ValueError as e: raise BadRequest("Invalid JSON: %s" % e) return obj def json_api_wrapper(app): def wrap(request, ctx): if request.content_type ...
""" WSGI config for kohrsupply project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTIN...
import requests import json import os from time import sleep from pprint import pprint f = open("creds.txt") lines = f.readlines() f.close token = lines[0].strip() print "Token loaded" last_update = 0 if os.path.isfile("offset"): f = open("offset", 'r') last_update = int(f.read()) f.close print "Offset ...
"""app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based vi...
from django.contrib import admin from .models import Link @admin.register(Link) class LinksAdmin(admin.ModelAdmin): list_display = ('slug', 'url', 'create_date')
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^$', 'applications.views.index'), url(r'^login/$', 'django.contrib.auth.views.login', { 'template_name': 'login.html'}), url(r'^logout/$', 'applications.vie...
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../")) import argparse import numpy as np import chainer from chainer import cuda from chainer import optimizers from chainer import serializers import alex from mlimages.gather.imagenet import ImagenetAPI from mlimages.label import LabelingM...
import os import sys import csv sys.setrecursionlimit(100000000) import wave import xml.etree.ElementTree as ET from textgrid import TextGrid, IntervalTier from bs4 import BeautifulSoup from alignment.sequence import Sequence from alignment.vocabulary import Vocabulary from alignment.sequencealigner import SimpleScorin...
""" Craft, sign and broadcast Tetcoin transactions. Interface with Tetcoind. """ import os import sys import binascii import json import hashlib import re import time import getpass import decimal import logging import requests from pycoin.ecdsa import generator_secp256k1, public_pair_for_secret_exponent from pycoin.en...
from argparse import ArgumentParser from getpass import getuser, getpass from sys import stderr from edsudoku.server import app from edsudoku.server.database import Base, engine, commit from edsudoku.server.users import User, UserPermission __author__ = 'Eli Daian <elidaian@gmail.com>' def _parse_args(): """ Pa...
import _plotly_utils.basevalidators class TickformatValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="tickformat", parent_name="mesh3d.colorbar", **kwargs ): super(TickformatValidator, self).__init__( plotly_name=plotly_name, parent...
from figment import Component import random class Sticky(Component): """A difficult-to-drop item.""" def __init__(self, stickiness=0.5): self.stickiness = stickiness def to_dict(self): return {"stickiness": self.stickiness} def roll_for_drop(self): return random.random() < self.s...
from unittest import TestCase class RegressionTestCase(TestCase): ''' Used for regression tests. Allows to compare files and update test data if desired. ''' def regressionTest(self, referenceFile, outputFile): f = open(outputFile, 'r') actualText = f.read() f.close() ...
import py.test import threading from Queue import Queue from draco2.draco.context import DracoContext class BaseTestContext(object): context_class = None def setup_method(cls, method): cls.context = cls.context_class() def teardown_method(cls, method): # Required because py.test captures sys...
from subprocess import check_output import re import string import sys import os.path projectdir = sys.argv[1] inpath = os.path.join(projectdir, "AssemblyInfo.fs.tmpl") outpath = os.path.join(projectdir, "AssemblyInfo.fs") tag = check_output(["git", "describe", "--dirty=-d"]) main_match = re.match("v([^\-]+)(?:-([0-9a-...
import argparse import logging from pathlib import Path import tempfile from swaggertosdk.SwaggerToSdkNewCLI import ( build_project, ) from swaggertosdk.SwaggerToSdkCore import ( CONFIG_FILE, read_config, solve_relative_path, extract_conf_from_readmes, get_input_paths, get_repo_tag_meta, ) _...
import json import pytest from pyre_extensions import none_throws from backend.common.consts.alliance_color import AllianceColor from backend.common.consts.comp_level import CompLevel from backend.common.helpers.match_tiebreakers import MatchTiebreakers from backend.common.models.alliance import MatchAlliance from back...
"""Tests for the views of the ``django-user-media`` app.""" import os from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django_libs.tests.factories import UserFactory from django_libs.tests.mixins import ViewTestMixin from user_media.tests....
import re import operator debug = False test = True def is_number(s): try: float(s) if '.' in s else int(s) return True except ValueError: return False def load_stop_words(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @para...
import logging import time import pywintypes import win32con import win32event import win32file import win32security class WinFile(object): def __init__(self, filename): self._hfile = win32file.CreateFile( filename, win32con.GENERIC_READ | win32con.GENERIC_WRITE, win32con...
from django.contrib.auth.models import Group from django.db import models from django.utils.encoding import python_2_unicode_compatible import mptt from mptt.models import MPTTModel, TreeForeignKey from mptt.managers import TreeManager class CustomTreeManager(TreeManager): pass class Category(MPTTModel): name =...
from . import vdp_utils import json __author__ = '2b||!2b' BASE_URL = 'https://sandbox.api.visa.com' def reverse_funds(S): uri = '/visadirect/fundstransfer/v1/reversefundstransactions/' body = json.loads('''{ "acquirerCountryCode": "608", "acquiringBin": "408999", "amount": "24.01", "cardAcceptor": ...
from __future__ import division import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import grey_dilation from skimage import img_as_float from skimage import color from skimage import exposure from skimage.util.dtype import dtype_limits __all__ = ['imshow_all', 'imshow_with_histogram', 'mean_filter_de...
""" https://leetcode.com/problems/judge-route-circle/ https://leetcode.com/submissions/detail/129339056/ https://leetcode.com/submissions/detail/129339394/ """ class Solution1: def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ place = [0, 0] for move...
"""prix polynomial reversed init-value xor-out finder""" from crcmod import mkCrcFun from faulhaber_const import commands import time match = open('prix.txt', 'w+') start = time.clock() lastpos = 0 for possibility in range(0x2000000): polynomial = (possibility & 0xff) | 0x100 init_value = (possibility & 0xff00)...
"""Get the branch year.""" import sys script_dir = sys.path[0] import os import pdb import argparse import iris import remove_drift_year_axis as rdya def main(inargs): """Run the program.""" exp_cube = iris.load(inargs.experiment_file)[0] cntrl_cube = iris.load(inargs.control_file)[0] if inargs.branch_y...
""" dedupe provides the main user interface for the library the Dedupe class """ from __future__ import print_function, division from future.utils import viewitems, viewvalues, viewkeys import itertools import logging import pickle import numpy import multiprocessing import random import warnings import copy import os ...
from Sockets.TCP_Socket_Client import SocketTCPClient from .manager import Manager class Client(): def __init__(self, _parent=None): self.parent = _parent # Sockets self.socketTCP = None self.manager = None def start(self): self.setSocket() self.socketTCP.start() ...
from Solver1b import Solver1b def main(): solver = Solver1b() with open('input.txt', 'r') as input_file: directions_string = input_file.read().replace('\n', '') solution = solver.get_distance_to_first_repeat_visit(directions_string) print(solution) if __name__ == '__main__': main()
from bnol import workflows specimenClasses = ['TissueA']*30 + ['TissueB']*29 + ['TissueC']*30 + ['TissueD']*30 analysis = workflows.CuffnormInformativeGenes('tests/data/genes.count_table', specimenClasses) genes = analysis.informativeGenes(allGenes=True) print(genes)
import os import sys import json import shutil import subprocess import tempfile import traceback from test_framework.util import * from test_framework.netutil import * def run_bind_test(tmpdir, allow_ips, connect_to, addresses, expected): ''' Start a node with requested rpcallowip and rpcbind parameters, t...
from database import db import arrow class Appointment(db.Model): __tablename__ = 'appointments' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) phone_number = db.Column(db.String(50), nullable=False) delta = db.Column(db.Integer, nullable=False) time...
from django.apps import AppConfig class FormSubmissionsConfig(AppConfig): name = 'form_submissions'
import getch import os import sys import time import argparse import urllib2 import subprocess import cv2 import numpy as np from math import pi import select from train import process_image, model max_angle = pi / 4.0 key = 0 def display_img(): test = subprocess.check_output(fetch_last_img, shell=True) img_name = ar...
def triangle(a, b, c): sides = sorted([a, b, c]) unique_sides = sorted(set(sides)) if unique_sides[0] <= 0: raise TriangleError('All sides should be greater than 0') if sides[2] >= sides[0] + sides[1]: raise TriangleError('The sum of any two sides should be greater than the third one') ...
from beetle import * def main(): beetle, ui, groot, webthread = setup() b = beetle self = beetle webthread.start() stop = lambda: webthread.stop() variables = locals() variables.update(globals()) IPython.start_ipython(user_ns=variables) if __name__ == "__main__": main()
from __future__ import absolute_import, print_function, unicode_literals import atexit import logging import os import subprocess import sys from threading import Thread from django.contrib.staticfiles.management.commands.runserver import \ Command as RunserverCommand from django.core.management.base import Command...
import sqlalchemy.types import uuid class UUID(sqlalchemy.types.TypeDecorator): impl = sqlalchemy.types.BINARY(16) python_type = uuid.UUID def load_dialect_impl(self, dialect): return dialect.type_descriptor(self.impl) def process_bind_param(self, value, dialect): if value is None: ...
from setuptools import setup, find_packages setup(name='MODEL1310110014', version=20140916, description='MODEL1310110014 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1310110014', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages()...
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1204280035.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return...
import OOMP newPart = OOMP.oompItem(9581) newPart.addTag("oompType", "VREG") newPart.addTag("oompSize", "T220") newPart.addTag("oompColor", "X") newPart.addTag("oompDesc", "V05") newPart.addTag("oompIndex", "A1") OOMP.parts.append(newPart)
from __future__ import unicode_literals import django.contrib.auth.models import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ] operations = [...
from setuptools import setup, find_packages setup(name='BIOMD0000000255', version=20140916, description='BIOMD0000000255 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/BIOMD0000000255', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages()...
import csv import boto3 import datetime import logging import tempfile import pandas as pd from pandas import isnull from sqlalchemy import func from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.jobModels...
# !/usr/bin/env python import os, sys, time import subprocess import pickle from wrappers import Tmux from fonctions import * CONFIGSERVER = os.path.join(os.path.expanduser("~"), "TimeLaps", "configServer") if not os.path.isfile(CONFIGSERVER): subprocess.call(["python", os.path.join(os.path.expanduser("~"), "TimeL...
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import griddata from mpl_toolkits.mplot3d import Axes3D step = 10 # grid step a = np.loadtxt('lidar.txt', delimiter=',') x = a[:,0] y = a[:,1] z = a[:,2] xmin = 548040.0 ymin = 5129010.0 zmin = round(z.min() + 5.0, -1) xmax = 548300.0 ymax = 51...
def on_square(square): return pow(2,square-1) def total_after(square): return sum(pow(2,x) for x in range(square))
""" Minimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy) BSD License """ import numpy as np data = open('sonnet.txt', 'r').read() # should be simple plain text file chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print 'data has %d characters, %d unique.' % (data_size,...
from gi.repository import Gtk def window_delete_event(window, event): messagedialog = Gtk.MessageDialog() messagedialog.add_button("Do Not Quit", Gtk.ResponseType.CANCEL) messagedialog.add_button("Quit", Gtk.ResponseType.OK) messagedialog.set_markup("Quit the program?") if messagedialog.run() == Gtk...
import sys from jarray import * from java.lang import * from java.awt import * from java.util import * from java.lang.reflect import * from javax.swing.event import * from javax.swing import * from java.awt.event import * from java.net import * from java.io import * from org.csstudio.mps.sns.tools.bricks import WindowR...
"""Proxy definitions.""" from __future__ import absolute_import, print_function from flask import current_app from werkzeug.local import LocalProxy from .permissions import (CommunityAdminActionNeed, CommunityReadActionNeed, CommunityManageActionNeed, ...
import configparser from datetime import datetime from os import path, sep directory = path.dirname(path.realpath(__file__)) + sep config = None def get(section, key): global config if config is None: load() if config.get(section) is None: return None else: return config[section]...
import json import sys import os from sys import stdin, stdout def getRequest(): return json.loads(stdin.read(int(stdin.read(7)))) def sendResponse(response): dump = json.dumps(response) dump = "%07d%s" % (len(dump)+7, dump) stdout.write(dump) stdout.flush() def mainLoop(): info = {'type': 'info...
""" Sub-sample the preprocessed training set into subsets based on click/non-click per hour. Input ------ ptrain.csv: the preprocessed training set. num: the number of subsets. Default is 10. Output ------- train_1 ~ num.csv: num subsets of the training set. """ FILE_DIR = './data' import os import copy import csv impo...
from gi.repository import Gtk, Notify, GObject import logging import time import threading import os class PomodoroGui: def __init__(self): self.gladfile = "pomodoro.glade" self.builder = Gtk.Builder() self.builder.add_from_file(self.gladfile) #magic self.builder.connect_sign...
"""This module represents the Punjabi language. .. seealso:: http://en.wikipedia.org/wiki/Punjabi_language """ import re from translate.lang import common class pa(common.Common): """This class represents Punjabi.""" sentenceend = "।!?…" sentencere = re.compile(r"""(?s) # make . also match newlines ...
from datetime import datetime from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db.models import get_model from edc_crypto_fields.classes import ModelCryptor, FieldCryptor class Command(BaseCommand): args = '--list-models ...
import re from django import forms from django.contrib import admin from .models import Mirror, MirrorProtocol, MirrorUrl, MirrorRsync class MirrorUrlForm(forms.ModelForm): class Meta: model = MirrorUrl def clean_url(self): # ensure we always save the URL with a trailing slash url = self...
from __future__ import print_function import sys import warnings import wx import traits.etsconfig.api traits.etsconfig.api.ETSConfig.toolkit = 'wx' from .external import backport_chaco_viridis # noqa: F401 from .gui import frontend def prepare_app(): # bypass "iCCP: known incorrect sRGB profile": wx.Log.SetLo...