content
stringlengths
5
1.05M
import datetime def print_header(): print('--------------------') print(' Due Date APP') print('--------------------') print() def get_lmp_from_patient(): print("When was the patient's last normal menstrual cycle? ") date_str = input('Format: [dd/mm/yyyy]? ') # Desired format '05/26/2...
from torchvision import models class Model: def __init__(self, arch): self.network = eval('models.{}(pretrained=True)'.format(arch)) self.input_size = self.network.classifier[0].in_features # Freeze parameters so we don't backprop through them for param in self.network.parameters():...
import argparse import nltk def argparser(): p = argparse.ArgumentParser() p.add_argument('-input', required=True) p.add_argument('-output', required=True) p.add_argument('-word_num', type=int, required=True, help='how many words to use. the...
# -*- coding: utf-8 -*- from config.basic import BasicSettings class Settings(BasicSettings): ES_HOSTS: list = ["localhost", ] # ES_HOSTS: list = ["es_dev", ] INFLUX_HOST = "localhost" INFLUX_PORT = 8086 INFLUX_DB = "my_db"
""" This is converted from tensorflow simple audio recognition tutorial: https://www.tensorflow.org/tutorials/audio/simple_audio """ import os import pathlib import matplotlib.pyplot as plt import numpy as np import seaborn as sns import tensorflow as tf from tensorflow.keras.layers.experimental import preprocessing...
import unittest def validBraces(string): stack = [] braces = {"(": ")", "[": "]", "{": "}"} for c in string: if c in braces.keys(): stack.append(c) else: if not stack or braces[stack.pop()] != c: return False return not len(stack) class TestE...
# pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta import operator import unittest import nose import numpy as np import pandas as pd from pandas import (Index, Series, DataFrame, Panel, isnull, notnull,date_range) from pandas.core.index import Index, MultiIndex from panda...
pi = 3.14 r = 1.1 area=pi*(r**2) print("the area of the circle is : ",area)
from app.models.book import Book from app.schemas.book import Book as SchemaBook from fastapi_sqlalchemy import db from app.utils.pagination import paginate def add_book(book: SchemaBook): model_book = Book(title=book.title, description=book.description, author_id=book.a...
from setuptools import setup, find_packages setup( name='various_utilities', version='0.1', license='MIT', # TODO: add license author="Cristian Desivo", author_email='[email protected]', packages=find_packages('src'), package_dir={'': 'src'}, url='', # TODO: add url keywords='uti...
"""Tests.""" from typing import List import pytest from bs4 import element ROOTS = ("buttons-on-top/default", "buttons-on-top/sphinx-conf") @pytest.mark.parametrize("testroot", [pytest.param(r, marks=pytest.mark.sphinx("html", testroot=r)) for r in ROOTS]) def test(carousels: List[element.Tag], testroot: str): ...
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for owners_finder.py.""" import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.pa...
text_file = "test.txt" def read_file(text_file): try: with open(text_file, "r") as handle: data = handle.read() return data except FileNotFoundError: return None def single_word(text_file): with open("test.txt", "r") as handle: data = handle.read() ...
import random import os import math import numpy as np from osgeo import gdal import scipy from scipy import stats from scipy import ndimage as ndi from pyproj import Proj, CRS # %% DEM LOADING AND CLIPPING FUNCTIONS def convert_wgs_to_utm(lon: float, lat: float): """Based on lat and lng, return best utm epsg-co...
USAGE_CONTENT = """Document and Blog Entry Manager USAGE: <command> [OPTIONS] OPTIONS: -i, -init initialize docs directory (don't delete exist file and dir). -n, -new [<OPTS>] new document set under "work" dir (create dir, md file and category file). OPTS (can a...
# newplots.py """Volume 1A: Data Visualization. Plotting file.""" from __future__ import print_function import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') # Decorator =================================================================== from matplotlib import colors, pyplot as...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
""" discovery/short_interest_api.py tests """ import unittest # from gamestonk_terminal.sentiment.reddit_api import popular_tickers class TestSentimentRedditApi(unittest.TestCase): def test_popular_tickers(self): # popular_tickers(["-s", "wallstreetbets"]) print("")
import argparse import os import matplotlib.pyplot as plt import numpy as np from multiobject import generate_multiobject_dataset from sprites import generate_dsprites, generate_binary_mnist from utils import get_date_str, show_img_grid supported_sprites = ['dsprites', 'binary_mnist'] def main(): args = parse_...
''' Tested on python3 About : Screen Shot Grabber ''' import win32gui import win32ui import win32con import win32api #handle h_desktop=win32gui.GetDesktopWindow() #display size width=win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height=win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) left_side=win...
from debexpo.tests import TestController from pylons import url from tempfile import mkdtemp from shutil import rmtree import os import os.path import pylons.test class TestIndexController(TestController): def setUp(self): self.tempdir = mkdtemp() def tearDown(self): rmtree(self.tempdir) ...
from collections import defaultdict class Solution: def arrangeWords(self, text) -> str: words = defaultdict(list) lengths = [] text = text.split(" ") for word in text: word = word.lower() words[len(word)].append(word) lengths.append(len(word)) ...
from OdsLib.PySql import PySql from OdsLib.Address import Address from OdsLib.Customer import Customer from OdsLib.Cart import Cart from OdsLib.DeliveryExecutive import DeliveryExecutive from OdsLib.Orders import Orders from OdsLib.Product import Product print("Imported ODS module")
""" ================== StripUnits Deriver ================== """ from typing import Dict, Any from vivarium.core.process import Deriver from vivarium.library.units import remove_units class StripUnits(Deriver): """StripUnits Deriver Reads values specified by the 'keys' parameter under the 'units' port, ...
__author__ = 'teemu kanstren' import json import argparse import os from influxdb import InfluxDBClient from datetime import datetime parser = argparse.ArgumentParser() parser.add_argument("-db", "--database", help="Database name", default="_internal", nargs='?') parser.add_argument("-ip", "--hostname", help="Databas...
''' Functions and classes for reading data ''' import numpy as np import tensorflow as tf import pandas as pd import collections import os from six.moves.urllib.request import urlretrieve import zipfile def load_zip_data(filename): ''' return the zip data as unicode strings :param: filename: name of file to ope...
import sys __all__ = ['mock'] PY3 = sys.version_info[0] == 3 if PY3: from unittest import mock else: import mock def str2bytes(s): if PY3: return bytes(s, encoding='utf8') else: return s
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2021-01-16 14:47:23 # @Author : Joe Gao ([email protected]) import os import json from utils import ( DIC_DataLoaders, DIC_Resolvers, ) from modules import( DIC_Funcs, DIC_Inits, DIC_Losses, DIC_Metrics, DIC_Layers, DIC_Bases, ...
from collections import deque class Solution(object): def shortestDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return -1 row, col = len(grid), len(grid[0]) dists = [[0 for _ in xrange(col)] fo...
import numpy as np import os import glob import matplotlib.pyplot as plt from numpy.fft import fft, ifft import NLS import random as rand # seed random number generator subdirs = ['Aug1Data','Aug2Data','JulyData'] # Define something that will list directories that are not hidden def listdirNH(path): return glob....
import json import pandas as pd import numpy as np import urllib.request import gzip import os import csv def download_json(): earliest_year = 2019 latest_year = 2020 file_paths = [] skipped_files = 0 for year in range(earliest_year, latest_year + 1): file_name = "nvdcve-1.1-{}.json".form...
expected_output = { 'vpn_id': { 1000: { 'vpn_id': 1000, 'encap': 'MPLS', 'esi': '0001.00ff.0102.0000.0011', 'eth_tag': 0, 'mp_resolved': True, 'mp_info': 'Remote all-active, ECMP Disable', 'pathlists': { 'e...
"""Interfaces for ClientModel and ServerModel.""" from abc import ABC, abstractmethod import numpy as np import random from baseline_constants import ACCURACY_KEY, OptimLoggingKeys, AGGR_MEAN from utils.model_utils import batch_data class Model(ABC): def __init__(self, lr, seed, max_batch_size, optimizer=None...
""" 余計な文字列や文字を検出し削除するプログラムである。 """ import re import function.Rename_func as Rename_func print("これからファイルを移動しますが、既に存在した場合 削除 しますか? yesかnoで\n") ans = input() if re.search("yes", ans) or re.search("y", ans): delete = "1" else: delete = "0" path1 = 'H:/TV(h.265)' path2 = 'D:/TV(h.265)/映画' path3 = ...
import glob, os import cv2 as cv import numpy as np import matplotlib.pyplot as plt from sklearn import svm from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA ### Reading Data ### path = "images/" imlist = glob.glob(os.path.join(path, "*.jpg")) def dataset(file_list, size=(1...
# Copyright (C) 2018-2021 # Author: Cesar Roman # Contact: [email protected] """OPC - UA Functions. The following functions allow you to interact directly with an OPC-UA server. """ from __future__ import print_function __all__ = ["callMethod"] def callMethod(connectionName, objectId, methodId, inputs): """...
""" Copyright (C) 2019 University of Massachusetts Amherst. This file is part of "expLinkage" http://github.com/iesl/expLinkage 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/l...
__all__ = ['Reply'] import time from collections import OrderedDict from tron import Misc, Parsing """ Reply is a slight misnomer -- - Reply to an existing command. Need to specify: - flag, cmd, [src], KVs - Generate non-command KVs. Need to specify: - flag, actorCid, actorMid, src, KVs """ ...
from abc import ABC, abstractmethod import collections.abc import re import struct import util # Defines classes for all tag types, with common logic contained in abstract base classes # Abstract Base Classes and Concrete classes are intertwined. I have separated them for convenience # but putting them in separate fil...
__author__ = 'yanivshalev' from hydro.connectors.mysql import MySqlConnector if __name__ == '__main__': params = { 'source_type': 'mysql', 'connection_type': 'connection_string', 'connection_string': '127.0.0.1', 'db_name': 'test', 'db_user': 'xxx', 'db_password': 'y...
import pytest import os from xonsh.commands_cache import (CommandsCache, predict_shell, SHELL_PREDICTOR_PARSER, predict_true, predict_false) from tools import skip_if_on_windows def test_commands_cache_lazy(xonsh_builtins): cc = CommandsCache() assert not cc.lazyin('xonsh') ...
import _plotly_utils.basevalidators class ShapeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name='shape', parent_name='scattercarpet.line', **kwargs ): super(ShapeValidator, self).__init__( plotly_name=plotly_name, parent_name...
from io import IncrementalNewlineDecoder from pdb import set_trace as br import numpy as np with open('input.txt') as f: input = f.readlines() input = [i.strip() for i in input] def scope(c): if c in '()': return 0 elif c in '[]': return 1 elif c in '\{\}': return 2 elif...
# # PySNMP MIB module BIANCA-BRICK-L2TP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BIANCA-BRICK-L2TP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:21:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "13/10/17 20:54" from config import CONFIG from optparse import OptionGroup from libs.core....
# -*- coding: UTF-8 -*- from nonebot import on_command, CommandSession,NoticeSession,on_notice,permission as perm from helper import getlogger,msgSendToBot,CQsessionToStr,TempMemory,argDeal,data_read,data_save from module.twitter import decode_b64,encode_b64,mintweetID from plugins.twitter import tweet_event_deal from ...
'''Module File'''
import discord from discord.ext import commands class Mod: """Useful moderation commands to keep the server under control.""" def __init__(self, bot): self.bot = bot @commands.command() @commands.guild_only() @commands.has_permissions(kick_members=True) async def kick(self, ctx, us...
# Copyright (c) 2021, PublicSpaces and Contributors # See license.txt # import frappe import unittest class TestToolToets(unittest.TestCase): pass
"""Base classes for Rattr components.""" import ast from abc import ABCMeta, abstractmethod, abstractproperty from ast import NodeTransformer, NodeVisitor # noqa: F401 from itertools import product from typing import Dict, List, Optional from rattr import error from rattr.analyser.context import Context from rattr.a...
# # Copyright (c) 2011 Daniel Truemper [email protected] # # settings.py 10-Jan-2011 # # 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 # #...
#!/usr/bin/env python3 # Ryan Hodgson - [email protected] class MyPRNG: 'Lehmer Generator' def __init__(self): self.m = 2147483647 self.a = 16807 def next_prn(self): self.seed = (self.a * self.seed) % self.m return(self.seed) def setSeed(self, rseed): self.seed = int(rseed)
import numpy as np #Taking Input in Form of list and saving in a list l=[0] n=list(map(int,input().split(' '))) l[0]=n for i in range(len(n)-1): l.append(list(map(int,input().split(' ')))) l=np.array(l) c=0 for i in range(len(n)): if (sum(l[:,i])==(len(n)-1)): c=i if (sum(l[c])==0): print("...
""" accuracy_assessment.py: contains functions to assess the accuracy of the RF classifier. The following metrics are evaluated: - Confusion matrix (CM) - Kappa statistic (Kappa) @author: Anastasiia Vynohradova """ import gdal import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix f...
# -*- coding: utf-8 -*- # Copyright 2019 Google LLC # # 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 agr...
import logging from flask import Flask import settings from routes import objects, pages, api # from secure.api import api -- not implemented yet app = Flask(__name__) # regex paths app.url_map.strict_slashes = True app.register_blueprint(pages.pages) app.register_blueprint(api.api) app.register_blueprint(objects.mo...
from bs4 import * import re, bs4 from doi_utils import * # doi 10.1088 def parse_iop(soup): is_french = False authors, affiliations = [], {} for elt in soup.find_all(class_='mb-05'): is_elt_ok = False for sub_elt in elt.children: if(isinstance(sub_elt, bs4.element.Tag)) : ...
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint from slp.modules.feedforward import FF def calc_scores(dk): def fn(q, k): return torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(dk) return fn class Attention(nn.Module): ...
# # MIT License # # Copyright (c) 2022 GT4SD team # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge,...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch.nn import functional as F import numpy as np import numpy.random as npr from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.modeling.matcher import Matcher from maskrcnn_benchmark.structures.b...
class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class MonostateSingleton(Borg): def __init__(self): Borg.__init__(self) self.name = "MySingleton" def get_name(self) -> str: return self.name def set_name(self, name: str): ...
from django.urls import path, include from . import views app_name = "pressTv" urlpatterns = [ path("", views.index.as_view(), name="index"), path("change_news_page/<str:pageNum>", views.changePage, name="change_news_page"), ]
""" It make request http. """ import logging from http_client.send_request import send_request from http_client.response import get_body class HttpRoute: """ It make request http. """ def __init__(self, host, port, method, path): """ Initialize the variables. :param host: strin...
import collections import os import sys import PIL from . import Image modules = { "pil": "PIL._imaging", "tkinter": "PIL._tkinter_finder", "freetype2": "PIL._imagingft", "littlecms2": "PIL._imagingcms", "webp": "PIL._webp", } def check_module(feature): if not (feature in modules): ...
class Foo: class Boo(): def foo(self): print "rrrrr"
#!/usr/bin/env python import sys from setuptools import setup, find_packages install_requires = ['PyYAML==3.10', 'virtualenvwrapper==4.0'] #virtualenvwrapper 4.1.1 has broken packaging if sys.version_info < (2, 7): install_requires += ['ordereddict==1.1', 'argparse==1.2.1'] setup( name='Batman', version...
# coding = utf-8 import numpy as np import cv2 def add_gasuss_noise(image, mean=0, var=0.001): ''' 添加高斯噪声 mean : 均值 var : 方差 ''' image = np.array(image/255, dtype=float) noise = np.random.normal(mean, var ** 0.5, image.shape) out = image + noise if out.min() < 0: ...
import numpy as np import pymc3 as pm import pandas as pd import arviz as az from scipy import stats from scipy.special import logsumexp from bayesian_routines import standardize import matplotlib.pyplot as plt np.random.seed(20897234) # 7H1 data = pd.read_csv('Laffer.csv', delimiter=';') rate = standardize(np.array(...
"""Package for defining custom template tags, for use in Django templates."""
#!/usr/bin/python3 # -*- coding:utf-8 -*- import http.client, urllib.parse import json import os import numpy as np import hashlib import base64 def calcFileSha256(filname): """calculate file sha256""" with open(filname, "rb") as f: sha256obj = hashlib.sha256() sha256obj.update(f.read()) ...
from CyberSource import * import os import json from importlib.machinery import SourceFileLoader config_file = os.path.join(os.getcwd(), "data", "Configuration.py") configuration = SourceFileLoader("module.name", config_file).load_module() def get_transaction_details_for_given_batch_id(): id = "12345" try: ...
import paho.mqtt.publish as publish import paho.mqtt.client as mqtt topic = "fountainStateOff" server = "168.128.36.204" publish.single( topic, payload=None, qos=0, retain=False, hostname=server, port=1883, client_id="cabbage_client", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31)
#!/usr/bin/env python # Copyright (C) 2018 Michael Pilosov # Michael Pilosov 01/21/2018 ''' The python script for building the ConsistentBayes package and subpackages. ''' try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='cbayes', version='0.3.26', ...
A_30_01_9 = {0: {'A': -0.273, 'C': 0.188, 'E': 0.612, 'D': 0.566, 'G': 0.063, 'F': 0.287, 'I': -0.054, 'H': -0.485, 'K': -0.921, 'M': -0.389, 'L': -0.073, 'N': 0.183, 'Q': 0.237, 'P': 0.557, 'S': -0.23, 'R': -0.832, 'T': 0.104, 'W': 0.296, 'V': 0.041, 'Y': 0.121}, 1: {'A': -0.287, 'C': 0.263, 'E': 0.858, 'D': 0.713, 'G...
from powerline_shell.utils import BasicSegment import os import json class Segment(BasicSegment): def add_to_powerline(self): with open('/root/.bluemix/config.json') as json_file: config = json.load(json_file) try: self.powerline.append(" g:%s " % config['ResourceGroup']['Name'], se...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from frappe import _ def get_data(): return [{ "label": _("Recruitment"), "items": [{ "type": "doctype", "name": "Job Contract", "description": _("Job Contract"), }, { "t...
from __future__ import unicode_literals from setuptools import setup, find_packages import os try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_INI = os.path.join(PROJECT_DIR, "project.ini") co...
# -*- coding: utf-8 -*- # Generated by scripts/generate_labels.py from __future__ import unicode_literals # LearningActivities READ = "wA01urpi" CREATE = "UXADWcXZ" PRACTICE = "VwRCom7G" WATCH = "UD5UGM0z" REFLECT = "3dSeJhqs" EXPLORE = "#j8L0eq3" LISTEN = "mkA1R3NU" choices = ( (READ, "Read"), (CREATE, "Cre...
import time class car(object): def __init__(self,name): print('init has been used') self.__name = name def __del__(self): print('del has been used') time.sleep(1) print('%s has been killed'%self.__name) car1 = car('bus') car2 = car1 car3 = car1 print(id(car),id(car2),id(car3)) prin...
from collections import defaultdict import logging from operator import itemgetter from numba import jit import numpy as np from shapely.geometry import LineString, MultiLineString, MultiPolygon, Polygon from shapely.ops import linemerge, unary_union from shapely.prepared import prep from .utils import build_spatial_...
# Simple demo of of the PCA9685 PWM servo/LED controller library. # This will move channel 0 from min to max position repeatedly. # Author: Tony DiCola # License: Public Domain from __future__ import division import time import paho.mqtt.client as mqtt import Adafruit_PCA9685 import serial from lightTelemetry import Li...
# Generated by Django 2.0.3 on 2018-07-02 17:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('queueapp', '0004_jenkins_project2'), ] operations = [ migrations.AddField( model_name='autofilter', name='issues_per...
from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template urlpatterns = patterns('impromptu.views', url(r'^filebrowser$', 'filebrowser', name='filebrowser'), # NEW.. url(r'^(?P<num>.+)$', 'funpage', name='impromptu_fun_detail'), url(r'^$', 'index', name='imprompt...
from subprocess import Popen, STDOUT from typing import List, Tuple import itertools onto_prefixes = ['SNOMEDCT_US','FMA','NCI'] middlefix = 'SCUI_to_keep' #onto_postfixes = ['large','mini-body','mini-disease-body','mini-pharm-neoplas-body','mini-SF-NF','mini-SN-disease','mini-SN-pharm-neoplas','mini-SN-pharm','mini-S...
import sys from tblib import pickling_support pickling_support.install() class TraceableException: """ This class stores an Exception and its traceback, allowing it to be rethrown in another process (or thread) whilst maintaining a useful stack trace """ def __init__(self, error: BaseException): if...
from .condizione_pagamento import CondizionePagamentoViewSet from .esigibilita_iva import EsigibilitaIVAViewSet from .modalita_pagamento import ModalitaPagamentoViewSet from .natura_operazione_iva import NaturaOperazioneIVAViewSet from .regime_fiscale import RegimeFiscaleViewSet __all__ = [ "CondizionePagamentoVie...
""" SiDE: Feature Learning in Signed Directed Networks Authors: Junghwan Kim([email protected]), Haekyu Park([email protected]), Ji-Eun Lee([email protected]), U Kang ([email protected]) Data Mining Lab., Seoul National University This software is free of charge under research purposes. For commerc...
import cv2 s=input("Enter The Name of the File: ") #print(s) a=int(input("Enter the Desired Breadth: ")) b=int(input("Enter the Desired Height: ")) t=input("Enter the Name of the New Resized File: ") t="Files/"+t s="Files/"+s img=cv2.imread(s,1) #cv2.imshow("Picture Box",img) #cv2.waitKey(0) resized_image=...
import logging import os from dataclasses import dataclass from typing import Any, Iterable, Mapping, Optional from reconcile.utils import gql from reconcile.utils import raw_github_api from reconcile.utils.secret_reader import SecretReader from reconcile import queries REPOS_QUERY = """ { apps_v1 { cod...
from funcy import print_durations import itertools import functools from collections import Counter # Puzzle: https://adventofcode.com/2021/day/21 def create_die(maxnum): # 100-sided die, rolls 1,2,3,...100,1,2,3... yield from enumerate(itertools.cycle(range(1, maxnum + 1)), 1) def wrap_around(field): ...
""" Base Class for using in connection to network devices Connections Method are based upon AsyncSSH and should be running in asyncio loop """ import asyncio import re import asyncssh from netdev.exceptions import TimeoutError, DisconnectError from netdev.logger import logger class BaseDevice(object): """ ...
# Generated by Selenium IDE import pytest import time import json import re import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wai...
import pytest import sqlalchemy as sa from h_matchers import Any from sqlalchemy.engine import CursorResult from lms.db import BASE, BulkAction class TestBulkAction: class TableWithBulkUpsert(BASE): __tablename__ = "test_table_with_bulk_upsert" BULK_CONFIG = BulkAction.Config( upsert...
import mock import pytest from pyetcd import EtcdResult from etcdb.eval_expr import EtcdbFunction, etcdb_count from etcdb.execute.dml.select import eval_row, prepare_columns, \ group_result_set, get_row_by_primary_key from etcdb.resultset import ColumnSet, Column, Row, ResultSet from etcdb.sqlparser.sql_tree impor...
class Solution: def removeDuplicates(self, s: str) -> str: stack = [] for i in s: if not stack or stack[-1] != i: stack.append(i) elif stack[-1] == i: stack.pop() return "".join(stack)
import unittest from collections import defaultdict import numpy as np import pandas as pd import numpy.testing as np_test from scipy.sparse import coo_matrix from dummyPy import Encoder, OneHotEncoder class TestEncoder(unittest.TestCase): def test_class(self): encoder = Encoder() self.assertEqu...
# This file is automatically generated by the rmf-codegen project. # # The Python code generator is maintained by Lab Digital. If you want to # contribute to this project then please do not edit this file directly # but send a pull request to the Lab Digital fork of rmf-codegen at # https://github.com/labd/rmf-codegen ...
import argparse import re parser = argparse.ArgumentParser() parser.add_argument("hybrid_pileup", help="pileup file for hybrid") parser.add_argument("parent_pileup", help="pileup file for parent") parser.add_argument("output", help="file to write shared SNPs to") parser.add_argument("-v", "--verbose", action="store_tr...
import os import glob import filetype import mutagen import json from pydub import AudioSegment from mutagen.easyid3 import EasyID3 from mutagen.easymp4 import EasyMP4 from mutagen.asf import ASFTags from mutagen.asf import ASF EXTENSION_MAPPING = None CONVERSION_TABLE = None def setExtensionMapping(): global EX...
import itertools def Hamming(Dna, Pat): return len([i for (i, j) in zip(Dna, Pat) if i!=j]) def GetAllString(mer): res = {} L= 'ACGT' perms = itertools.product(L, repeat=mer) all_str = [] for k in perms: all_str.append(''.join(k)) return all_str def GetTotal(Dna, Pat, d): arr ...