content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division
import ndef
import pytest
import _test_record_base
def pytest_generate_tests(metafunc):
_test_record_base.generate_tests(metafunc)
class TestTextRecord(_test_record_base._TestRecordBase):
RECORD = ndef.text.TextRecord
ATTRIB = "t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def check(S,a,b):
if (a in S) and (b not in S):
return 0
if (b in S) and (a not in S):
return 0
return 1
def main():
S = str(input())
flag = 1
for a,b in [['N','S'],['E','W']]:
flag = min(check(S,a,b),flag)
if flag==1:
... |
from policy.common import Policy, Perms
import os
class Printers (Policy):
def __init__(self):
self._Policy__name = "Printers"
self._Policy__script_name = "printers.sh"
self._Policy__template = "printers.bash.j2"
self._Policy__perms = Perms.ROOT
def process(self, scope, pat... |
import os
import torchvision.models as models
import gemicai as gem
import unittest
data_path = os.path.join("..", "examples", "gemset", "CT")
data_set = os.path.join(data_path, "000001.gemset")
test_classifier_dir = os.path.join("test_directory")
model = models.resnet18(pretrained=True)
train_dataset = gem.DicomoDat... |
# RPG SIMPLES
# BIBLIOTECAS
import os # Sistema operacional
import sys # Sistema-interpretador
from random import random # Gerador de números aleatórios [0,1)
from time import sleep # Aguardar
# CLASSES
class Jogador():
"""
# JOGADOR
---------
Classe primá... |
import pytest
from types import SimpleNamespace
from _pytest.main import Session
from click.testing import CliRunner
from commands.login import cli as login
from commands.status import cli as status
from commands.config import cli as config
from tests.helpers.test_utils import mock_login_get_urls
import sys
sys.path.... |
import logging, threading, time
from acq4.util import Qt
import falconoptics
from ..FilterWheel.filterwheel import FilterWheel, FilterWheelFuture, FilterWheelDevGui
class FalconTurret(FilterWheel):
def __init__(self, dm, config, name):
self.dev = falconoptics.Falcon(config_file=None, update_nonvolatile=Tr... |
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
class Config(TeaModel):
"""
Model for initing client
"""
def __init__(self, access_key_id=None, access_key_secret=None, security_token=None, protocol=None,
read_timeout=None, c... |
import json
import logging
class simpleGraph():
def __initializeGraph(self, graphData: dict):
self.__graph = {}
for key, value in graphData.items():
neighbors = []
for neighbor, weight in value.items():
neighbors.append((int(neighbor), int(weight)))
... |
#!/usr/bin/env python3
# -*- coding: iso-8859-15 -*-
from sqlalchemy import *
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
engine = ""
try:
from settin... |
"""
gpcr_ecl_saltbridge.py
Identify GPCR structures with saltbridges between extracellular loops 2 and 3.
Handles all functions.
"""
# python standard library
from collections import OrderedDict
import json
import logging
import pathlib
import pickle
from urllib.error import HTTPError
from urllib.request import urlope... |
from .stage01_ale_analysis_io import stage01_ale_analysis_io
class stage01_ale_analysis_execute(stage01_ale_analysis_io):
pass; |
from itertools import permutations
from pathlib import Path
from number_class import NumberLeaf, NumberTree
from ycecream import y as ic
def part1():
lines = Path("input.txt").read_text().splitlines()
total = NumberTree.from_string(lines[0])
for line in lines[1:]:
add_on = NumberTree.from_string... |
"""
Main file to run the directory app.
"""
from django.apps import AppConfig
class DirectoryConfig(AppConfig):
"""
Specify directory name to run
"""
name = 'directory'
|
from django.shortcuts import render
from .models import UserProfile, Job, Skill, Degree, Project
# Create your views here.
def home(request):
profiles = UserProfile.objects.all()
jobs = Job.objects.all()
skills = Skill.objects.all()
degrees = Degree.objects.all()
projects = Project.objects.all()
... |
from typing import Any, Callable, Iterable, Tuple, TypeVar
_T = TypeVar('_T')
_U = TypeVar('_U')
def _is_iterable(x: Any) -> bool:
return hasattr(x, '__iter__')
def identity(x: _T) -> _T:
"""The identity function."""
return x
def compose(f: Callable[[_T], _U], g: Callable[..., _T]) -> Callable[..., _U]:... |
import re
from events import events
from settings import DEFAULT_RESPONSE
class EventHandler(object):
def __init__(self):
self.events = [(re.compile(pattern), callback) for pattern, callback in events]
def route(self, update):
msg = update.message.text
for event, callback in self.eve... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Import Modules
import re
... |
import GPUtil
import os
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from firebase_admin import storage
import threading
import random
darknetPath = "/homes/ma438/scratch/darknet/"
rootDataPath = "/homes/ma438/scratch/darknet/labs/"
outputPath = "/homes/ma438/scratch/darkn... |
from logicqubit.logic import *
from logicqubit.gates import *
from logicqubit.synthesis import *
A = Matrix([[15, 9, 5, -3],[9, 15, 3, -5],[5, 3, 15, -9],[-3, -5, -9, 15]])*(1/4)
dep = PauliDecomposition(A)
print(dep.get_a())
ket0 = Hilbert.ket(0)
ket1 = Hilbert.ket(1)
ket00 = Hilbert.kronProduct([ket0, ket0])
ket0... |
import logging
import simplejson as json
from restclients.models.bridge import BridgeCustomField
from restclients.bridge import get_resource
logger = logging.getLogger(__name__)
URL_PREFIX = "/api/author/custom_fields"
def get_custom_fields():
"""
Return a list of BridgeCustomField objects
"""
resp ... |
import cv2
def readMap(mapFileName):
mapFile = open(mapFileName, "r")
lines = mapFile.readlines()
map = []
for line in lines:
line =line.split(',')
line = [int(x) for x in line]
map.append(line)
return map
def writeMap(imageFileName, mapFileName):
mapFile = open(mapFil... |
# Generated by Django 2.1.5 on 2020-10-17 21:32
from django.db import migrations, models
import django.db.models.deletion
import hostel.service.variables
class Migration(migrations.Migration):
initial = True
dependencies = [
('common', '0002_auto_20201017_2132'),
]
operations = [
m... |
from cms.extensions.toolbar import ExtensionToolbar
from cms.utils import get_language_list
from django.utils.encoding import force_text
from django.utils.translation import get_language_info
class TitleExtensionToolbar(ExtensionToolbar):
model = None
insert_after = None
def get_item_position(self, menu)... |
import random
import typing as t
import unittest
from bamboo import (
ASGIApp,
ASGIHTTPEndpoint,
WSGIApp,
WSGIEndpoint,
WSGIServerForm,
WSGITestExecutor,
)
from bamboo.api import JsonApiData
from bamboo.request import http
from bamboo.sticky.http import data_format
from bamboo.util.string impor... |
'''
Created on Aug 27, 2015
@author: ash
'''
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import shapefile
# urlShpFile = "/home/ash/Data/tl_2014_39049_roads/tl_2014_39049_roads.shp"
urlShpFile = "/home/ash/Data/tl_2013_06_prisecroads/tl_2013_06_prisecroads.shp"
def synGraph():
G = n... |
from django.apps import AppConfig
class TranspilerConfig(AppConfig):
# default_auto_field = 'django.db.models.BigAutoField'
name = 'transpiler'
|
from bitstring import Bits, BitString, BitArray, ConstBitStream
import base64
class Addr:
def __init__(self,bank,addr) -> None:
self.bank = bank
self.addr = addr
def absolute_pos(self) -> int:
return (((self.bank-1)*BANK_SIZE)+self.addr)
@classmethod
def convert_to_addr(cls, ... |
import multiprocessing
from myFunc import myFunc
if __name__ == '__main__':
for i in range(6):
process = multiprocessing.Process(target=myFunc, args=(i,))
process.start()
process.join()
|
import scrapy
from scrapy.spiders import CrawlSpider
from scrapy_app.spider_common import common_parser
class CrawlItem(scrapy.Item):
name = scrapy.Field()
link = scrapy.Field()
# default spider for retrieve href in the given URL
class CrawlerxSpider(CrawlSpider):
name = 'crawlerx'
def __init__(sel... |
from conans import ConanFile, CMake, tools
from conans.util import files
import yaml
class Bcm2837Conan(ConanFile):
name = "bcm2837"
version = str(yaml.load(tools.load("settings.yml"))['project']['version'])
license = "MIT"
url = "git@git.hiventive.com:socs/broadcom/bcm2837.git"
description = "BCM... |
#!/usr/bin/env python3
"""
SCRIPT: plot_semivariogram.py
Script for plotting empirical and fitted semivariograms based on data from
procOBA_NWP or procOBA_Sat, plus fit_semivariogram.py. For interactive
use.
REQUIREMENTS:
* Python 3
* Matplotlib
* Numpy
REVISION HISTORY:
20 Nov 2020: Eric Kemp. Initial specificatio... |
import io
import os
import os.path as osp
import shutil
import warnings
import copy
import mmcv
import numpy as np
import torch
from mmcv.fileio import FileClient
from torch.nn.modules.utils import _pair
from ...utils import get_random_string, get_shm_dir, get_thread_id
from ..builder import PIPELINES
from .loading im... |
######################################################################################
# python 3 script for killing user sessions of Ibcos gold classic
# author: Isaac Thompson 20/03/2021 - 26/05/2021, Lloyd Ltd
######################################################################################
import telnetl... |
from .entrepreneur_profile_cleanup import (
clean_entrepreneur_profile_twitter_handles
)
from .expert_profile_cleanup import (
clean_expert_profile_twitter_handles
)
from .organization_cleanup import clean_organization_twitter_handles
|
import setuptools
with open("README.md", "r") as readme:
long_description = readme.read()
with open("VERSION", "r") as version_f:
version = version_f.read()
setuptools.setup(
name="FastAPIwee",
version=version,
author="German Gensetskyi",
author_email="Ignis2497@gmail.com",
description="... |
from unittest import TestCase
import simplejson as json
from mock import patch, PropertyMock, Mock
from pydclib.pydclib import bin2hstr
from dc.core import config
from dc.core.Indexer import Indexer
from dc.core.State import State
from dc.core.StateContainer import StateContainer
from dc.core.misc import logger
from ... |
import os
LAST_VERSION_WITH_ERROR = 174
conan_version = int(filter(str.isdigit, os.popen('conan --version').read()))
if LAST_VERSION_WITH_ERROR >= conan_version :
os.system('cp -r conan_fixed_os_x/default /Users/$USER/.conan/profiles/')
os.system('cp -r conan_fixed_os_x/settings.yml /Users/$USER/.conan/') |
import random
cont = 1
pi = 'a'
print('Vamos jogar par ou impar?')
while True:
num = int(input('Digite um numero'))
rand = random.randint(1, 5)
while pi not in '´PIpi':
pi = str(input('Par ou Impar?[P/I]')).strip().upper()[0]
if (num+rand) % 2 == 0 and pi == 'P':
print(f'A soma dos numer... |
# coding: utf-8
"""
Account - 虚拟账户,用于仿真交易
仿真交易分为两种模式:
1)strict - 严格模式,只能在正常交易时间段进行虚拟交易,参照真实交易规则;
2)loose - 宽松模式,不进行任何限制,允许任意添加交易记录
====================================================================
"""
import os
from datetime import datetime
import json
from tma import ACCOUNT_PATH
from tma.collector import get_p... |
import os
import types
import unittest
from LAMARCK_ML.data_util import TypeShape, IOLabel, DFloat, Shape, DimNames
from LAMARCK_ML.individuals import ClassifierIndividualOPACDG, NetworkIndividualInterface
from LAMARCK_ML.models.models import GenerationalModel
from LAMARCK_ML.reproduction import Mutation, Recombinatio... |
class Command(object):
is_global = True
def __init__(self, name):
self.name = name
self.cli = None
# For completion
self.matches = []
def valid_in_context(self, context):
return True
def complete(self, text, state):
'''
Return the next possible ... |
#!/usr/bin/env python3
# [rights] Copyright 2020 brianddk at github https://github.com/brianddk
# [license] Apache 2.0 License https://www.apache.org/licenses/LICENSE-2.0
# [repo] github.com/brianddk/reddit/blob/master/python/elec-p2sh-hodl.py
# [btc] BTC-b32: bc1qwc2203uym96u0nmq04pcgqfs9ldqz9l3mz8fpj
# [tipja... |
# Generated by Django 2.2.4 on 2019-08-04 21:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('jobHistory', '0002_auto_20190106_0202'),
]
operations = [
migrations.AlterField(
model_name='em... |
import pymht.tracker as tomht
import pymht.utils.helpFunctions as hpf
import xml.etree.ElementTree as ET
from pymht.utils.xmlDefinitions import *
from pysimulator.scenarios.defaults import *
import os
import datetime
def runPreinitializedVariations(scenario, path, pdList, lambdaphiList, nList, nMonteCarlo,
... |
"""Bounding volume implementation
Based on code from:
http://www.markmorley.com/opengl/frustumculling.html
Notes regarding general implementation:
BoundingVolume objects are generally created by Grouping
and/or Shape nodes (or rather, the geometry nodes of Shape
nodes). Grouping nodes are able to cr... |
import argparse
import sys
from webStegFS import console
default_proxies = {'https': 'https://165.139.149.169:3128',
'http': 'http://165.139.149.169:3128'}
def proxy_test(proxyL):
import requests
try:
r = requests.get('https://google.com', timeout=5)
assert(r.status_code is... |
# Copyright 2020 The fingym Authors.
#
# 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 w... |
with open('day-08/input.txt', 'r') as file:
signals = file.readlines()
def find(patterns):
one = (next(p for p in patterns if len(p) == 2))
seven = (next(p for p in patterns if len(p) == 3))
four = (next(p for p in patterns if len(p) == 4))
eight = (next(p for p in patterns if len(p) == 7))
nin... |
import glob
import os
import shutil
for whl_path in glob.glob(os.path.join(os.getcwd(), 'dist', '*.whl')):
whl_name = os.path.basename(whl_path)
dist, version, python_tag, abi_tag, platform_tag = whl_name.split('-')
if 'manylinux' in platform_tag:
continue
platform_tag = platform_tag.replace('... |
from scripts import Warnings, Log, Constants
from scripts.backend.database import Database
"""
All database functions return a boolean value as for whether the operation or check was successful or not
"""
def get_user_name_list():
Log.debug("Retrieving all user names.")
Database.cursor.execute("SELECT Na... |
""" Interface to the SUNDIALS libraries """
import numpy as np
from .cvode import *
from .cvode_ls import *
from .nvector_serial import *
from .sundials_linearsolver import *
from .sundials_matrix import *
from .sundials_nvector import *
from .sundials_types import *
from .sundials_version import *
from .su... |
#!/usr/bin/python
# Filename: venter_gff_snp_to_gff.py
"""
usage: %prog venter_gff ...
"""
# Output standardized GFF record for each SNP in file(s)
# ---
# This code is part of the Trait-o-matic project and is governed by its license.
import fileinput, os, sys
def main():
# return if we don't have the correct a... |
"""Contains Sensor class.
Sensor manages connection with board.
"""
import analogio
import board
class Sensor(analogio.AnalogIn):
@property
def voltage(self) -> float:
"""Return approx voltage."""
return self.value / 65535 * 3.3
|
from setuptools import setup, find_packages
PACKAGES = find_packages()
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='pyns',
version='0.4.10',
description='Neuroscout API wrapper',
long_description=long_description,
long_description_content_type="text/markdown"... |
# pylint: disable=redefined-outer-name,protected-access
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
from awesome_panel_extensions.frameworks.fast import FastTextInput
from tests.frameworks.fast.fast_test_app import create_fast_test_app
def test_constructor():
# Wh... |
from .base import *
from .signals import *
#TODO: test storage of facet labels |
from django.contrib import admin
from {{ app_name }}.models import *
# Register your models here
# For more information on this file, see
# https://docs.djangoproject.com/en/{{ docs_version }}/intro/tutorial02/
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdm... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from types import NoneType
from posts.models import Post
def home(request):
try:
post_new = Post.objects.all().filter(visible=True).latest('created')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
from setuptools import setup, Extension
import versioneer
from Cython.Build import cythonize
import numpy
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()... |
"""Match products to customers to maximize suitability.
https://www.codeeval.com/open_challenges/48/
"""
from itertools import permutations, product, izip
from fractions import gcd
from fileinput import input
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
VOWELS = 'aeiouy' # yes, 'y' is a v... |
from __future__ import absolute_import
from .ppo import PPO
from .a2c import A2C
from .acktr import ACKTR
|
import colorama
from colorama import Fore
colorama.init(autoreset=True)
def read_int(txt):
while True:
try:
read = int(input(txt))
except (ValueError, TypeError, KeyboardInterrupt):
print(Fore.RED + '\nPOR FAVOR,UTILIZE APENAS NÚMEROS!')
continue
else:
... |
# Copyright 2017 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.
"""Provides an endpoint for getting details about a sheriffed bug."""
import json
import re
from dashboard import oauth2_decorator
from dashboard.common im... |
from typing import Optional, List, Tuple, Dict
import numpy as np
from banditpylib.data_pb2 import Feedback, Actions, Context
from .lilucb_heur_collaborative_utils import assign_arms, \
get_num_pulls_per_round, CentralizedLilUCBHeuristic
from .utils import MABCollaborativeFixedTimeBAIAgent, \
MABCollaborativ... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
import papas
# Load long description from files
with open('README.rst', 'r') as readme, open('CHANGELOG.rst', 'r') as history:
long_description = '\n' + readme.read() + '\n\n' + history.read()
# A list of strings specifying what other distributi... |
#!/usr/bin/env python
'''
Code for isotope diffusion.
'''
import numpy as np
# from solver import solver
from solver import transient_solve_TR
# from Gasses import gasses
# from Sites import sites
from reader import read_input, read_init
import json
import scipy.interpolate as interpolate
from constants import *
imp... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 3 12:05:07 2020
@author: henry
"""
import sqlalchemy as db
engine = db.create_engine('sqlite:///../GPOWarehouse.sqlite')
metadata = db.MetaData()
connection = engine.connect()
#Global vars
run_stats = db.table('run_stats', metadata,
db.Column('r... |
# Copyright (c) 2017 Trail of Bits, 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 ... |
import base64
import keys
def generate_password(formatted_time):
data_to_encode = keys.business_shortCode + \
keys.lipa_na_mpesa_passkey + formatted_time
encoded_string = base64.b64encode(data_to_encode.encode())
# print(encoded_string) b'MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODk... |
#/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2014, Nigel Small
#
# 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 ... |
#!/usr/bin/env python
# coding=utf-8
"""
This script will aid in generating a test coverage report for PFASST++ including its examples.
A standard CPython 3.3 compatible Python interpreter with standard library support is required.
No additional modules.
Run it with argument `-h` for usage instructions.
.. moduleaut... |
"""
Mask initial bases from alignment FASTA
"""
import argparse
from random import shuffle
from collections import defaultdict
import Bio
import numpy as np
from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio.Seq import Seq
from Bio import AlignIO, SeqIO
from scipy import sparse
def compactify_sequences(sparse_m... |
from dataclasses import dataclass
from typing import List
from spotdl.utils.spotify import SpotifyClient
from spotdl.types.song import Song
class PlaylistError(Exception):
"""
Base class for all exceptions related to playlists.
"""
@dataclass(frozen=True)
class Playlist:
name: str
url: str
t... |
#!/usr/bin/env python3
"""
Optimization transforms are special modules that take gradients as inputs
and output model updates.
Transforms are usually parameterized, and those parameters can be learned by
gradient descent, allow you to learn optimization functions from data.
"""
from .module_transform import ModuleTra... |
from datetime import datetime
from typing import Any, Optional
from phx_events.phx_messages import ChannelEvent, ChannelMessage, PHXEvent, PHXEventMessage, PHXMessage, Topic
def parse_event(event: ChannelEvent) -> ChannelEvent:
try:
return PHXEvent(event)
except ValueError:
return event
def... |
import copy
import numpy as np
from scipy.sparse import csgraph
import datetime
import os.path
import argparse
import yaml
from sklearn.decomposition import TruncatedSVD
from sklearn import cluster
from sklearn.decomposition import PCA
from conf import sim_files_folder, save_address
from util_functions import *
from A... |
from datetime import datetime
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.utils.translation import ugettext as _
class RegisterForm(UserCreationForm):
birth_date = forms.DateField(
required=... |
import pytest
from pyregions.database.ponydatabase import sql_entities, region_database as rdb
from pyregions import standard_definition as sd
from pony.orm import db_session
import datetime
from loguru import logger
import importlib
@pytest.fixture
def empty_database(tmp_path)->rdb.RegionDatabase:
rdb.sql_entities =... |
#!/usr/bin/env python
from telnetlib import Telnet
import io
import datetime
import re
import xml.etree.cElementTree as ET
def test2():
root = ET.Element("root")
orbitRoot = ET.Element("root")
bodyList = [b'10',b'301']
now = datetime.datetime.now()
print("Accessing JPL Horizons via Telnet")
tn ... |
from model.key import *
from util.logger import get_logger
from util.keys import replace_nonprintable
class KeyExtractor:
keys = {}
logger = get_logger(__name__)
@staticmethod
def process_transactions(transactions):
for tx in transactions:
KeyExtractor._merge_results(
... |
from uwimg import *
# 1. Getting and setting pixels
im = load_image("data/dog.jpg")
for row in range(im.h):
for col in range(im.w):
set_pixel(im, col, row, 0, 0)
save_image(im, "dog_no_red")
# 3. Grayscale image
im = load_image("data/colorbar.png")
graybar = rgb_to_grayscale(im)
save_image(graybar, "grayb... |
#!/bin/python3
import sys
# Hackerrank Python3 environment does not provide math.gcd
# as of the time of writing. We define it ourselves.
def gcd(n, m):
while m > 0:
n, m = m, n % m
return n
def lcm(x, y):
return (x * y) // gcd(x, y)
def between(s1, s2):
import functools
cd = functools.... |
def fib():
a, b = 1, 1
while True:
yield b
a, b = b, a + b
def pares(seq):
for n in seq:
if n % 2 == 0:
yield n
def menores_4M(seq):
for n in seq:
if n > 4000000:
break
yield n
print (sum(pares(menores_4M(fib()))))
|
import argparse
import asyncio
import atexit
import contextlib
import os
import socket
import ssl
import subprocess
import sys
import tempfile
import time
from collections import namedtuple
from urllib.parse import urlencode, urlunparse
import pytest
import aioredis
import aioredis.sentinel
TCPAddress = namedtuple("... |
# 高雄市公有路外停車場一覽表
import sys
import urllib.request
import json
import csv
def fetch(query_limit):
# 指定查詢筆數上限
url = 'http://data.kcg.gov.tw/api/action/datastore_search?resource_id=cd53c749-abeb-47db-b58c-5954d6c337a1'
if query_limit > 0:
url = url+'&limit={}'.format(query_limit)
req = urllib.reque... |
import os
import sys
import argparse
import json
from fractions import Fraction
from typing import List, Tuple, Dict, Set
from random import sample, choice, randint
from soadata import DataSystem, DataSystemConfig, ServiceCost
if not (sys.version_info.major == 3 and sys.version_info.minor >= 5):
print("This script... |
# Generated by Django 3.1.12 on 2021-07-05 15:13
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('category', '0002_category_color'),
('board', '00... |
# start of importing
import os
import logging
from emoji import emojize
from gettext import gettext as _
from gettext import translation
from telegram import InlineKeyboardButton, InlineKeyboardMarkup,\
KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import (
Updater,
CommandHan... |
def GenerateConfig(context):
resources = [{
'name': context.properties['infra_id'] + '-bootstrap-public-ip',
'type': 'compute.v1.address',
'properties': {
'region': context.properties['region']
}
}, {
'name': context.properties['infra_id'] + '-bootstrap',
... |
from datetime import timedelta
import hikari
import lavasnek_rs
import tanjun
from avgamah.core.client import Client
from avgamah.utils.buttons import DELETE_ROW
from avgamah.utils.time import pretty_timedelta_shortened
from . import fetch_lavalink
now_playing_component = tanjun.Component()
@now_playing_component... |
import threading
import sys
import time
a = 0
b = 0
def lidar():
global a
while True:
a += 1
time.sleep(0.25)
def ir():
global b
while True:
b += 1
time.sleep(0.5)
# creating threads
sensor1 = threading.Thread(target=lidar)
sensor2 = threading.Thread(target=ir)... |
# pylint: disable=missing-function-docstring
from typing import List
import torch
def sample_data(counts: List[int], dims: List[int]) -> List[torch.Tensor]:
return [torch.randn(count, dim) for count, dim in zip(counts, dims)]
def sample_means(counts: List[int], dims: List[int]) -> List[torch.Tensor]:
return... |
from bs4 import BeautifulSoup
soup = BeautifulSoup('<html><p>line 1</p><div><a>line 2</a></div></html>', features="lxml")
print(soup.find('p').nextSibling.name)
|
import math
import numpy as np
import torch
from torch import nn as nn
from torch import einsum
import torch.nn.functional as F
from config import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from .helpers import build_model_with_cfg
from .layers import SelectiveKernelConv, ConvBnAct, create_attn
from .registry import r... |
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: jupyter_notebooks/Test_trainer.ipynb
from uti.interface import *
class Trainer():
'''Take interface, which is preprocessed data
create lear... |
from fractions import Fraction
from functools import reduce
from fractions import gcd
def product(fracs):
n = reduce(lambda x, y: Fraction(x.numerator*y.numerator, 1), fracs)
d = reduce(lambda x, y: Fraction(1, x.denominator*y.denominator), fracs)
g = gcd(n.numerator, d.denominator)
return n.numerator... |
# ----------------------------------------------------------------------
# Copyright (c) 2013-2016 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including... |
# https://www.acmicpc.net/problem/2110
if __name__ == "__main__":
N, C = map(int, input().split())
nums = []
for _ in range(N):
nums.append(int(input()))
nums.sort()
minDist, maxDist = 1, nums[-1] - nums[0]
bestDist = minDist
while maxDist >= minDist:
cur, count = nums[0], ... |
# *-* coding: utf-8 *-*
from threading import Thread
from subprocess import Popen, PIPE
import numpy as np
from .logger import Logger
## A class for capturing raw frames from the virtual framebuffer
class FrameCapturer(Thread):
def __init__(self, raw_frame_queue, loglevel, display_num, width, height, depth, fps):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.