code
stringlengths
1
199k
__author__ = 'Bernhard Biskup' __email__ = 'bbiskup@gmx.de' __version__ = '0.1.2'
import os import sys import time from alice.utility import * from alice.utility import LOG as L from alice.script import testcase_normal class TestCase(testcase_normal.TestCase): def __init__(self, *args, **kwargs): super(TestCase, self).__init__(*args, **kwargs) @classmethod def setUpClass(cls): ...
import logging import sys from microservice.core import settings, communication, utils logger = logging.getLogger(__name__) def microservice(method=None, exposed=False): """ Decorator that declares a function as a microservice. This handles both calling out to a remote microservice, and being called as a mi...
""" Created on Tue Aug 02 22:31:39 2016 @author: Alex """ import numpy as np def main(width, length): a = 1.50 posList, zList = get_sites(a, width, length) nList = find_neighbors(a, posList) return posList,nList,zList def get_sites(a, width, length): a1 = a*np.array([1.,0.,0.]) a2 = a*np.array([...
''' This module contains functions that extracts metadata from mp3 file and returns a python dict of UniCode Characters NOTE : Windows Doesn't support unicode in powershell and console by default run `chcp 65001` if you getting errors related to unicode in windows ''' from mutagen.id3 import ID3 from bs4 import Unicode...
import unittest import numpy as np from batchcalc import zbc class TestReactantClassOnEtOH(unittest.TestCase): def setUp(self): self.r = cal.Reactant(id=15, name="ethanol", formula="C2H5OH", molwt=46.0688, ...
def subproc_pad_to_x480(fpath, destdir): import subprocess, os fname = fpath.split(".")[0] ext = fpath.split(".")[-1] if not destdir: destdir = os.path.dirname(fpath) outfile = os.path.join(destdir, fname + "_" + "l" + ".jpg") try: subprocess.call([ "convert", ...
from escpos import printer from escpos.escpos import EscposIO class print_TM9: def __init__(self, *args): self.label = "Test Print" # Need to find the port for this printer self.print_port = "/dev/ttyx" def print_test(self): self.print_instance.text(self.label) with Escpo...
files = [ '__init__.py', 'settings.py' ] requirements = [ 'djangorestframework', 'django-filter', ]
""" Talon.One API The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. ### Where is the AP...
from merc import feature class ConnectFeature(feature.Feature): NAME = __name__ install = ConnectFeature.install @ConnectFeature.hook("network.connect") def on_connect(app, server): app.run_hooks("server.pass", server, app.network.get_send_password(server), app.network.local.sid) a...
import pygame import sys from inputbox import * def get_textfield_value(screen, msg): textfield = ask(screen, msg) return textfield def create_label(screen, msg, pos): # initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error myfont = pygame.font.SysFont("monospace", ...
from flask import Flask, request import requests from os import system import re import sys import json import httplib import hmac import hashlib import time import os import base64 print os.environ.get("ACR_ACCESS_KEY") access_key = os.environ.get("ACR_ACCESS_KEY") access_secret = os.environ.get("ACR_ACCESS_SECRET") a...
from copy import deepcopy from typing import Any, Optional, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer from . import models from ._configuration import DeploymentScriptsClientConfiguration from .operations...
def is_prime(number): """Return True if *number* is prime.""" for element in range(2,number): if number % element == 0: print "hello" return False return True def print_next_prime(number): """Print the closest prime number larger than *number*.""" index = number while True: ...
from typing import Pattern, Dict from recognizers_text.utilities import RegExpUtility from recognizers_number.number.extractors import BaseNumberExtractor from recognizers_number.number.parsers import BaseNumberParser from recognizers_number.number.french.extractors import FrenchCardinalExtractor from recognizers_numbe...
import os LOG_FOLDER = "log" LOG_FILE = LOG_FOLDER + "/sync_couchbase.log" LOG_LEVEL = "debug" FROM_DB_HOST = "127.0.0.2" # IP address of the CouchBase Host (From) FROM_DB_ADMIN = "admin" FROM_DB_BUCKET = "frombucket" FROM_DB_VIEW = "dev_sync" TO_DB_HOST = "127.0.0.1" # IP address of the CouchBase Host (To) TO_DB_A...
import pypsa network = pypsa.Network() for i in range(3): network.add("Bus","electric bus {}".format(i),v_nom=20.) network.add("Bus","heat bus {}".format(i),carrier="heat") print(network.buses) network.buses["carrier"].value_counts() for i in range(3): network.add("Line","line {}".format(i), ...
from PyQt5.QtGui import * __author__ = 'magnus' icons_instance = None def get_icon(name): global icons_instance if not icons_instance: icons_instance = Icons() return icons_instance.icon(name) class Icons(object): def __init__(self): self._icons = {} self.make_icon("new", "icons/...
import datetime import xml.etree.ElementTree as ET from pysync_redmine.domain import (Repository, Project, Member, Task, Phase, Calendar, ...
import sys import numpy as np from vasprun import * from kpt_transform import * vasprun = VaspRun(str(sys.argv[1])) eigenvals = vasprun.read_eigenvals() kpoints = vasprun.read_kpoints() fermi,energy,dos = vasprun.read_dos() recip = vasprun.recip_lat() # Missing factor of 2*pi. Not sure if that matters. real_ops = read...
from .. import Provider as LoremProvider class Provider(LoremProvider): """Implement lorem provider for ``bn_BD`` locale.""" # source 1: https://en.wikipedia.org/wiki/Bengali_vocabulary # source 2: https://en.wikipedia.org/wiki/Bengali_grammar word_connector = " " sentence_punctuation = "।" word...
import logging import optparse import os import sys from logging import FileHandler from huey.consumer import Consumer from huey.utils import load_class def err(s): sys.stderr.write('\033[91m%s\033[0m\n' % s) def get_loglevel(verbose=None): if verbose is None: return logging.INFO elif verbose: ...
from django.conf import settings from django.core.management.base import CommandError, NoArgsCommand from django.contrib.sites.models import Site class Command(NoArgsCommand): help = ("Updates the default Site based on the DEFAULT_DOMAIN environment " "variable.") def handle_noargs(self, **options):...
import numpy as np n,m=map(int,input().split()) print(np.add())
sum = 0 for i in range(3, 1000): if (i % 3 == 0) or (i % 5 == 0): sum += i print sum
from django.conf.urls import url from . import views urlpatterns = [ url(r'^print/$', views.AgendaPDF.as_view(), name='agenda_pdf'), ]
"""Compare two or more bitcoinds to each other. To use, create a class that implements get_tests(), and pass it in as the test generator to TestManager. get_tests() should be a python generator that returns TestInstance objects. See below for definition. TestP2PConn behaves as follows: Configure with a BlockStore...
import abc import pymongo import scrapy from pymongo import MongoClient from libs.misc import get_spider_name_from_domain from libs.polish import * from novelsCrawler.items import NovelsCrawlerItem class SimpleSpider(scrapy.Spider): """ classdocs example: https://m.yushuwu.com/novel/31960.html """ d...
''' Created on Nov 29, 2016 @author: jphelps, Rochenko ''' import sys import psycopg2 import os import time def connect(): # user = os.environ['USER'] user = "postgres" try: conn = psycopg2.connect(dbname="postgres", user=user) return conn except: print "Failed to connect to the ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('members', '0006_auto_20160726_1927'), ] operations = [ migrations.AddField( model_name='member', name='spent_time_factor', ...
class Keyboard: buttons = [] home_buttons = ["오늘의 식단", "내일의 식단", "식단 리뷰", "운영시간", "도서관", "버스", "지하철" ] food_buttons = ['학식', '교식', '푸드코트', '스낵코너', '더 키친'] ratable_f...
import json from google.appengine.ext import ndb from backend.common.consts.media_type import MediaType from backend.common.models.media import Media from backend.common.models.team import Team from backend.tasks_io.datafeeds.parsers.fms_api.fms_api_team_avatar_parser import ( FMSAPITeamAvatarParser, ) def test_par...
import csv import functools import os import pickle from itertools import cycle from multiprocessing import Pool import matplotlib import matplotlib.pyplot as plt import numpy as np import qtutil import scipy.misc from PyQt4.QtCore import * from PyQt4.QtGui import * from pyqtgraph.Qt import QtGui from pyqtgraph.dockare...
import vaex import numpy as np def test_countna(): x = np.array([5, '', 1, 4, None, 6, np.nan, np.nan, 10, '', 0, 0, -13.5]) y_data = np.array([np.nan, 2, None, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) y_mask = np.array([0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1]) y = np.ma.MaskedArray(data=y_data, mask=y_mask) ...
import os import tempfile from copy import deepcopy from html import escape as html_escape from urllib.parse import quote from collections import namedtuple from collections import defaultdict as base_dd import htmlfn as hfn import requests from pyontutils.core import OntId, log as _log from pyontutils.utils import Ter...
import django_roa from aaee_front.settings import AAEE_API_ROOT_URL class DjangoROAModel(django_roa.Model): class Meta: abstract = True api_base_name = None @classmethod def get_resource_url_list(cls): """ Returns url like http://127.0.0.1:4567/api/v1.0/countries/ """ ...
from math import floor from py3njection import inject from learn.infrastructure.database import Database from learn.infrastructure.strings import caseless_equal from learn.services.repetition import compute_next_repetition class Answer: @inject def __init__(self, database: Database): self.database = dat...
import unittest import numpy import pytest import six import chainer from chainer import initializers from chainer import testing from chainer import utils import chainerx class _ContiguousnessMatched(Exception): pass def _is_f_contiguous(shape, strides, itemsize): if numpy.prod(shape) <= 1: return True...
from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_safe from ide.models.project import Project, TemplateProject from utils.keen_helper ...
import os import sys from ...helpers import testenv from ..utils import launch_background_thread app_thread = None if app_thread is None and sys.version_info >= (3, 5, 3) and 'GEVENT_TEST' not in os.environ and 'CASSANDRA_TEST' not in os.environ: testenv["tornado_port"] = 10813 testenv["tornado_server"] = ("htt...
SELECT_MOVIES_ORDERED_BY_RATING = ''' SELECT * FROM MOVIE ORDER BY RATING; ''' SELECT_PROJECTION_FOR_MOVIE = ''' SELECT p.*, COUNT(r.ROW * r.COL) FROM PROJECTION as p LEFT JOIN RESERVATION as r ON r.PROJECTION_ID = p.ID WHERE p.MOVIE_ID = ? GROUP BY p.ID ORDER BY p.DATE; ''' SELE...
import sqlite3 import json from util import check_bucket_name class SqliteBucket: def __init__(self, conn, name, indexfn=None): self.conn = conn self.name = name self.indexfn = indexfn def get(self, key, default=None): key = str(key) # lookup key/value pair c = se...
import unittest from test_helper import ShiftSolver from test_helper import ShiftCalendar from test_requests import team1_requests from datetime import date class TestShiftSolver(unittest.TestCase): def setUp(self): self.shift_calendar = ShiftCalendar(7) self.shifts = self.shift_calendar.iter_shift_...
from __future__ import print_function """ Orientation of an ordered triplet of points in the plane can be 1. counterclockwise 2. clockwise 3. collinear If orientation of (p1, p2, p3) is collinear, then orientation of (p3, p2, p1) is also collinear. If orientation of (p1, p2, p3) is clockwise, then orientation of (p3, p...
<<<<<<< HEAD <<<<<<< HEAD """ Python Character Mapping Codec iso8859_1 generated from 'MAPPINGS/ISO8859/8859-1.TXT' with gencodec.py. """#" import codecs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,err...
import six import time from ..const import ORDER_STATUS, SIDE, POSITION_EFFECT, ORDER_TYPE from ..utils import id_gen from ..utils.repr import property_repr, properties from ..utils.logger import user_system_log OrderPersistMap = { "_order_id": "_order_id", "_calendar_dt": "_calendar_dt", "_trading_dt": "_t...
""" Models for Front app Author : {{cookiecutter.author_name}} <{{cookiecutter.email}}> """ from django.db import models
""" Code to generate random radial velocities when performing synthetic tests of the performance of RV codes. """ import random def random_radial_velocity(): """ Pick a random radial velocity in km/s, following the approximate probability distribution expected for 4MOST galactic stars. :return: ...
"""Automated testing of GATT functionality using unittest.mock.""" import sys import unittest from unittest.mock import MagicMock from unittest.mock import patch import tests.obj_data from bluezero import constants adapter_props = tests.obj_data.full_ubits def mock_get(iface, prop): if iface == 'org.bluez.Adapter1'...
from client import Client from pdb import set_trace from random import randint, choice client = Client() for sset in client.subject_sets(client.mark_workflow): options = client.mark_workflow['tasks']['mark_primary']['tool_config']['options'] colors = [x['color'] for x in options] subject_set = sset['id'] ...
from django.conf.urls import patterns, url from .views import ProfileCreateView, ProfileDeleteView, ProfileDetailView, ProfileUpdateView urlpatterns = patterns('', url(r'^$', ProfileDetailView.as_view(), name='detail'), url(r'^new/$', ProfileCreateView.as_view(), name='new'), url(r'^edit/$', ProfileUpdateVi...
"""relais.py simple script for switching a actuator pin """ import RPi.GPIO as IO import sqlite3 as lite IO.setwarnings(False) IO.setmode(IO.BCM) """switch a GPIO pin""" def switch(dbName,id,pin,state): IO.setup(pin, IO.OUT) IO.output(pin, state) #write state in database try: db = lite.connect(d...
import sys, json def main(args): shit = [s.strip() for s in sys.stdin] # Hilariously, this was range(8) when I first did it # and it still passed part A. # Apparently none of the rect writes ever write to already lit # pixels, which means you could solve part A without implementing # rotate! ...
from bingmaps.urls import LocationByPointSchema from .fixtures import parametrize, BING_MAPS_KEY DATA = [ {'point': '1,2', 'includeEntityTypes': 'address', 'key': BING_MAPS_KEY }, {'point': '2,3', 'includeEntityTypes': 'address', }, { 'point': '1,2', 'includeEntityTy...
""" ERP+ """ __author__ = 'António Anacleto' __credits__ = [] __version__ = "1.0" __maintainer__ = "António Anacleto" __status__ = "Development" __model_name__ = 'linha_entrega.LinhaEntrega' import auth, base_models from orm import * from form import * try: from my_produto import Produto except: from produto im...
from flask import Flask, request, jsonify, Response from flask_cors import CORS, cross_origin from flask_mail import Mail from flask_httpauth import HTTPBasicAuth from flask import g from mentii import user_ctrl from mentii import class_ctrl from mentii import problem_ctrl from mentii import book_ctrl from problems imp...
import numpy as np from scipy.stats import randint, uniform from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import GradientBoostingClassifier from ..base import BaseClassifier from ..utils.stats import _uniform class MetaGradBoostingClassifier(BaseClassifier): """ Meta classifier wrapping ...
import numpy as np import math import sys import time from joblib import Parallel, delayed from SimComponents import Star, Galaxy, printProgress import argparse def write(s): w = "{0},{1},{2},{3},{4}\n".format(currentIteration, s.pos[0], s.pos[1], s.pos[2], s.origin.color) f.write(w) def getdist(pos1, pos2): ...
sessions = list(range(108,149)) skyrslubeidni = open('skyrslubeidni', 'w') for s in sessions: try: with open(str(s), 'r') as f: for line in f: l = line.split(';') if l[3] == 'b': skyrslubeidni.write(l[1] + ';' + l[2] + '\n') except: pass skyrslubeidni.close()
from lib2to3.pytree import Base import os import sys import shutil from glob import glob from pathlib import Path from tempfile import mkdtemp from collections import OrderedDict import numpy as np import pandas as pd from gsw import z_from_p, p_from_z from gutils import ( generate_stream, get_decimal_degrees, ...
from __future__ import absolute_import, unicode_literals import collections _single_subplot_types = {"scene", "geo", "polar", "ternary", "mapbox"} _subplot_types = set.union(_single_subplot_types, {"xy", "domain"}) _subplot_prop_named_subplot = {"polar", "ternary", "mapbox"} SubplotXY = collections.namedtuple("SubplotX...
"""Import the style modules.""" from .github import GithubStyle from .github2014 import Github2014Style from .readthedocs import ReadthedocsStyle from .tomorrowmorning import TomorrowmorningStyle from .tomorrownighteightiesstormy import TomorrownighteightiesstormyStyle __all__ = ( "GithubStyle", "Github2014Styl...
import codecs def dex_special_handler(err): ''' handles DEX files' special modified UTF-8 when the default utf-8 decoder can't. https://source.android.com/devices/tech/dalvik/dex-format.html''' if type(err) is not UnicodeDecodeError: raise err def _read_one(bytes): b = bytes[0] if (b & 0xc0) != 0xc0:...
from django.contrib.syndication.feeds import Feed from blogserver.apps.blog.models import Post,Category# Category class LatestPosts(Feed): title = "Latest Posts" link = "" description = "The Latest posts from the blog." def items(self): return Post.live.order_by('-date_published') [:10] class Ca...
import os.path import sys import codecs import numpy as np import networkx as nx import matplotlib.pyplot as plt from youtubeAPICrawler.database import * class ThinDiGraph(nx.DiGraph): all_edge_dict = {'weight': 1} def single_edge_dict(self): return self.all_edge_dict edge_attr_dict_factory = single...
""" WSGI config for zhangDjango 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.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTIN...
import numpy as np import pandas as pd import graphviz from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn import tree balance_data = pd.read_csv( 'https://archive.ics.uci.edu/ml/machine-learning-databases/balan...
class NodeListLockedException(Exception): pass class ExitMessage(object): pass
''' Retrieve Youtube video *information* ''' import requests import elasticsearch import json import logging from requests import ConnectTimeout, ConnectionError import httplib2 import os import datetime from apiclient import discovery from oauth2client import client from oauth2client.client import Credentials logger =...
from .datasource import * # noqa from .report import * # noqa from .table import * # noqa
from sklearn import datasets import pandas as pd from sklearn.cluster import KMeans iris = datasets.load_iris() x, y = iris.data, iris.target kmean = KMeans(n_clusters=3) kmodel = kmean.fit(x) print(y) print(kmodel.labels_) print(kmodel.cluster_centers_) print(pd.crosstab(y, kmodel.labels_))
''' 描述:首先有一个有序序列,插入一个元素,结果保证依然是一个有序序列 怎么找插入位置:将新插入的元素依次从右到左和序列中的元素比较, 找到第一个比它小或者它已经是第一个元素(元素比它大,交换) ''' l = [4,1,34,9,26,13,10,7,4] for i in range(len(l)): for j in range(i+1,len(l)): if l[i] > l[j]: l[i],l[j] = l[j],l[i] print(str(l)) print("result: " + str(l)) l = [4,1,9,13,34,26,10,7,4] f...
def square_of_list(some_list, num): return(some_list, num) a = [1, 2, 3, 10, 20] num = 2 b = [10, 50, 200, 1] k = 3 p = 10 if square_of_list(a, num) == 9: print('success') else: print('fail') if square_of_list(b, k) == 9: print('success') else: print('fail') if square_of_list(a, num) == 0: pr...
from __future__ import absolute_import, unicode_literals from base import GAETestCase from gaepermission import middleware from gaepermission.model import MainUser from mock import Mock, patch from mommygae import mommy class LoggedUserTests(GAETestCase): @patch('gaepermission.middleware.facade', ) def test_no_...
from __future__ import unicode_literals import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
""" This file contains custom exception classes used for differentiating expected and unexpected cryptographic exceptions. """ class PasswordHashComparisonError (Exception): pass class SignatureVerificationFailedError (Exception): pass class SymmetricEncryptionError (Exception): pass class AsymmetricEncryptionError (Ex...
import numpy as np class ArrayWrapper(object): def __init__(self, array_like): if type(array_like) is not np.array: self._array = np.array(array_like) else: self._array = array_like def __get__(self): return self def __getitem__(self, key): return self...
import os import sys import json import datetime import argparse import shutil import xml.sax class OpcorpContentHandler(xml.sax.ContentHandler): def __init__(self, out_path, encoding, out_format): super().__init__() self.out_path = out_path self.out_format = out_format self.encoding...
import sys from time import sleep import RPi.GPIO as io io.setmode(io.BCM) io.setup(23, io.IN, pull_up_down=io.PUD_UP) print("Checking IR Sensor") while True: try: if io.input(23) == 1: print("IR Detected") sleep(0.1) elif io.input(23) == 0: print("IR Not Detected...
from spidergraphs.models import Institution, Program, ProgramOutcome, Course, CourseOutcome, CourseToProgram, UserProfile from django.contrib import admin from django.forms import TextInput, Textarea, ModelForm from django.db import models from django import forms from django.contrib.auth.admin import UserAdmin from dj...
__revision__ = "test/CacheDir/SideEffect.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Test that use of SideEffect() doesn't interfere with CacheDir. """ import TestSCons test = TestSCons.TestSCons() test.subdir('cache', 'work') cache = test.workpath('cache') test.write(['work', 'SConstruct'], """\ d...
from setuptools import setup setup( name='bndr', packages=['bndr'], install_requires=['pillow', 'six'], entry_points={ 'console_scripts': ['bndrimg = bndr.bndrimg:main', 'bndtxt = bndr.bndrtxt:main'] }, version='1.0.1', description='A library + command lin...
import asyncio import discord import json import numpy as np import PIL from helpers import * from os import path from PIL import Image from wordcloud import WordCloud, ImageColorGenerator client = discord.Client(max_messages=20000) @client.event async def on_ready(): print('Logged in as ' + client.user.name + ', I...
""" Runs import for both new & old spreadsheets formats and csv files """ import csv import xlrd def run_spreadsheet_import(sheet_name, dataset, db): """ Reads excel spreadsheet and inserts data to the database instance :param sheet_name: :param dataset_path: :param db: :return: """ try:...
from tables_B1 import a, b, c, k, u, g, q, f, s, w from tables_B2 import M, E, K, G, Q, F, S, W from tables_B3 import E_star, U, Kij, G_star import numpy as np from scipy.optimize import fsolve from scipy.constants import R print('Please Enter the absolute Temperature [K], absolute pressure P [MPa] and the mole fractio...
from __future__ import division import re import tamil class SummaryTool(object): # Naive method for splitting a text into sentences def split_content_to_sentences(self, content): content = content.replace("\n", ". ") return content.split(". ") # Naive method for splitting a text into paragr...
from flask import Flask, request, render_template, url_for from subprocess import run, TimeoutExpired, PIPE from base64 import b64encode app = Flask(__name__) MENU = [ ('Basic shapes', [ ('Cube', 'examples/basic/cube.css'), ('Cylinder', 'examples/basic/cylinder.css'), ('Cone', 'examples/basi...
def next_code(current_code): return (current_code * 252533) % 33554393 max_x = 1 max_y = 1 code = 20151125 target_x = 2981 target_y = 3075 target_found = False while not target_found: y = 1 x = max_x + 1 while x > 0: max_x = max(max_x, x) code = next_code(code) if x == target_x a...
import math import re import sys import apx START_SECTION=0 NODE_SECTION=1 TYPE_SECTION=2 PROVIDE_SECTION=3 REQUIRE_SECTION=4 _p0=re.compile(r'([\+\-A-Z]+)') _p1=re.compile(r'([^:]*)') _p2=re.compile(r'#(.*)') def strip_comment(apx_text): return re.sub(_p2, '', apx_text) def apx_split_line(s): #remove comment se...
from anormbookmarker.test.test_enviroment import * with self_contained_session(CONFIG.database_timestamp) as session: BASE.metadata.create_all(session.bind) a = Word.construct(session=session, word='a') session.commit() aa = Word.construct(session=session, word='aa') session.commit() db_result = [('...
import functools from typing import Any, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport im...
"""RAML (REST API Markup Language) enhanced loader.""" __all__ = 'Loader'.split() import dataloader class Loader(dataloader.Loader): default_markup = 'raml' name = 'api spec' def postprocess(self, spec, name=None, uri=None, params=None): spec['id'] = '{title} {version}'.format(**spec).lower().replac...
""" Defines views. """ import calendar from flask import render_template, abort from presence_analyzer.main import app from presence_analyzer import utils from jinja2 import TemplateNotFound import logging log = logging.getLogger(__name__) # pylint: disable-msg=C0103 @app.route('/') def mainpage(): """ Redirec...
""" SQLpie License (MIT License) Copyright (c) 2011-2016 André Lessa, http://sqlpie.com See LICENSE file. """ import json import sqlpie class HealthTests(object): # # Health Tests # def test_ping(self): response = self.app.get('/ping') assert 'pong' in response.data, "Actual Response : %...
"""Diffusion maps module. This module implements the diffusion maps method for dimensionality reduction, as introduced in: Coifman, R. R., & Lafon, S. (2006). Diffusion maps. Applied and Computational Harmonic Analysis, 21(1), 5–30. DOI:10.1016/j.acha.2006.04.006 """ __all__ = ['BaseDiffusionMaps', 'SparseDiffusionMaps...
import requests from tc import Test import re from bs4 import BeautifulSoup regex = r'charset=([a-zA-Z0-9-]+)?' pattern = re.compile(regex, re.IGNORECASE) @Test def test(): response = requests.get('https://github.com/timeline.json') r = response # for parame in response.__dict__: # print # p...
""" A C brace style checker designed for the "EPITECH norm". """ import argparse import os import re import sys COPYRIGHT = """ Copyright © 2016 Antoine Motet <antoine.motet@epitech.eu> This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Versio...
def mdc(a,b): if b == 0: return a return mdc(b, a % b) def mmc(a,b): return abs(a*b) / mdc(a,b) print("MMC 10 e 5 --> %d" % mmc(10,5)) print("MMC 32 e 24 --> %d" % mmc(32,24)) print("MMC 5 e 3 --> %d" % mmc(5,3))
from david.core.article.admin import ArticleAdmin from david.ext.admin import _ from .model import News, Charity class NewsAdmin(ArticleAdmin): pass views = [ (NewsAdmin(News, name=_('News')), 20), (NewsAdmin(Charity, name=_('Charity')), 20) ]