content stringlengths 5 1.05M |
|---|
# Masters Research Project 2017
# Kenneth Young
# Data Processing for the SUALBSP-2
# This file contains:
# -Functions to process the results
# Packages
from __future__ import division
import os, sys, pdb, csv
import numpy as np
#--------------------------------------------------------------------------------------... |
import base64
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import os,sys
def decr... |
import imp
import pytest
from biocommons.seqrepo import config
def test_SEQREPO_LRU_CACHE_MAXSIZE_default(monkeypatch):
monkeypatch.delenv("SEQREPO_LRU_CACHE_MAXSIZE", raising=False)
imp.reload(config)
assert config.SEQREPO_LRU_CACHE_MAXSIZE == 1000000
def test_SEQREPO_LRU_CACHE_MAXSIZE_int(monkeypatc... |
from setuptools import setup
from cli import __version__
setup(
name='csvmatch',
version=__version__,
description='Find (fuzzy) matches between two CSV files in the terminal.',
long_description=open('README.md').read(),
author='Max Harlow',
author_email='maxharlow@gmail.com',
url='https://g... |
# coding: utf-8
from __future__ import absolute_import
import json
from google.appengine.ext import ndb
from api import fields
import model
import util
class Drawing(model.Base):
hash = ndb.StringProperty(required=True)
json = ndb.JsonProperty(required=True, compressed=True, verbose_name=u'JSON')
@ndb.Compu... |
import falcon
import subprocess
from datalad_service.common.user import get_user_info
from datalad_service.tasks.files import commit_files
class ResetResource(object):
def __init__(self, store):
self.store = store
def on_post(self, req, resp, dataset, hexsha):
"""Reset master to a given comm... |
# semordnilap
def semordnilapWrapper(str1, str2):
# A single-length string cannot be semordnilap
if len(str1) == 1 or len(str2) == 1:
return False
# Equal strings cannot be semordnilap
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1,... |
#!/usr/bin/python
#crc tutorial scripts
#0_summarize_data.py
#identifies datasets and dependencies necessary for tutorial
#==========================================================================
#=============================DEPENDENCIES=================================
#=======================================... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
import libcst as cst
from fixit import CstLintRule, InvalidTestCase as Invalid, ValidTestCase as Valid
class UsePl... |
# Copyright 2018 AT&T Intellectual Property. All other 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
import glob
import jinja2
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader("slides"))
template = jinja_env.get_template("base.html")
general_vars = {
"presentation_date": "2021-09-29",
"presentation_title": "Investigating the determinants of social communication differences in neurodevelopmental... |
# Copyright © 2022 Province of British Columbia
#
# 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 scrapy
import datetime
import math
from scrapy_official_newspapers.items import ScrapyOfficialNewspapersItem
from scrapy_official_newspapers.spiders import BaseSpider
class ElPeruano(BaseSpider):
name = "ElPeruano"
country = "El Peruano, Diario oficial del Perú"
country_code = "PE" # You ... |
from fastapi import APIRouter, Request
from typing import Optional
import requests
# from fastapi import FastAPI
from fastapi.responses import RedirectResponse
import sys
import time
import jwt # JWT library for python available from https://github.com/progrium/pyjwt
import uuid
import urllib
import urllib.parse
import... |
from gpytranslate import SyncTranslator
translator = SyncTranslator()
with open("test.mp3", "wb") as file:
translator.tts("Hello world!", file=file, targetlang="en")
|
from .dataset import directory_dataset, loader, torchvision_dataset
from .model import model_checkpointer
from .trainer import trainer_checkpointer
from .optim import optimizer, scheduler, optimizer_checkpointer
from .opts import print_opts, parse, add_extras, make_subsets |
"""Class to control openMVS behaviour."""
from pathlib import Path
import subprocess
from . import utils
class OpenMVSControllerError(RuntimeError):
"""Generic openMVS error."""
pass
class OpenMVSController():
"""Controls behaviour of openMVS data processing."""
def __init__(self, res_dir, ext_lo... |
"""
Figure: network spreading
@auth: Yu-Hsiang Fu
@date: 2015/12/10
@update: 2018/03/22
"""
# --------------------------------------------------------------------------------
# 1.Import modular
# --------------------------------------------------------------------------------
# import modular
import matplot... |
from flask import Flask, render_template, url_for
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = ''
posts = [
{
'author': 'Johnny Nguyen',
'title': 'Blog post 1',
'content': 'First post content',
'date_posted': 'Oct 3, 2018',
},
{
'author': 'Jane Nguye... |
def nextPermutation(nums):
if len(nums) == 0:
return None
i = len(nums) - 1
j = -1 # j is set to -1 for case `4321`, so need to reverse all in following step
while i > 0:
if nums[i - 1] < nums[i]: # first one violates the trend
j = i - 1
break
i... |
import json
import sys,os
import threading
from typing import List
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from request.RequestPostJson import RequestPostJson
from session.Session import Session
from request.RequestGetOwnPlayerTrades import RequestGetOwnPlayerTrades
class Reques... |
import matplotlib.pyplot as plt
import numpy as np
from ECDF import ecdf
samples_std1 = np.random.normal(20, 1, size=100000)
samples_std3 = np.random.normal(20, 3, size=100000)
samples_std10 = np.random.normal(20, 10, size=100000)
# Generate CDFs
x_std1, y_std1 = ecdf(samples_std1)
x_std3, y_std3 = ecdf(samples_std3)... |
from tinydb import Query
from .database import Database
from .document import Document
from .mixins import ModelMixin
from .models import BaseModel
from .table import Table
|
class Buffer(object):
"""
A Buffer is a simple FIFO buffer. You write() stuff to it, and you
read() them back. You can also peek() or drain() data.
"""
def __init__(self, data=b''):
"""
Initialize a buffer with 'data'.
"""
self.buffer = bytes(data)
def read(self... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model as lm # Used for solving linear regression problems
def fit_ar(y, p):
"""Fits an AR(p) model. The loss function is the sum of squared errors from t=p+1 to t=n.
:param y: array (n,), training data points
:param p: int, AR ... |
#-------------------------------
# Statistical functions for computing the bounds
#-------------------------------
from Source.experiments import *
from scipy.optimize import fsolve, brentq
# Years for the exposure
years = 10.
# Chi2 treshold
#chi2_th = 1. # 68.27 CL (1 sigma)
chi2_th = 2.71 # 90 % CL
#chi2_th =... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import itertools
# switch to Physical Review compatible font
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath,amssymb,txfonts}'
matplotlib.rcParams['font.f... |
import click
import toml
import sys
import os
@click.command()
@click.option('--pydss_path',
default=r'C:\Users\alatif\Desktop\PyDSS_2.0\PyDSS')
@click.option('--sim_path',
default=r'C:\Users\alatif\Desktop\PyDSS_2.0\PyDSS\examples\external_interfaces\Python_example')
@click.option('--sim_f... |
"""Evaluation measures at the level of document orderings."""
from repro_eval.config import TRIM_THRESH, PHI
from scipy.stats.stats import kendalltau
from tqdm import tqdm
from repro_eval.measure.external.rbo import rbo
from repro_eval.util import break_ties
def _rbo(run, ideal, p, depth):
# Implementation taken... |
import struct
from . import codes
from . import _data
class PDU:
@property
def functionCode(self): return self._functionCode
@property
def bytes(self): return self._bytes
def __init__(self, functionCode, bytes_=b''):
self._functionCode = functionCode
self._bytes = bytes_
... |
from keras.layers.core import Dense, Dropout
from keras.models import Sequential
from keras.preprocessing.sequence import pad_sequences
from keras.utils import np_utils
from sklearn.model_selection import train_test_split
import collections
import nltk
import numpy as np
from make_tensorboard import make_tensorboard
im... |
from LosmliProxyPool.settings import default_settings
from LosmliProxyPool.utils.load import mysql2redis, update2mysql
from LosmliProxyPool.utils.log import root_logger
from LosmliProxyPool.validator.amazon import check_proxy_amazon
def check_proxy():
root_logger.info('Start to check proxy.')
mysql2redis(defa... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2021 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from lib.core.enums import DBMS
from lib.core.settings import INFORMIX_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.informix.enumeration import Enumerati... |
from metamapper import CoreIRContext
from metamapper.irs.coreir import gen_CoreIRNodes
import metamapper.coreir_util as cutil
from metamapper.common_passes import SMT, print_dag, prove_equal
def test_dag_to_smt():
CoreIRContext(reset=True)
CoreIRNodes = gen_CoreIRNodes(16)
cmod = cutil.load_from_json("exa... |
#!/usr/bin/python
import sys
for line in sys.stdin:
data = line.strip().split(" ")
request = data[5]
print request |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2001-2017 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause Lic... |
import ml_colorise
import image_convert
# IMAGE ML
image_convert.video_to_images("input/vid.mp4","input")
ml_colorise.test("input","output",ml_colorise.ML_TYPE_TF,ml_colorise.ML_MODE_COLORIZE)
image_convert.images_to_video("output",output_file="vid_colour.avi")
ml_colorise.test("output","output_super",ml_colorise.ML_T... |
import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from db.helper.forms import convert_date
from db.models import JobType, DateMode, Branch
@pytest.mark.django_db
def test_employment_date_range(login, user_student, student_employment, job_type_objects_d... |
import argparse
import codecs
import json
import logging
import os
import sys
import time
#BASE_DIR = "/Users/cbardas/instapy-log/"
BASE_DIR = "/home/instapy-log/"
stdout = sys.stdout
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.path.append(os.path.join(sys.path[0], '../'))
fileName = "resize" + time.strftim... |
from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="lambdata-NealWhitlock",
version="0.1.7",
author="NealWhitlock",
author_email="nealwhitlock@gmail.com",
description="Example package for lambda school DS Unit 3",
long_de... |
"""Unit test package for concurrency."""
|
from miflora.miflora_poller import MiFloraPoller, \
MI_CONDUCTIVITY, MI_MOISTURE, MI_LIGHT, MI_TEMPERATURE, MI_BATTERY
class FlowerSensor:
def __init__(self,name,mac):
self.name = name
self.mac = mac
self.temp = 0
self.light = 0
self.battery = 0
self.conduc... |
#import Minsung.Face_list as fl
import Minsung.Face as fa
import os
import re
#import picamera
#Initial Settings
def setName(name):
name = name.lower()
with open('name.txt', 'w') as f:
f.write(name)
f.close()
print("이름이 성공적으로 저장되었습니다.")
def Picapture():
with picamera.Pic... |
import glob
import pandas as pd
import argparse
from gensim.models import Word2Vec
import gensim.downloader as api
from scipy.stats import pearsonr
parser = argparse.ArgumentParser()
parser.add_argument(
'-w',
'--w2v',
action='store',
default=None,
dest='model_path',
help='File with the word2... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("CastorShowerLibraryMaker")
process.common_maximum_timex = cms.PSet(
MaxTrackTime = cms.double(500.0),
MaxTimeNames = cms.vstring(),
MaxTrackTimes = cms.vdouble()
)
process.common_pgun_particleID = cms.PSet(
PartID = cms.vint32(11,211)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: mohit jain
"""
'''
We will use genetic algorithum to optimize hyperparameters for XGboost.
'''
# Importing the libraries
import numpy as np
import pandas as pd
import geneticXGboost #genetic algorithum module
import xgboost as xgb
np.random.seed(723)
'''
... |
import logging
import os
import json
from elasticsearch import Elasticsearch
from traceback import format_exc
### Default configuration ###
# Don't edit these values directly
# either set them on import with velociwrapper.config.varname = value
# or through the environment VW_VARNAME=value
# Data source node names a... |
# coding: utf-8
import os
def cd(arg, display_cwd=True):
os.chdir(arg)
if display_cwd:
print(os.getcwd())
|
"""The mqtt_room component."""
|
import os
import time
from argparse import ArgumentParser, Namespace
from multiprocessing.pool import ThreadPool
def get_time_in_seconds(testing_time):
if 'h' in testing_time:
testing_time_in_secs = int(testing_time[:-1]) * 60 * 60
elif 'm' in testing_time:
testing_time_in_secs = int(testing_t... |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
# coding:utf-8
import requests
import time
from math import fabs
from base64 import b64encode
# from demjson import decode
class RaspberryMonitorNetSpeed:
url = 'http://192.168.123.1/update.cgi?output=netdev'
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,... |
#!/usr/bin/python
"""
Name : create_smgr_db.py
Author : rishiv@juniper.net
Description : This program is a simple cli interface to
create server manager database with objects.
Objects can be cluster, server or image.
Mandatory Parameter : testbed.py
Optional Parameter : cluster_id
Optional Para... |
import asyncio
from userbot import CMD_HELP, StartTime, bot
from userbot.utils import bash, edit_or_reply, zelda_cmd
@zelda_cmd(pattern="cm (.*)")
async def amireallycontent(content):
user = await bot.get_me()
capt = str(content.pattern_match.group(1).split(" ", 2)[0])
link = str(content.pattern_match.gro... |
#-*-coding:utf-8-*-
import re
import random
from utils.tools import ch_count
not_match_pattern = re.compile(r"吗|\?|?|多|哪|怎|什么|啥|退|发票")
start_pattern = re.compile(
r"http|"
r"您好|"
r"你好|"
r"在|"
r"那个|"
r"有人|"
r"转人工|"
r"hi|"
r"(?=.*咨询)(?=.*订单)")
def intent_update(msg, dialog_status... |
import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.models import NaiveModel
from etna.transforms.missing_values import TimeSeriesImputerTransform
from etna.transforms.missing_values.imputation import _OneSegmentTimeSeriesImputerTransform
def test_wrong_init_one_segment... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""Run the main body of this code to execute experiments."""
from __future__ import absolute_import
from __future__ import print_function
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd import grad
from autograd.misc.flatten import flatten
from co... |
# Copyright 2016 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.
{
'targets': [
{
# This target runs a functionally empty lint to create or update the
# API versions cache if necessary. This prevents racy... |
# --------------
#Header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading of the file
data=pd.read_csv(path)
# Code starts here
#1
data['Gender'] = data['Gender'].replace('-','Agender')
data['Gender'].value_counts().plot(kind="bar")
plt.title('Gender Distribution o... |
import sys,os,subprocess,json,argparse
def main():
duration = 0
parser = argparse.ArgumentParser(description='Build BORIS from data')
parser.add_argument('--template',help="template BORIS file to load")
parser.add_argument('--videopath',help="path with mp4 to scan")
parser.add_argument('--output',hel... |
"""
The flask application package.
"""
from configparser import ConfigParser
from flask import Flask,render_template,Config,session,request,abort
import base64
from functools import wraps
from flask import g,request,redirect,url_for
import itsdangerous
class LibConfig(Config):
"""
LibServer inherits this Con... |
def mensagem(msg):
tam = len(msg) + 4
print('~' * tam)
print(f' {msg}')
print('~' * tam)
# Programa Principal
mensagem(f'{"Gustavo Guanabara"}')
mensagem(f'{"Curso de Python no Youtube"}')
mensagem(f'{"CeV"}')
|
from cabi.prepare_data.complete import complete
from cabi.techniques.ensemble import random_forest
import pandas as pd
from sklearn.externals import joblib
def create_model(
file_prefix, db_engine, station_id, start, end, prep=complete,
technique=random_forest):
start = pd.to_datetime(start, infer... |
#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, 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 ... |
def increment_string(s):
numbers = '0123456789'
s_strip = s.rstrip(numbers)
get_numbers = s[len(s_strip):]
if len(get_numbers) > 0:
adding_proc = 1 + int(get_numbers)
return s_strip + str(adding_proc).zfill(len(get_numbers))
elif len(get_numbers) == 0:
return s + '1'
... |
"""Test Scrape component setup process."""
from __future__ import annotations
from unittest.mock import patch
from homeassistant.components.scrape.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import MockRestData
from tests.common i... |
from __future__ import print_function
"""
Do a mouseclick somewhere, move the mouse to some destination, release
the button. This class gives click- and release-events and also draws
a line or a box from the click-point to the actual mouseposition
(within the same axes) until the button is released. Within the
method... |
import numpy as np
import soundfile as sf
from scipy import signal
import random
import os
def load_audio(path):
sound, sample_rate = sf.read(path, dtype='int16')
# TODO this should be 32768.0 to get twos-complement range.
# TODO the difference is negligible but should be fixed for new models.
soun... |
# -*- coding: utf-8 -*-
# Part of BrowseInfo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class medical_medication_dosage(models.Model):
_name = 'medical.medication.dosage'
name = fields.Char(string="Frequency",required=True)
abbreviation = field... |
from .emailService import Email
from .sms import Sms
from .console import Console
from .mqtt import Mqtt
from .attachment import Attachment
from .notification import Notification
class Services:
def __init__(self, token):
self.token = token
@property
def sms(self):
return Sms(self.token)
@property
... |
import sys
import logging
logger_bike = None
logger_bus = None
logger_app = None
logger_emergency = None
logger_parkings = None
logger_population = None
def bike_log(): # Creating custom logger to store logging information.
global logger_bike
if logger_bike is None:
logger_bike = create_logger('bike... |
import subprocess
def traceroute(dest: str) -> dict:
"""
Trace the route to some destination IP and return a dict of intermediates.
In order to prevent the daemon itself from needing to run with elevated
privileges, this is primarily handled by the system's traceroute utility.
"""
# Sanitize input.
for char in... |
class TextExtractor:
"""
Extract text from a txt file
"""
def extract_text(self, file, encoding = None):
"""
Extract text from an text
:param file: file_path of text file
:return: List of dictionary in following keys
"text": Transcrip... |
from typing import List
from annotation.param import Param
class Jsdoc:
def __init__(self):
self.params = list()
self.name = ''
def add_param(self, param: Param):
self.params.append(param)
def set_name(self, name: str):
self.name = name
def set_type(self, type_: st... |
#
# STEP Part 21 Parser
#
# Copyright (c) 2011, Thomas Paviot (tpaviot@gmail.com)
# Copyright (c) 2014, Christopher HORLER (cshorler@googlemail.com)
#
# All rights reserved.
#
# This file is part of the StepClassLibrary (SCL).
#
# Redistribution and use in source and binary forms, with or without
# modification, are pe... |
#!/usr/bin/env python
#
# Copyright (C) 2020 The Android Open Source Project
#
# 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 req... |
import base64
import requests
import urllib3
from urllib.parse import quote,unquote
# 禁用warning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 填写帐号密码
userAccounts = [
# ['userStudentId', 'password'],
['123456', 'password']
]
def func(username, pwd):
# 初始化用headers
url1 = 'http... |
"""Implementation of the difficulty command."""
from mcipc.rcon.client import Client
from mcipc.rcon.functions import parsed
from mcipc.rcon.response_types.difficulty import parse
from mcipc.rcon.types import Difficulty
__all__ = ['difficulty']
# pylint: disable=W0621
@parsed(parse)
def difficulty(self: Client, di... |
import argparse
import sys
from ttvduw import DocuPrinter, DataFeeder
from ttvduw_gui import TtvduwGui
def test():
#########
## testing DataFeeder
# from test_ttvduw import test_DataFeeder
# test_DataFeeder()
#########
## testing DocuPrinter
# from test_ttvduw import test_DocuPrinter
# ... |
import unittest
from anchore_engine.util.rpm import compare_versions
class TestRpmVersionHandling(unittest.TestCase):
"""
Tests for version comparisons of rpm package versions maintained in anchore engine.
Note that this does not exactly confirm the official rpm spec
"""
def test_version_compar... |
"""Class decorators and other helpers."""
import numpy as np
import inspect
from vectorbt.utils import checks
from vectorbt.utils.config import merge_dicts
def get_kwargs(func):
"""Get names and default values of keyword arguments from the signature of `func`."""
return {
k: v.default
for k,... |
# Generated by Django 3.2.5 on 2021-07-21 10:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Stu... |
import time
from zxcvbn.matching import omnimatch
from zxcvbn.scoring import minimum_entropy_match_sequence
def password_strength(password, user_inputs=[]):
start = time.time()
matches = omnimatch(password, user_inputs)
result = minimum_entropy_match_sequence(password, matches)
result['calc_time'] = ... |
# -*- coding: utf-8 -*-
# properties.py
#
# Copyright 2019 Hiroshi Miura <miurahr@linux.com>
from __future__ import unicode_literals
import os
import pkg_resources
# This class is Borg
class Configurations(object):
_shared_state = {}
data_path = pkg_resources.resource_filename(__name__, 'data')
jisy... |
from my_enc_dec2 import encrypt, decrypt
KEY = 'small_key'
def test_encrypt():
assert encrypt('cat', KEY) == 'WOV'
assert encrypt('dog', KEY) == 'X]I'
def test_decrypt():
assert decrypt('WOV', KEY) == 'cat'
assert decrypt('X]I', KEY) == 'dog'
test_encrypt()
test_decrypt()
|
import h5py
import numpy as np
import scipy
from typing import List, Tuple
from tensorflow.keras.utils import to_categorical
# from ml4h.tensor_writer_ukbb import tensor_path
from ml4h.normalizer import ZeroMeanStd1, Standardize
from ml4h.tensormap.general import tensor_path
from ml4h.TensorMap import TensorMap, Interp... |
# RLE Source: https://www.kaggle.com/rakhlin/fast-run-length-encoding-python
import os
import numpy as np
import pandas as pd
from skimage.morphology import label
def rle_encoding(x):
dots = np.where(x.T.flatten() == 1)[0]
run_lengths = []
prev = -2
for b in dots:
if (b>prev+1): run_lengths.ext... |
while True:
up_c = input('Результаты через запятую (без пробелов):\n').rstrip().split(',')
if up_c == ['']:
exit(0)
up_ball = ((int(up_c[2]) - int(up_c[1])) + (int(up_c[4]) - int(up_c[3])) + (int(up_c[6])) - int(up_c[5])) / 3
up_ball = round(up_ball, 2)
print(up_ball)
|
"""Init strategies to be used for running jobs."""
import logging
import os
from copy import deepcopy
import numpy as np
import yaml
from sklearn.experimental import (enable_hist_gradient_boosting,
enable_iterative_imputer)
from sklearn.ensemble import (HistGradientBoostingClassifier,... |
import os
import shutil
import re
from fontInfoData import getAttrWithFallback, intListToNum, normalizeStringForPostscript
from outlineOTF import OutlineOTFCompiler
from featureTableWriter import FeatureTableWriter, winStr, macStr
from kernFeatureWriter import KernFeatureWriter
try:
sorted
except NameError:
def... |
import logging
from rastervision.pytorch_learner.dataset import (ImageDataset, TransformType,
SlidingWindowGeoDataset,
RandomWindowGeoDataset)
log = logging.getLogger(__name__)
class ClassificationImageDataset(ImageD... |
from flask_restful import Resource
from flask import request
from main.server import app, cache, db
from main.server.models import Games, GameSchema
games_schema = GameSchema(many=True)
game_schema = GameSchema()
@app.after_request
def add_header(response):
response.headers['Access-Control-Allow-Origin'] = '*'
... |
import gdsfactory as gf
def test_transition_ports() -> None:
width1 = 0.5
width2 = 1.0
x1 = gf.cross_section.strip(width=width1)
x2 = gf.cross_section.strip(width=width2)
xt = gf.path.transition(cross_section1=x1, cross_section2=x2, width_type="linear")
path = gf.path.straight(length=5)
c ... |
from esl._esl._economics._finance import *
|
###################################################
# header_meshes.py
# This file contains declarations for meshes
# DO NOT EDIT THIS FILE!
###################################################
render_order_plus_1 = 0x00000001
|
import random
from app.fiftycents.entities.card import Card
class Deck():
def __init__(self, size=1, empty = False):
self.cards = []
if not empty:
self.cards = [Card(r) for r in Card.RANKS
for i in range(Card(r).count)
... |
def double(arg: int) -> int:
return arg * 2
x: List[str] = ['a', 'bb']
x1 = list(map(double @ length_of_str, x))
x2 = list(map(double, list(map(length_of_str, x))))
assert x1 == x2 # どちらの値も[2, 4]
|
import logging
from corona_data_collector.tests.common import get_db_test_row, run_full_db_data_test
logging.basicConfig(level=logging.INFO)
TEST_FIELDS = {
# db field corona_bot_answers field
"version": "questionare_version... |
def top3(products, amounts, prices):
|
#!/usr/bin/env python3
# Synthesise AnkleSoC on iCEStick, with some given RAM size and RAM init binary.
import sys
import os.path
sys.path.append(os.path.abspath(os.path.dirname(sys.argv[0]) + "/../hdl"))
import argparse
from nmigen import *
from nmigen_boards.icestick import ICEStickPlatform
from anklesoc import An... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.