content
stringlengths
5
1.05M
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: conn_cmfe.py # # Defect ID: '6616 # # Programmer: Hank Childs # Date: August 30, 2005 # # Modifications: # # Hank Childs, Tue Sep 20 13:15:11 PDT 2005 # Test for non-existent databases, e...
import sqlite3 from pathlib import Path import os import os.path """ Operations.py BSD 2-Clause License Copyright (c) 2020, Scott Little All rights reserved. This file is the basic Python interface to the SQL database. """ class Dotfiles(): def __init__(self): self.db = sqlite3.connect(os.path.expandu...
import sys import fscc import msvcrt def init(p): print('Restoring to default settings.') p.memory_cap.input = 1000000; p.memory_cap.output = 1000000; p.rx_multiple = False; p.append_status = False; p.append_timestamp = False; p.tx_modifiers = fscc.XF; p.ignore_timeout = False; ...
import sys import cv2 import pandas as pd import numpy as np print (len(sys.argv)) if len(sys.argv) != 2: print (sys.argv[0] + " expects one csv-file as its argument.") sys.exit() recording = pd.read_csv(sys.argv[1], header=None).values for i in range(0,recording.shape[0]): canvas = np.zeros((256,256,3),...
def limitPos(servoPosition): """Prevent servo position from exceeding limited range Args: servoPosition (int): Servo angle position in degrees Returns: (int): Servo position in degrees """ if servoPosition > 180: servoPosition = 180 return servoPosition def FollowTarge...
import os import sqlite3 from pathlib import Path from types import SimpleNamespace from typing import Union from alembic.config import Config from configargparse import Namespace PROJECT_PATH = Path(__file__).parent.resolve() def get_all_accounts(filename="accounts.db"): with sqlite3.connect(filename) as conn:...
# -*- coding: utf-8 -*- import tornado.web import tornado.gen from .base import BaseHandler class WebAuthHandler(BaseHandler): def get_current_user(self): return self.get_secure_cookie('username') class LoginHandler(WebAuthHandler): def get(self): if self.get_current_user(): se...
ELIGIBILITY_TRANSACTION_CODE = '270' SUPPORTED_TRANSACTION_CODES = [ELIGIBILITY_TRANSACTION_CODE] class UnsupportedTransactionException(Exception): """ Indicates that a X12 Transaction Type is not currently supported """ pass class InvalidControlSegment(Exception): """ Raised when a X12 mess...
import json import csv with open('./train-v2.0.json', "r") as reader: input_data = json.load(reader)["data"] gt = {} for entry in input_data: for paragraph in entry["paragraphs"]: for qa in paragraph["qas"]: qas_id = qa["id"] answerable = qa["is_impossible"] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import random import utils as utils # 冒泡排序法 def bubble_sort(nums): swapped = True while swapped: swapped = False for i in range(len(nums)-1): if nums[i] > nums[i+1]: # 交换元素 ...
import warnings from tortoise.models import Model from tortoise import fields, Tortoise from enum import IntEnum from Util import Configuration class LoggedMessage(Model): messageid = fields.BigIntField(pk=True, generated=False) content = fields.CharField(max_length=4000, collation="utf8mb4_general_ci", null=...
import logging from botocore.exceptions import ClientError logger = logging.getLogger(__name__) def start_job( job_name, media_uri, media_format, language_code, transcribe_client, vocabulary_name=None): """ Starts a transcription job. This function returns as soon as the job is started. To...
def isascii(s): return len(s) == len(s.encode())
import xml.etree.ElementTree as ET from sys import argv, exit if len(argv) != 4: print('usage: {} <xml1> <xml2> <output>'.format(argv[0])) exit(1) with open(argv[1], 'rb') as f1, open(argv[2], 'rb') as f2, open(argv[3], 'wb') as f3: tree = list(map(ET.parse, (f1, f2))) root = list(map(lambda tree: tre...
# flake8: noqa from zarr.codecs import * from zarr.convenience import (consolidate_metadata, copy, copy_all, copy_store, load, open, open_consolidated, save, save_array, save_group, tree) from zarr.core import Array from zarr.creation import (array, create, em...
import sublime import sublime_plugin import time import datetime import re from functools import partial status = { 'idle': 'doing nothing', 'tagging': 'tagging...', 'pause': 'paused...', 'playing': 'playing...', 'done': 'done', } settings = None def log(line): if settings and settings.get('de...
from tkinter import * from tkinter import messagebox from os import system root = Tk() root.title("AminoRep Manager") root.geometry("1366x760") root.config(background="gray17") def repFarmCommand(): messagebox.showinfo("Done!", "Script is started, check terminal!") system("python main.py") pri...
import math import os import random import re import sys def median(arr,n): arr.sort() if n%2==1: median = arr[(n//2)] if n%2==0: median = (arr[n//2 -1]+arr[(n//2)])/2 return int(median) def quartile(arr, n): quartiles = [] if n%2==1: q2, p2 = median(arr, n) ...
import word2vec import sys ''' Usage: python get_vocab.py /path/to/vocab.bin ''' w2v_file = sys.argv[1] model = word2vec.load(w2v_file) vocab = model.vocab print ("Writing to files/vocab.txt...") f = open('files/vocab.txt','w') f.write("\n".join(vocab)) f.close()
test = { 'name': '', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> a [1, 8, 7, 20, 13, 32, 19, 44, 25, 56, 31, 68, 37, 43, 49, 55, 61, 67, 73] """, 'hidden': False, 'locked': False } ], 'scored': True, ...
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import request, redirect, url_for, render_template, Blueprint import base64 import json import glob import time from uuid import uuid4 import random from PIL import Image import os try: from StringIO import StringIO decode = unicode.decode b64enc = lamb...
# Copyright 2019 Erik Kalkoken # # Licensed under MIT license. See attached file for details # # This package contains the implementation of the command line interface # for Channelexport # import argparse import os from dateutil import parser import pytz from babel import Locale, UnknownLocaleError from . import __...
# Copyright (c) ZenML GmbH 2022. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# *-* coding: utf-8 *-* import argparse import csv import matplotlib.pyplot as plt import numpy as np import nltk import pandas as pd import random import re import sklearn def get_jaccard_coefficient(s1, s2): """returns float jaccard coefficient jacc_coeff with 0 <= jacc_coeff <= 1 """ intersection = s1.i...
from pyaccessories.TimeLog import Timer import os from RedmineAPI.RedmineAPI import RedmineInterface from pyaccessories.SaveLoad import SaveLoad import base64 # TODO documentation class Run(object): def main(self, force): if self.first_run == 'yes': choice = 'y' if force: ...
from py4web import action, request, abort, redirect, URL from yatl.helpers import A from .common import db, session, T, cache, auth, logger, authenticated, unauthenticated from py4web_weasy import WeasyTemplate import datetime @action("invoice") @action.uses(WeasyTemplate("invoice.html")) def invoice(): return...
import numpy as np # a = np.arange(3) # print(a) b = np.arange(6,12).reshape(2,3) it = np.nditer(b, flags=['multi_index']) for x in it: print(f'{x}, {it.multi_index[1]}')
from jsonschema import Draft7Validator, draft7_format_checker from .data import get_extra_functions, get_packages, get_services standard_pattern = r"^([A-Za-z0-9\u00C0-\u00FF][A-Za-z0-9\u00C0-\u00FF\'\-\.\,\#]+([\ A-Za-z0-9\u00C0-\u00FF][A-Za-z0-9\u00C0-\u00FF\'\-\.\,\#]+)*)?$" standard_pattern_no_number = r"^[A-Za-...
import random import string from datetime import datetime, date def random_datetime(): year = random.randint(1970, 2017) month = random.randint(1, 12) day = random.randint(1, 28) return datetime(year, month, day) def generate_row(entity_description): properties = entity_description['column_map'...
from django.db import models from basis.models import BasisModel class Person(BasisModel): name = models.CharField(max_length=100)
# ==== NARRATIVES, MAIN ==== # import sys import time import hundMov_bb_validators def save_progress(): print("Would you like to save?") def standard_question(list_): get_first_letter = lambda w: w[0] get_idx = lambda l, s: l.index(s) + 1 letters = [get_first_letter(l) for l in list_] indexes...
# # Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. # from builtins import str from pysandesh.gen_py.sandesh.ttypes import SandeshLevel from vnc_api.gen.resource_common import FloatingIp from vnc_cfg_api_server.context import get_context from vnc_cfg_api_server.resources._resource_base import Resource...
"""Default client responses.""" from copy import copy from looseserver.client.response import ClientResponse from looseserver.common.response import ResponseFactory from looseserver.default.common.constants import ResponseType from looseserver.default.common.configuration import ResponseFactoryPreparator class Fixe...
from gym.envs.registration import register register( id='1010-v0', entry_point='gym_1010.envs:TenTenEnv', timestep_limit=1000, )
import datetime class Count(): def __init__(self): self.stChangeCnt = 2 self.lastState = None self.stateContinueCnt = 0 self.stateChangeContinueCnt = 0 self.stateTrueSumSec = 0 self.stateFalseSumSec = 0 self.lastTime = datetime.datetime.now() def setSta...
from eventsourcing.application.simple import ApplicationWithConcreteInfrastructure from eventsourcing.infrastructure.sqlalchemy.factory import SQLAlchemyInfrastructureFactory from eventsourcing.infrastructure.sqlalchemy.records import EntitySnapshotRecord, StoredEventRecord class SQLAlchemyApplication(ApplicationWith...
#!/usr/bin/env python # $Id$ """many solutions""" import puzzler from puzzler.puzzles.quasitritwigs import QuasiTritwigsTrefoil3 puzzler.run(QuasiTritwigsTrefoil3)
import cv2 import os import xml.etree.ElementTree as ET import math import glob def slice(image, xml, size=(2, 2), path='', prefix=''): height, width = image.shape[:2] wSize = int(math.ceil(float(height) / size[0])) for r in range(0, height, wSize): window = image[r:r+wSize] ...
TEMPLATE = """ # Class Index {% for letter, children in dictionary.items() %} ## {{letter}} {% for node in children -%} * [**{{node.name_short}}**]({{node.url}}) {% if node.parent.is_language -%} ([**{{node.parent.name_long}}**]({{node.parent.url}})) {% endif -%} {% endfor %} {% endfor %} """
# # Copyright 2015 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
#!/usr/bin/env python import sys import numpy as np import rospy import moveit_commander import math import tf import geometry_msgs.msg from std_msgs.msg import String from geometry_msgs.msg import WrenchStamped from geometry_msgs.msg import PoseStamped from std_msgs.msg import Float32 from std_msgs.msg import Float...
import paho.mqtt.client as mqtt def on_connect(client, userdata, rc): print "Connected with result code " + str(rc) client.subscribe("ais/recognize/result/#") client.publish("ais/recognize/voice/mock-speaker", voice_bytes) def on_message(client, userdata, msg): print msg.topic + " " + str(msg.payload)...
#Bot checking for page updates on Palace Skate shop server # # ___ ___ __ ___ _________ # / _ \/ _ | / / / _ |/ ___/ __/ # / ___/ __ |/ /__/ __ / /__/ _/ # /_/ /_/ |_/____/_/ |_\___/___/ # # # Developed by Paul92S # Date 14/11/16 # Version 0.1 # Import requests (to download the page) import ...
import json from unittest.mock import MagicMock, call import falcon.testing import hug import pytest import contact_list.app @pytest.fixture def mock_redis(): return MagicMock() @pytest.fixture def test_client(mock_redis): hug_api = contact_list.app.create_api(mock_redis) return falcon.testing.TestCli...
#!/usr/bin/env python # # Copyright (c) 2019, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # - Redistributions of source code must retain the above copyright notice, # ...
import glob import json import logging from os.path import basename from pathlib import Path playlist_dir = Path() def makePlaylistsInMusicFolder(music_dir): for playlist in glob.glob(str(music_dir / "*")): name = basename(playlist) genres = [name] directories = [playlist] createP...
__all__ = [ 'NameClashError', 'MergeTeamError', 'DuplicateSubmissionError', 'TooEarlySubmissionError', 'MissingExtensionError', 'MissingSubmissionFileError', ] class NameClashError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr...
from CTFd.utils import set_config from ..models import WhaleRedirectTemplate, db def setup_default_configs(): for key, val in { 'setup': 'true', 'docker_api_url': 'unix:///var/run/docker.sock', 'docker_credentials': '', 'docker_dns': '127.0.0.1', 'docker_max_container_coun...
import typer import subprocess app = typer.Typer() @app.command(help="OS rebuild and switch configuration") def switch(): subprocess.run("sudo nixos-rebuild switch --flake path:.#define7") link = subprocess.run( "nix build './#darwinConfigurations.LF2107010038.system' --no-out-link" ) switch...
""" author: @nimrobotics description: process and prepare data for EC and FC analysis """ from operator import le import numpy as np import scipy.io import scipy.signal def load_data(file): """ load data from nirs file :param file: .nirs file :return: data """ nirs = scipy.io.loadmat(file) ...
import argparse import os import sys import torch from collections import OrderedDict from data.segmentation_dataset import SegmentationDataset from util.visualizer import Visualizer from util import html from models.joint_inference_model import JointInference import util.util as util from skimage import io import nu...
# !/usr/bin/env python # -*- coding: utf8 -*- import sys import numpy as np import scipy.sparse as sp import torch import torch.nn as nn import torch.nn.functional as F from utils import glorot_init from modules import GCN, AvgReadout, Discriminator from collections import Counter from evaluation import * print(torch....
from typing import Optional, List, Tuple from enum import Enum from pathlib import Path from wasabi import Printer, diff_strings from thinc.api import Config import srsly import re from jinja2 import Template from .. import util from ..language import DEFAULT_CONFIG_PRETRAIN_PATH from ..schemas import RecommendationSc...
import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) import re import pandas as pd import camelot import pdfminer from pdfminer.high_level import extract_pages try: from local_extractor.utils import common_utils except ImportError: import sys, os, pathlib path = pathlib.Path(__file__).absolute(...
# Copyright 2020 John Reese # Licensed under the MIT License import asyncio import logging from concurrent.futures import ThreadPoolExecutor from functools import partial from typing import Optional import aiosqlite from aioseinfeld import Seinfeld from discord import Message from legion.unit import Unit, command L...
# ---------------------------------------------------------------------------- # Author: Nicolas P. Rougier # License: BSD # ---------------------------------------------------------------------------- import numpy as np import matplotlib.pyplot as plt X = np.linspace(0.1, 10*np.pi, 10000) Y = np.sin(X) # fig = plt....
# 车次 TRAIN="" #字母为大写 # 出发时间 dptHm = "" # 出发站 FROMSTATION= "上海" # 到达站 TOSTATION = "北京西" # 出发日期 STARTTIME= "20181123" # 20181121 # 座位类型 SEAT= "硬座" # 硬座 硬卧 软卧 无座 二等座 一等座 商务座 # 用户姓名 USER_NAME = "陈二明" # 身份证号码 USER_ID = "2xxxxxxxxxxxxxxxxx" # 联系人姓名 TEL_NAME = "陈二明" # 联系电话 TEL_NUMBER = "180xxxxxxxx"
#!/usr/bin/env python3 """ Simple example/demo of the unlinkable DP-3T design This demo simulates some interactions between two phones, represented by the contact tracing modules, and then runs contact tracing. """ __copyright__ = """ Copyright 2020 EPFL Licensed under the Apache License, Version 2.0 (the "...
'''Collection of classes and functions for loading, interpolation and processing of atomic data. Refer also to the adas_files.py script. ''' import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import RectBivariateSpline, interp1d from matplotlib import cm import os, sys, copy import scipy.ndimag...
from vectorformats.Feature import Feature from vectorformats.Formats.Format import Format from Cheetah.Template import Template class HTML (Format): """Uses Cheetah to format a list of features.""" template_file = "template/default.html" """Default template file to use.""" def encode(self, result, *...
import logging import datetime from util.ioparser import mkdir, parent class Logger: def __init__(self): self.lgs = [] def add_console_logger(self, name, filter=logging.DEBUG): lg = logging.getLogger(name) lg.setLevel(filter) lg = self._clean_handler(lg) lg = self._add...
#!/usr/bin/python import os import pandas as pd import util class File: """ :return: """ def read_file_data(self, file_path, sep) -> object: """ :return: :rtype: object :param sep: :param file_path: :return: """ with open(file_path, '...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Test a Fast R-CNN network on an imdb (image database).""" from fast...
import sys sys.path.append('../clivia')
import os import random import pytest import tempfile import pandas as pd from pycytominer.cyto_utils.load import infer_delim, load_profiles, load_platemap random.seed(123) # Get temporary directory tmpdir = tempfile.gettempdir() # Lauch a sqlite connection output_data_file = os.path.join(tmpdir, "test_data.csv") ou...
from .evaluator import * from .resa_trainer import * from .registry import build_evaluator
# -*- coding: utf-8 -*- """ Created on Wed Sep 5 14:45:43 2018 @author: dani """ import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import os from matplotlib import colors as mcolors indir = "./" outdir = 'ViolinPlots_Vert/' if not os.path.exists(indir+outdir): os.makedirs(indir+outdir...
import pytest import pydsm import numpy as np import pandas as pd from pydsm.functions import tsmath @pytest.fixture def linear_timeseries(): ''' A simple increasing time series to use for averaging functions ``` 01JAN2000 0100 - 0 01JAN2000 0200 - 1 .... 01JAN2000 2200 - 21 01JAN2000 2...
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-03-17 23:41 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields class Migration(migrations.Migration): initial = True de...
# -*- coding: utf-8 -*- """ Created on Tue Sep 2 20:33:55 2014 @author: isaac """ import numpy as np from scipy.interpolate import interp1d from scipy.optimize import newton def calc_epsilon(m, L, S): """Non-dimensional gliding parameter, epsilon. Parameters ---------- m : float mass in kg...
import pyexasol import _config as config C = pyexasol.connect(dsn=config.dsn, user=config.user, password=config.password, schema=config.schema) C.execute("ALTER SESSION SET QUERY_CACHE = 'OFF'") st = C.execute("SELECT * FROM {table_name!i}", {'table_name': config.table_name}) st.fetchall()
from collections import defaultdict, OrderedDict from functools import partial class FeatureHooks: def __init__(self, hooks, named_modules): # setup feature hooks modules = {k: v for k, v in named_modules} for h in hooks: hook_name = h['name'] m = modules[hook_name...
import numpy as np from scipy.ndimage.morphology import binary_dilation from skimage.measure import label as label_cc # avoid namespace conflict from skimage.segmentation import find_boundaries from .data_affinity import make_2d_nhood, seg_to_aff # reduce the labeling def getSegType(mid): m_type = np.uint64 ...
from typing import List, Union from sardine.exceptions.lang.lang_exception import SardineLangException class UnexpectedTokenFound(SardineLangException): def __init__(self, unexpected_token_type: str, expected_types: Union[str, List[str]]): msg = f"Unexpected token type {unexpected_token_type}." ...
# -*- coding: utf-8 -*- """ This code is used to run the lumpedmodel - you have to make the root directory to the examples folder to enable the code from reading input files - Example catchment needs to be calibrated """ #%library #import numpy as np import pandas as pd # Hapi modules import Hapi.hbvlumped as ...
error_categories = ['USER', 'HARDWARE', 'LOGIC', 'FRAMEWORK'] error_extents = ['LOCAL', 'GLOBAL'] error_levels = ['WARN', 'ERROR', 'FATAL'] dcdc_control_commands = ['MODE', 'VOLTAGE', 'CURRENT'] dcdc_modes = ['WAIT', 'VOLTAGE_REFERENCE', 'DISCHARGE', 'CHARGE'] dcdc_mode_2_code = { 'WAIT' : '0x0000', 'VOLTAGE_REFERE...
class Solution: def compareVersion(self, version1: str, version2: str) -> int: i = 0 j = 0 while i < len(version1) and j < len(version2): i_r = i j_r = j while i_r < len(version1) and version1[i_r] != '.': i_r+=1 while ...
import os.path, time from twisted.web2 import server, http, resource, channel from twisted.web2 import static, http_headers, responsecode class Child(resource.Resource): creation_time = time.time() text = 'Yo Ho Ho and a bottle of rum.' content_type = http_headers.MimeType('text', 'plain') def render(self, ct...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: José Sánchez-Gallego (gallegoj@uw.edu) # @Date: 2020-03-23 # @Filename: CatWISE_load_helper.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) import sys import astropy.table from astropy.io import ascii def main(): file_ = s...
# -*- coding: utf-8 -*- """ Created on Wed Feb 24 08:32:39 2016 set up all user specific information @author: xf05id1 """ import os #import scanoutput import time import shutil #user experiment will be put into the Start Document for every scan proposal_num = None proposal_title = None PI_lastname = None saf_num...
from django.contrib import admin from .models import Product, Catogory # Register your models here. admin.site.register(Product) admin.site.register(Catogory)
from django.apps import AppConfig class Newapp1Config(AppConfig): name = 'newapp1'
#!/usr/bin/env python import sys import os import xls2cwl_job import argparse parser = argparse.ArgumentParser(description='Generates a XLSX template sheet from a CWL document. ' + 'The template sheet can be used with xls2cwl-job.py') parser.add_argument('-c', '--cwl', help='Path to a CWL doc...
#!/usr/bin/env python2 # pylint: disable=missing-docstring,invalid-name,import-error """Hierarchical clustering of samples.""" from __future__ import absolute_import, division, print_function, unicode_literals import argparse import json import csv import gzip import numpy as np from scipy.stats import spearmanr from...
from datetime import datetime from django.shortcuts import render import requests import environ env = environ.Env() environ.Env.read_env() stock_api_key = env('STOCK_API_KEY') def index(request): context = {} context.update(fetch_news(request)) context.update(fetch_stocks(request)) context.update(f...
""" Tests related to the pip interfaces into the pypi interface """ :
from models.errors import InvalidTypeError class Link(): """ Class defining the Link model """ __href = None # string __rel = None # string def __init__(self, href=None, rel=None): """ Initialize a Link object :param href: string containing the url :pa...
# -*- coding: utf-8 -*- import base64 import csv import json import os import re import requests import sys import urllib.parse as urlparse from io import StringIO from configparser import ConfigParser requests.packages.urllib3.disable_warnings() class Config(object): """ Find the config settings which inc...
""" at.py - a Python interface to the unix "at" command """ import platform import re import subprocess from subprocess import PIPE, STDOUT from dateutil.parser import parse as parse_datetime from .utils import has_timezone, apply_local_timezone, now_local_timezone, strip_seconds AT_DATETIME_FORMAT = '%H:%M %m%d%Y...
from django import forms from .models import Product #DjangoFOrms is the same as forms but the view will behave different this one seems to be the recomended class ProductForm(forms.ModelForm): title = forms.CharField(label='Titulo', initial="", widget=forms.TextInput(attrs={"placehold...
import numpy as np from itertools import combinations from functools import reduce def _get_far_point(points, distances, selected_points): max_distances_sum = -1 far_point = -1 for point in points: if point in selected_points: continue distances_sum = reduce(lambda x, y: x + d...
from .RegexBase import RegexBase class Comment(RegexBase): def get(self) -> str: return '(?#{})'.format(self.rgx)
# -*- coding: utf-8 -*- """Monoalphabatic cipher.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1-L50uNaC7UWbbkgk1uQ_MEFz3tEfQgg9 """ Key = { "a":"z", 'b':'y', 'c':'x', 'd':'w', 'e':'v', 'f':'u', 'g':'t', 'h':'s', 'i':'r', 'j':'q',...
import mysql.connector import re from io import StringIO class DB: def __init__(self, connString): dic = dict() for m in re.findall(r'[ \t]*([a-zA-Z0-9-]*)[ \t]*=[ \t]*\'([a-zA-Z0-9-+*\/=?!@#$%&()_{}\[\]<>:;.~^`" ]*)\'[ \t]*',connString): dic[m[0]] = m[1] self.conn = mysql.con...
import serial import time ser = serial.Serial('/dev/ttyACM0',9600) #while True: ser.write("f".encode('utf-8')) time.sleep(2) ser.write("b".encode('utf-8')) time.sleep(2) ser.write("r".encode('utf-8')) time.sleep(2) ser.write("l".encode('utf-8')) time.sleep(2) ser.write("s".encode('utf-8')) time.sleep(2)
from medacy.model import Model model = Model.load_external('medacy_model_clinical_notes') def tagMedical(text): annotation = model.predict(text) return formatResponse(annotation) def formatResponse(annotation): entities_dict = annotation.get_entity_annotations(return_dictionary=True) entities = [{'te...
#Código criado por: Iury Chagas da Silva Caetano import numpy as np #importando bibliteca numpy para o objeto np #variaveis com inicialização em 0 para retirar lixo de memoria identidade = 0 simetrica = 0 antisimetrica = 0 nula = 0 #solicitando ao usuario os dados necessarios print("##### Este programa identifica a ma...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-09-07 00:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sagelist', '0005_auto_20160906_2220'), ] operations = [ migrations.AlterFiel...
# -*- coding: utf-8 -*- """ Created on Wed Oct 10 16:37:52 2012 @author: VHOEYS """ import random import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from .sobol_lib import i4_sobol from .distributions import randomUniform, randomTriangular, randomTrapezoidal, \ rando...
from .. import ast from .. ast.expressions import expression as e from .. properties import shape, sign from nose.tools import eq_ def test_default_data(): """ Test that default arguments are set. """ data = ast.ProgramData() yield eq_, data.dimensions, set() yield eq_, data.parameters, {} yie...