content stringlengths 5 1.05M |
|---|
import asyncio
import json
import os
import re
import signal
import tempfile
import zof
# zof <---------+
# | |
# exabgp |
# | |
# bgp_tunnel -----+
APP = zof.Application('bgp')
class BGPNeighbor:
"""Represents a peer connection to a BGP neighbor."""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: parser.py
# modified: 2019-09-09
import re
from lxml import etree
from .course import Course
_regexBzfxSida = re.compile(r'\?sida=(\S+?)&sttp=(?:bzx|bfx)')
def get_tree_from_response(r):
return etree.HTML(r.text) # 不要用 r.content, 否则可能会以 latin-1 编码
def ... |
import matplotlib.pyplot as plt
import numpy as np
import itertools
from icubam.analytics import plots
data_source = ["bedcounts"]
FIG_NAME = 'BAR_BEDS_PER'
def plot(data, **kwargs):
all_plots = {}
for col_prefix, n_days in itertools.product(('n_covid', 'n_ncovid'),
... |
# -*- coding: utf-8 -*-
"""
chemdataextractor.parse.tg
~~~~~~~~~~~~~~~~~~~~~~~~~~
Glass transition temperature parser.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import re
from .cem import ce... |
originalList = [1, 3, 5, 2, 6, 3]
newList = originalList
for i in range(6):
print(newList[i])
print(originalList[i])
newList.remove(newList[i])
print(newList)
|
import angr
import simuvex
from decision_graph.compacting.constraint_normalizer import normalize_constraint
proj = angr.Project('../../cyborg-generator/bins/challenges_qualifiers/KPRCA_00052/bin/KPRCA_00052', load_options={"auto_load_libs": False})
add_options = {simuvex.o.CGC_NO_SYMBOLIC_RECEIVE_LENGTH}
add_options... |
#!/usr/bin/env python
from vogue.constants.constants import LANE_UDFS
def instrument_info(adapter, year: int, metric: str) -> dict:
"""Prepares data for a plot Q30 values for diferent runs over time"""
instruments = {"axis": {"y": "Average Q30"}, "data": {p: {} for p in LANE_UDFS}, "title": "Q30"}
pipe =... |
#! /usr/bin/env python3
from abc import abstractmethod
import numpy
from rl.agents.agent import Agent
class PolicyAgent(Agent):
"""
The policy agents main purpose is to implement the acting method.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@abstractmeth... |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from resnet import resnet
class Dataset:
def __init__(self, filename):
data = np.load(filename)
self._images = data["images"]
self._labels = data["labels"] if "labels" in data else None
self._m... |
from prl.storage.storage import Memory, History, Storage
|
from django.db import models
from django.conf import settings
import uuid
class MeetingNoticeMail(models.Model):
""" Meeting Notice Email """
ts = models.DateTimeField(auto_now_add=True)
place = models.CharField(max_length=32, default="AK219")
time = models.TimeField(default="17:00")
date = model... |
"""Component that will help set the Dlib face detect processing."""
import logging
import io
# pylint: disable=import-error
import face_recognition
import voluptuous as vol
from homeassistant.core import split_entity_id
from homeassistant.components.image_processing import (
ImageProcessingFaceEntity,
PLATFOR... |
# -*- coding: utf-8 -*-
class QueryParamParserBase(object):
def parse(self, fields):
raise NotImplementedError
class UnderlineQueryParamParser(QueryParamParserBase):
"""
Parses string like 'user__id,user__city,user__city__name,first_name,job' to dictionary
"""
def parse(self, fi... |
# Generated by Django 2.1.8 on 2019-06-11 13:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('steambird', '0010_auto_20190608_1208'),
]
operations = [
migrations.AlterField(
model_name='coursestudy',
name='stud... |
import os
import math
import cv2
import numpy as np
from frames import LOG
from frames.hashing import create_imghash, ImageHash, video_frame_by_frame
from bw_plex.misc import to_time
from frames.db import session_scope, Reference_Frame
def to_time(sec):
if sec == -1:
return '00:00'
m, s = divmod(se... |
from typing import List
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pyspawn._graph.graph_builder import GraphBuilder
from pyspawn._graph.temporal_table import TemporalTable
from pyspawn._graph.table import Table
from pyspawn import Checkpoint
from pyspawn.adapters._db_adapter import DbAdapte... |
"""tools to analyze interferometric data."""
import warnings
import inspect
from scipy import signal, optimize
from .conf import config
from .mathops import engine as e
from ._phase import OpticalPhase
from .zernike import defocus, zernikefit, FringeZernike
from .io import read_zygo_dat, read_zygo_datx, write_zygo_as... |
def check_ci(*args, **kwargs):
"""this method trying to parse README.md and find
badge which is point to CI provider
"""
result = len(list(filter(lambda x: content.find(
'{0}/{1}'.format(x, repo)) != -1, ci))) > 0
output('Checking Badge for CI', result)
self.score.add_check('Checking Bad... |
import maestroflow as mf
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import sys
import tkinter as Tk
# Set up tkinter
root = Tk.Tk()
f = plt.figure()
canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw()
canva... |
import xarray as xr
import numpy as np
import pandas as pd
def distrib_run_build_beam_pointing_vector(dat: list):
"""
Convenience function for mapping build_beam_pointing_vectors across cluster. Assumes that you are mapping this
function with a list of data.
distrib functions also return a processin... |
from termcolor import colored
import datetime
import sys
def section(msg):
print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"]), file=sys.stderr)
def task(msg):
print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"]), file=sys.stderr)
def subtask(msg):
print(color... |
import datetime
import os
import time
import discord
import motor.motor_asyncio
import nest_asyncio
import requests
from discord.ext import commands, tasks, timers
from discord.ext.commands import BucketType, cooldown
from pymongo import MongoClient
nest_asyncio.apply()
mongo_url = os.environ.get("MONGO_URL")
cluster... |
import cv2 # this is for opencv which our program uses to process the image that we're running color detection on
import numpy as np
import pandas as pd # use pandas to read csv file which contains our color library
import argparse # this is the argument parser which allows us to take the image pa... |
Triangle Count from Array Program In Python
An array of N integers is passed as the input to the program. The program must print the count of triangles that can be formed with the given integer values.
Note: Sum of any two sides in a triangle must be greater than the third side.
Boundary Condition(s):
3 <= N <= 500
1... |
#!/usr/bin/env python
'''
This example covers different ways to input basis
1. A universal basis set for all elements.
2. Different basis for different elements.
3. Different basis for same elements (different atoms).
4. Default basis for all elements, except the given basis of specific element.
5. gto.basis.parse and... |
# Generated by Django 3.1.13 on 2021-10-22 12:55
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('outdoor', '0034_auto_20211022_1255'),
]
operations = [
migrations.AlterField(
model_name='course',
name... |
#!/usr/bin/env python
# Copyright (c) 2014 - 2018 Mateo Rojas-Carulla [mrojascarulla@gmail.com]
# All rights reserved. See the file COPYING for license terms.
import autograd.numpy as np_aut
import autograd
import numpy as np
import scipy as sc
from scipy import io
from scipy.spatial.distance import pdist, squaref... |
# coding=utf-8
__all__ = ['switch_mode']
from force import mapping
def switch_mode(mode, exit_action=None):
return ('切换到 {0} 模式'.format(mode.MODE),
lambda _: mapping.mode_switch(mode, exit_action))
|
# Copyright 2014 OpenStack Foundation
# 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 requ... |
import os
import logging
import warnings
import torch
warnings.filterwarnings('ignore') # sklearn
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
logging.getLogger('tensorflow').setLevel(logging.FATAL)
from transformers import logging
logging.set_verbosity_error()
import sys
temp_dir = os.path.dirname(os.path.realpath(__fi... |
# -*- coding: utf-8 -*-
#!/usr/bin/python3
__author__ = "Richa Bharti"
__copyright__ = "Copyright 2019-2022"
__license__ = "MIT"
__version__ = "0.1.0"
__maintainer__ = "Richa Bharti, Dominik Grimm"
__email__ = "richabharti74@gmail.com"
__status__ = "Dev"
import pandas as pd
import numpy as np
import ar... |
# This file is Copyright (c) 2013-2014 Sebastien Bourdeauducq <sb@m-labs.hk>
# This file is Copyright (c) 2014-2019 Florent Kermarrec <florent@enjoy-digital.fr>
# This file is Copyright (c) 2018 Dolu1990 <charles.papon.90@gmail.com>
# This file is Copyright (c) 2019 Gabriel L. Somlo <gsomlo@gmail.com>
# This file is Co... |
from django.test import TestCase
# Create your tests here.
class addtestcase(TestCase):
def test_simple_addition(self):
self.assertEquals(5, 3 + 2)
|
import math
from qlazy import QState
def main():
print("== phase prediction == ")
# prepare initial state
qs_0 = QState(1)
qs_psi = QState(1).h(0)
qs = qs_0.tenspro(qs_psi)
# circuit for hadamard test
qs.h(0)
qs.crx(0,1,phase=0.5)
qs.h(0)
shots = 1000
md = qs.m([0]... |
import os
from settings.base import INSTALLED_APPS, MIDDLEWARE_CLASSES, TEMPLATE_CONTEXT_PROCESSORS
DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
#To show debug toolbar or not. Only shows on debug == True
def custom_show_toolbar(request):
return DEBUG
INSTALLED_APPS += (
'debug_toolbar'... |
# ------------------------------------------------------------------------------------
# Tutorial: Learn how and when to use virtual environments
# ------------------------------------------------------------------------------------
# What is a Virtual Environment
# A virtual environment allows you to create a directo... |
import soco_openqa.helper as helper
from soco_openqa.soco_mrc.mrc_model import MrcModel, MrcRerankerModel
from collections import defaultdict
import numpy as np
class Reader(object):
def __init__(self, config):
gpu_request = config.param.n_gpu
n_gpu = helper.find_device(gpu_request)
print(... |
S = input()
l = len(S)
nhug = 0
for i in range(l//2):
if S[i] != S[l-1-i]:
nhug += 1
print(nhug)
|
"""
Functions to compile a set of CPPA3 documents into data structures that facilitate
efficient lookup at runtime for inbound or outbound message exchange.
For an Endpoint, compute the Channels that use them and from there the Actions bound
to them.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
from... |
import base64
import io
import os
import dash
from dash.dependencies import Input, Output, State
from dash import dcc
from dash import html
from dash import dash_table
from flask import Flask, send_file
from flaml import AutoML
import pickle
import hashlib
from sklearn.model_selection import train_test_split
import ... |
def moveElementToEnd(array, toMove):
# Write your code here.
start=0
end=len(array)-1
while(start<end):
while array[start]!=toMove and start<len(array)-1:
start+=1
while array[end]==toMove and end>0:
end-=1
if start<end:
array[start], array[... |
# flake8: noqa
import os.path as osp
from basicsr.train import train_pipeline
import gfpgan.archs
import gfpgan.data
import gfpgan.models
if __name__ == '__main__':
root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir))
train_pipeline(root_path)
|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
""" Finetunes BART and GPT2 model with the canonical utterance generation task. """
import itertools
import os
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any, ... |
import numpy as np
import pandas as pd
import time
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import SVC
from SVM import... |
#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 1
# This program is optimized for Python 2.7.
# It may run on any other version with/without modifications.
import socket
import struct
import sys
import time
NTP_SERVER = "0.uk.pool.ntp.org"
TIME1970 = 2208988800L
def sntp_client(... |
import logging
# create logger
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
def fib(n):
first = 0
second = 1
for x in range(n):
print(first)
first, second = second, first+second
if __name__ == "__main__":
logging.debug("Calling fib(3)")
fib(3)
... |
#!/usr/bin/env python
"""This module defines basic device tapes and enumerations of the optigatrust package """
# pylint: skip-file
from enum import IntEnum
class Rng(IntEnum):
TRNG = 0
DRNG = 1
class Curves(IntEnum):
SEC_P256R1 = 0x03
SEC_P384R1 = 0x04
SEC_P521R1 = 0x05
BRA... |
# coding: utf-8
import os
from os.path import join, exists
import time
import cv2
import numpy as np
#from .cnns import getCNNs
def logger(msg):
"""
log message
"""
now = time.ctime()
print("[%s] %s" % (now, msg))
def createDir(p):
if not os.path.exists(p):
os.mkdir(p)
#shuffle i... |
# -*- encoding:utf-8 -*-
"""期货度量模块"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from ..CoreBu import ABuEnv
from ..ExtBu.empyrical import stats
from ..MetricsBu.ABuMetricsBase im... |
from webserver.utilities.configuration import configuration
from webserver.tasks import task_keeper
# Make celery find the task dependent on the worker type
if configuration['celery']['celery_worker_type'] == "seqvec":
# noinspection PyUnresolvedReferences
from webserver.tasks.seqvec_embeddings import get_seqv... |
"""
Example script that identifies old Sanger URLs in all Wikipedia pages linked from
Rfam families.
Usage: python pwb.py update_sanger_urls
"""
import pywikibot
from rfam_db import get_rfam_wiki_pages
def main():
site = pywikibot.Site('en', 'wikipedia')
for page in get_rfam_wiki_pages():
wiki = ... |
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from nautobot.utilities.api import get_serializer_for_model
from nautobot.extras.models import Webhook, ObjectChange
from nautobot.extras.registry import registry
from nautobot.extras.tasks import process_webhook
from nautobot... |
# -*- coding: utf-8 -*-
from sys import argv
script, file_name = argv
#Warning the user
print "We're going to erase %r." % file_name
print "If you don't want that, hit CTRL+C (^C)."
print "If you do want that, hit RETURN (ENTER)."
raw_input('?')
print "Opening the file"
txt_file = open(file_name, "w")
print "Trunca... |
# encoding=utf8
from __future__ import unicode_literals
import pyramid.testing
import pyramid_mailer
import pytest
import sw.allotmentclub.browser.app
import sw.allotmentclub.browser.testing
import sw.allotmentclub.conftest
DEFAULT_SETTINGS = {
'beaker.lock_dir': '/tmp',
'https_disabled': 'true',
'public_... |
from django.apps import AppConfig
class AppointmentsConfig(AppConfig):
name = 'phandler.appointments'
|
# Copyright (c) 2015. Mount Sinai School of Medicine
#
# 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 o... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import pytest
import simple_bayes
from simple_bayes import english_tokenizer
# Fixtures ================================================================... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-10-21 09:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('insta', '0008_remove_image_profile'),
]
operations = [
migrations.AddField... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from congress_api.models.base_model_ import Model
from congress_api.models.bill_version_metadata import BillVersionMetadata
from congress_api import util
from congress... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import stats
def plot_bivariate(U,V,Z):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(U,V,Z)
plt.show()
class empirical():
"""
Bivariate... |
# -*- coding: utf-8 -*-
# Copyright 2012 Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your ... |
from datetime import timedelta
from decimal import Decimal
import uuid
from django.db import models
from django.contrib import admin
from django.contrib.postgres.fields import JSONField
from django.utils import timezone
from simple_history.models import HistoricalRecords
from search.exceptions import ValueNotFoundErr... |
# Python AR.Drone 2.0
#
# Copyright (C) 2013 Quadeare <lacrampe.florian@gmail.com>
# Twitter : @quadeare
from pygame import *
import pygame
import libardrone
import threading
import time
from subprocess import call
import signal
import sys
class video(threading.Thread):
"""Video class to launch media flux""... |
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from flytekit import task, workflow
@dataclass_json
@dataclass
class DataclassA:
a: str
b: int
@task
def t(dca: DataclassA):
print(dca)
@workflow
def wf(dca: DataclassA = DataclassA("hello", 42)):
t(dca=dca)
|
import os
import cv2
import random
import numpy as np
import torch
import argparse
from shutil import copyfile
from utils.utils import Config, Progbar, to_cuda, postprocess, stitch_images, imsave
from src.metrics import get_sketch_metrics
from utils.logger import setup_logger
from torch.utils.data import DataLoader
fro... |
"""Integration tests for esmf_regrid."""
|
import os
import sys
import time
from parse_arguments import get_parsed_arguments
from step1_cells_spatial_mapping.run_cells_spatial_mapping import run_cd_cc
from step2_coexpression_analysis.run_coexpression_analysis import run_coexp
from step3_mark_composite_images.AnnotateMifImage import AnnotateMifImage
from step0_... |
import yaml
# don't dump with aliases
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True # type: ignore
def str_presenter(yaml_dumper, data):
"""Use block style for multiline strings"""
if len(data.splitlines()) > 1: # check for multiline string
return y... |
#Use right set of switches
import RPi.GPIO as GPIO
import time
vibration_pin = 13
GPIO.setmode(GPIO.BOARD)
#turn on vibration
GPIO.setup(vibration_pin, GPIO.HIGH)
#wait half a second
time.sleep(3)
#turn off vibration
GPIO.output(vibration_pin, GPIO.LOW)
#cleanup GPIO
GPIO.cleanup()
|
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from options.options import OptionDefaultValue
from utils.models import MyCharField, MyJSONField
from utils.shortcuts import default_username, default_user_id
class AdminType(object):
# 学生
St... |
# -*- coding: utf-8 -*-
import os
import re
import sys
from pyflakes.scripts import pyflakes
from cStringIO import StringIO
from django_jenkins.functions import relpath
from django_jenkins.tasks import BaseTask, get_apps_locations
class Task(BaseTask):
def __init__(self, test_labels, options):
super(Task,... |
# Solution of;
# Project Euler Problem 404: Crisscross Ellipses
# https://projecteuler.net/problem=404
#
# Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the
# rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0)
# for 0° < θ < 90°. b is the distance to the origin of the ... |
from browser import window
if hasattr(window, 'WebSocket'):
supported = True
WebSocket = window.WebSocket.new
else:
supported = False
def WebSocket(*args,**kw):
raise NotImplementedError |
import basicprogs as b
import boardstate_class as bsc
from inspect import signature # use this to check the "condition" argument
class rule:
def __init__(self, condition, rule_type, name='rule'):
if not callable(condition):
print('Error: condition argument must be a callable function')
raise(ValueError)
s... |
class User(object):
username = None
discriminator = None
avatar = None
def __init__(self, stores, id):
self._stores = stores
self.id = int(id)
def update(self, data):
self.id = int(data.get('id', self.id))
self.discriminator = int(data.get('discriminator', self.disc... |
# -*- coding: utf-8 -*-
import sys
import os
from pickle import NONE
import requests
from tqdm import tqdm
from rss_parser import RssParser
from ner import NER
import kss
import json
SERVER_URL = 'http://localhost:8080/news'
'''
개체이름:
사람이름(PER), 지명(LOC),
기관명(ORG), 기타(POH)
시간표현:
날짜(DAT), 시간(TI... |
import datetime
import tempfile
from pytest import raises
from passthesalt.model import DateTime, Model
class TestDateTime:
def test___init__(self):
example = DateTime(validators=[])
assert example.validators == []
assert not hasattr(example, 'format')
def test_serialize(self):
... |
#!interpreter [optional-arg]
# -*- coding: utf-8 -*-
#
"""
task_routes.py
"""
#Built-in/Generic
import datetime
#Libs
from flask import Flask, g, redirect, render_template, request, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import (
Table, Column, Integer, Strin... |
"""Simple example of two Python functions playing pingpong with messages."""
from AHPGraph import *
from AHPGraph.examples.pingpong.architecture import architecture
class Ping():
"""Example class that sends a ping."""
def __init__(self, name: str, repeats: int):
"""Init."""
self.name = name
... |
import pkgutil
import sys
from fly.http.headers import Headers
from fly.http.request import Request
from fly.http.response import Response
from fly.spider import Spider
from fly.settings import Settings
from fly.utils.log import Logger
__all__ = [
'__version__', 'version_info',
'Headers', 'Request', 'Response... |
# Generated by Django 2.2.9 on 2020-08-03 10:12
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_auto_20200721_1707'),
]
operations = [
migrations.AlterField(
model_name='post',
... |
__name__ = "pydatatable"
__version__ = "1.2"
__developer__ = "Siddhesh Chavan"
__doc__ = """
Library to create graphical Tables from the given data. This library is made by Siddhesh Chavan!
Import Statement:
import pydatatable
Documentation(Tutorial):
For documentation go to https://github.com/Sid7202... |
from __future__ import absolute_import
from pymatgen import Element
class SHELXElement:
"""
Define class to hold information about an element in the context of a SHELX File
"""
def __init__(self, name, stoichiometry, index):
self.name = name
self.nominal_stoichiometry = stoichiometry
... |
"""
Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
"""
class Stack:
def __init__(self):
self._arr = []
self._min_arr = []
def is_empty(self):
return not... |
#! /usr/bin/env python
import re
pattern = re.compile(r'(\d+)\-(\d+) (\w): (.*)')
total = 0
with open('input.txt', 'r') as f:
for line in f:
least, most, ch, password = pattern.findall(line.strip())[0]
if int(least) <= password.count(ch) <= int(most):
total += 1
print(total)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TRIE 모듈
__author__ = 'Jamie (jamie.lim@kakaocorp.com)'
__copyright__ = 'Copyright (C) 2018-, Kakao Corp. All rights reserved.'
"""
###########
# imports #
###########
import argparse
import codecs
import logging
import struct
import sys
#############
# constants ... |
#!/usr/bin/env python3
from optparse import OptionParser
from os import system
def parse_command_line_arguments():
parser = OptionParser()
parser.add_option("-i", "--install", action="store_true", dest="install", default=False, help="Run npm install to download dependencies of the project.")
parser.add_op... |
import contextlib
import io
import os
import sys
from Bio import PDB
def load_pdb_file(pdb_file):
parser = PDB.PDBParser()
pdb_name = ''.join(os.path.splitext(os.path.basename(pdb_file))[:-1])
return parser.get_structure(pdb_name, pdb_file)
@contextlib.contextmanager
def capture():
"""
Thank yo... |
def get_input_string():
# stmt = ("Akash is hospitalized.")
# stmt = "Akash is hospitalized. He is not taken to ABC hospital. Patient did not get any proper treatment.".lower()
stmt = "so high our experience so far has been a little bit difficult when you have a teenage child that is stuck in the house for... |
from django.urls import path
from . import views
# /products/1/detail
# /products/new
# map the root url of "products" to this function
urlpatterns = [
path('',views.index), #this represents the root of the products app
path('new',views.new)
] |
from db.scaffold import Scaffold
from pyrogram import types
from telegram import models as tg_models
class UpdateMessageAndView(Scaffold):
def update_message_and_view(
self,
*,
db_chat: 'tg_models.Chat',
raw_message: types.Message,
logger_account: "tg_m... |
class Solution:
def countBits(self, num: int) -> List[int]:
res = [0]
while len(res) <= num:
res += [x+1 for x in res]
return res[:num+1] |
from ..schema.users.models import *
from .generic import GenericService
__all__ = ['UserService']
class UserService(GenericService):
__model__ = User
|
from selenium import webdriver
from time import sleep
import pytest
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service as ChromeService
options = webdriver.ChromeOptions()
options.add_experimenta... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Port(pulumi.CustomResource):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def multiplication():
mp = 1
a = int(input("Enter the number: "))
while a != 0:
mp *= a
a = int(input("Enter the number: "))
return mp
if __name__ == '__main__':
print(f"The multiplication of entered numbers is: {multiplication()}") |
version_info = (2, 3, 3)
version = '.'.join(map(str, version_info))
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from jobbing.models.base_model_ import Model
from jobbing import util
class Category(Model):
"""NOTE: This class is auto generated by the swagger code generator p... |
# Accesing elements in a list
list_a = ['phy','chem',1998,2000];
list_b = [1,2,3,4,5,6,7,8,9];
print("list_a[2] is:",list_a[2]);
print(list_b[2:7]);
#updating lists
print("updation");
print(list_a[1]);
list_a[1] = "math";
list_b.append("hello"); #append to add an element to the list
print(list_a);
print(list_b);
#Del... |
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "access token"
access_token_secret = "access token secret"
consumer_key = "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.