filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_16405 | from cpf_cnpj import Documento
from TelefonesBr import TelefonesBr
from datasbr import DatasBr
from acesso_cep import BuscaEndereco
import requests
exemplo_cpf = "94561576010"
exemplo_cnpj = "35379838000112"
telefone = "11976453329"
cep = "01001000"
cpf_um = Documento.cria_documento(exemplo_cpf)
cnpj_um = Documento.c... |
the-stack_0_16406 | # Copyright 2015 CloudByte Inc.
# 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 required b... |
the-stack_0_16407 | from flask import Flask, render_template, request, redirect, url_for
from music_data_types import Artist, Song, Discography
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def render_page():
name = request.form['name']
option = r... |
the-stack_0_16408 | from Bio.Seq import Seq
from Bio.SeqUtils import nt_search, GC, molecular_weight
from Bio import SeqIO
seqobj = Seq("ATCGATATATACGCGAT")
print(seqobj.translate(to_stop=True))
patron = Seq("ACG")
resultado = nt_search(str(seqobj), patron)
print(resultado)
print(GC(seqobj))
print(molecular_weight(seqobj))
... |
the-stack_0_16409 | from __future__ import print_function
import json
import urllib
import boto3
import logging, logging.config
from botocore.client import Config
# Because Step Functions client uses long polling, read timeout has to be > 60 seconds
sfn_client_config = Config(connect_timeout=50, read_timeout=70)
sfn = boto3.client('step... |
the-stack_0_16410 | import math
def no_moving_vehicles(object_localizer_inference) -> bool:
no_movement_mdv_max_length = 3
for obstacle in object_localizer_inference:
if obstacle["label"] == "car" or obstacle["label"] == "bicycle":
mdv_length = math.sqrt(obstacle["mdv"][0]**2 + obstacle["mdv"][1]**2 + obstacle... |
the-stack_0_16411 | from datetime import timedelta
from flask import Flask, redirect, render_template, request, url_for
import json
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.wsgi import WSGIContainer
from webpixels import PixelSet, RgbPixel
from webpixels.controller import ColorKinetics
app ... |
the-stack_0_16415 | #!/usr/bin/env python3
import sys
import tempfile
import warnings
from lxml import etree as ET
def qname(ns, key, name):
if key in ns:
return "{{{}}}{}".format(ns[key], name)
return name
def create_naf(sofatext, sofaid, xminame):
naf = ET.Element("NAF")
naf.set('version', 'v1.naf')
naf.se... |
the-stack_0_16416 | from multiprocessing import Process, Queue
from Queue import Empty
from ansible_server import ansible_server
# DON'T USE THIS UNLESS YOU KNOW WHAT YOU'RE DOING
# Low level message sending. For high level messaging, use send_msg.
def send(msg):
send_queue.put_nowait(msg)
# Use this one instead of send
def send_mes... |
the-stack_0_16417 | from django import forms
from subscriptions.models import Subscription
from django.utils.translation import gettext as _
class SubscriptionForm(forms.ModelForm):
#STATUS_CHOICES IS SET TO BE LIKE STATUS_CHOICES IN SUBSCRIPTION MODEL BUT WITHOUT UKNOWN AND (UNKOWN) FOR USERS TO SELECT
STATUS_CHOICES = (
... |
the-stack_0_16418 | # pylint: skip-file
# flake8: noqa
# pylint: disable=wrong-import-position,too-many-branches,invalid-name
import json
from ansible.module_utils.basic import AnsibleModule
def _install(module, container, image, values_list):
''' install a container using atomic CLI. values_list is the list of --set arguments.
... |
the-stack_0_16419 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'han'
import os
import re
import zipfile
import spacy
import json
import h5py
import logging
import numpy as np
from functools import reduce
from utils.functions import pad_sequences
from .doc_text import DocText, Space
logger = logging.getLogger(__name__)
... |
the-stack_0_16420 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
`generalFunctions.py`
=================
Containing general purpose Python functions for small bits of manipulation.
Import it: import generalFunctions
Depends
=======
datetime
'''
import datetime
def empty(string):
if string in ['', ' ', None]:
return Tru... |
the-stack_0_16422 | # -*- coding: utf-8 -*-
"""Pyramid request argument parsing.
Example usage: ::
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from marshmallow import fields
from webargs.pyramidparser import use_args
hello_args = {
... |
the-stack_0_16424 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 09:45:44 2016
@author: Arturo
"""
import signal
import sys
import time
import pyupm_grove as grove
import pyupm_i2clcd as lcd
def interruptHandler(signal, frame):
sys.exit(0)
if __name__ == '__main__':
signal.signal(signal.SIGINT, interrup... |
the-stack_0_16426 | from unittest import TestCase
from tests import get_data
from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson
class StorageTestKT1JH9GCs3Y3kiLEuu2n9bAJev2UaGJbVaJX(TestCase):
@classmethod
def setUpClass(cls):
cls.maxDiff = None
cls.... |
the-stack_0_16428 | import sys # Needed for sys.argv
from typing import List, Dict, Set
from statistics import mean
import collections
import csv
def get_climate(in_filename: str, out_filename: str) -> None:
"""Read historical weather from in_filename, write climate to out_filename.
Parameters
----------
in_filename : ... |
the-stack_0_16429 | # Define shout with the parameter, word
def shout(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word= word + '!!!'
# Replace print with return
return shout_word
# Pass 'congratulations' to shout: yell
yell=shout('congratulations')
... |
the-stack_0_16430 | #!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class AppInfo:
def __init__(self):
self.app_root = ''
self.app_version = '1.0.0'
self.app_versionCode = ''
self.ful... |
the-stack_0_16433 | # pylint: disable=too-many-lines
import copy
import json
import os
import re
import six
from typing import Any, Optional, Dict, List, Set, Union # noqa
from typing import cast
import yaml
from yaml.scanner import ScannerError
from yaml.nodes import Node, ScalarNode, SequenceNode
from chalice.deploy.swagger import ... |
the-stack_0_16436 | import os
import logging
import random
from typing import List, Optional
import itertools
import numpy as np
from config import save_path
from ..abstract_system import abstract_system
from .controlloop import controlloop
class system(abstract_system):
def __init__(self, cl: List[controlloop], trap_state=False):... |
the-stack_0_16437 | # -*- coding: utf-8 -*-
import prefect # base import is required for prefect context
from prefect import task, Flow, Parameter
from prefect.storage import Module
from simmate.calculators.vasp.tasks.relaxation.third_party.mit import MITRelaxationTask
from simmate.workflows.common_tasks.all import load_input
from sim... |
the-stack_0_16438 | # -*- coding: utf-8 -*-
""" S3 Synchronization: Peer Repository Adapter for ADASHI
@copyright: 2011-2020 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), ... |
the-stack_0_16440 | """
Luna API.
API is written via FastAPI.
"""
from fastapi import FastAPI, HTTPException, Response
from pydantic import BaseModel
from typing import List, Optional
from natsort import natsorted, ns
from luna.db.db_util import DbConnection
from luna.db import bucket
from luna.db import vignette
from luna.db import cell... |
the-stack_0_16446 | # -*- coding: utf-8 -*-
class WriterRegistry:
def __init__(self, listener):
self.storage = {}
self.id = 0
self.next_id = 0
self.listener = listener
def get_id(self, value):
try:
value_id=self.storage[value]
return value_id
... |
the-stack_0_16451 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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 witho... |
the-stack_0_16453 | # Authors:
#
# Giorgio Patrini
#
# License: BSD 3 clause
from __future__ import division
import warnings
import itertools
import numpy as np
import numpy.linalg as la
from scipy import sparse, stats
from scipy.sparse import random as sparse_random
import pytest
from sklearn.utils import gen_batches
from s... |
the-stack_0_16454 | from django.urls import path
from .views import account_session, get_csrf, register, account_login, account_logout
urlpatterns = [
path('get_session/', account_session),
path('get_csrf/', get_csrf),
path('register/', register, name='account_register'),
path('login/', account_login, name="account_login... |
the-stack_0_16455 | import math
from typing import Tuple
import torch
import torch.nn as nn
from cached_property import cached_property
from torch.nn.modules.transformer import (
TransformerDecoder,
TransformerDecoderLayer,
TransformerEncoder,
TransformerEncoderLayer,
)
from kobe.data.dataset import Batched, EncodedBatch... |
the-stack_0_16457 | # -*- coding: future_fstrings -*-
class GroupUser:
group_user_access_right_key = 'groupUserAccessRight'
email_address_key = 'emailAddress'
display_name_key = 'displayName'
identifier_key = 'identifier'
principal_type_key = 'principalType'
def __init__(
self,
group_user_access_ri... |
the-stack_0_16458 | # -*- coding: ascii -*-
"""
app.utils
~~~~~~~~~
Utils. for the application.
"""
import re
import unicodedata
from functools import partial
from Levenshtein import distance
__all__ = [
'parse_db_uri',
'parse_citations',
'parse_doi',
'normalize',
'doi_normalize',
'matching'
]
# Find citations... |
the-stack_0_16461 | import operator
import re
import sys
from typing import Optional
from packaging import version
# The package importlib_metadata is in a different place, depending on the python version.
if sys.version_info < (3, 8):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
ops = {
... |
the-stack_0_16463 | #!/usr/bin/env python
# -*- coding: utf-8 -*
"""
:authors:
Guannan Ma @mythmgn
:create_date:
2016/06/07
:description:
heartbeat service
"""
from cup.services import heartbeat
class HeartbeatService(heartbeat.HeartbeatService):
"""
heartbeat service. not in use yet
"""
def __init__(self, ju... |
the-stack_0_16465 | # Copyright 2015-2017 ARM Limited
#
# 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... |
the-stack_0_16467 | import discord
from discord.ext import commands
import stackprinter as sp
from bin import zb
class onmemberremoveCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Events on member join
@commands.Cog.listener()
async def on_member_remove(self, member):
try:
# If... |
the-stack_0_16468 | '''
This script resets the escpos printer
'''
import sys
from escpos.printer import Usb
from escpos import exceptions
VENDOR_ID = 0x0456
PRODUCT_ID = 0x0808
P_INTERFACE = 4
P_IN_ENDPOINT = 0x81
P_OUT_ENDPOINT = 0x03
p = Usb(VENDOR_ID, PRODUCT_ID, P_INTERFACE, P_IN_ENDPOINT, P_OUT_ENDPOINT)
reset_cmd = b'\x1b?\n\x... |
the-stack_0_16469 | import setuptools
with open('README.md', 'r') as f:
long_description = f.read()
setuptools.setup(
name='jc',
version='1.17.1',
author='Kelly Brazil',
author_email='kellyjonbrazil@gmail.com',
description='Converts the output of popular command-line tools and file-types to JSON.',
install_re... |
the-stack_0_16472 | import numpy as np
from KPI import KPI
def calc(inp):
return inp[:, 9]
def gap(open_price, close_price, init_money):
return 1.0 * (close_price / open_price - 1) * init_money
def gap_colume(open_price, close_price, colume):
return 1.0 * (close_price - open_price) * colume
def RSI(data, paras, standard_da... |
the-stack_0_16473 | from __future__ import absolute_import, print_function
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from zerver.models import UserProfile
import argparse
from datetime import datetime
import requests
import ujson
from typing import Any
class ... |
the-stack_0_16474 | # -*- coding: utf-8 -*-
# website: http://30daydo.com
# @Time : 2019/10/24 0:03
# @File : new_stock_fund.py
# 获取打新基金数据
import requests
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common... |
the-stack_0_16475 | import numpy as np
from mygrad.operation_base import BroadcastableOp, Operation
__all__ = ["GetItem", "SetItem"]
class GetItem(Operation):
""" Defines the __getitem__ interface for a Tensor, supporting back-propagation
Supports back-propagation through all valid numpy-indexing (basic, advanced, mixed, ... |
the-stack_0_16477 | #!/usr/bin/env python
# Copyright 2018 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 ... |
the-stack_0_16478 | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from profiles_api import views
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset')
router.register('profile', views.UserProfileViewSet)
router.register('feed', views.User... |
the-stack_0_16479 | import os
from src.antlr_utils import parse
from src.grammar_cnf import GrammarCNF
import pytest
@pytest.mark.parametrize("grammar", [GrammarCNF.from_txt("dbql_grammar.txt")])
@pytest.mark.parametrize("test_input, expected", [
(
'''
connect "azat/home/db" ;
select edges
f... |
the-stack_0_16482 | from random import randint
from epidemic_simulation.simulation import SimulationManager
import pytest
@pytest.fixture
def test_data():
test_bodies=[{'position': (748, 634), 'state': 'INFECTIOUS'}, {'position': (1137, 351), 'state': 'SUSCEPTIBLE'}, {'position': (1017, 464), 'state': 'INFECTIOUS'}, {'position': (90... |
the-stack_0_16483 | # encoding: UTF-8
__author__ = 'CHENXY'
# C++和python类型的映射字典
type_dict = {
'int': 'int',
'char': 'string',
'double': 'float',
'short': 'int'
}
def process_line(line):
"""处理每行"""
if '///' in line: # 注释
py_line = process_comment(line)
elif 'typedef' in line: # 类型申明
... |
the-stack_0_16485 | import os
import pefile
import hashlib
import pickle
import time
import pandas as pd
from config import settings as cnst
from collections import OrderedDict
from utils import embedder
all_sections = OrderedDict({".header": 0})
def raw_pe_to_pkl(path, is_benign, unprocessed, processed):
list_idx = []
for src... |
the-stack_0_16487 | class Solution:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
St = []
remove = len(nums) - k
for num in nums:
while St and num < St[-1] and remove > 0:
St.pop()
remove -= 1
St.append(num)
return St[:len(St) - ... |
the-stack_0_16488 | from cpc import CPCStateMachine as CPCwithTG
from cpc import CPCStateMachineL4 as CPCwithTGL4
from cic.states import CICStateMachineLvl2 as CICwithCG
from cic.states import CICStateMachineLvl4 as CICwithCGL4
from cic.states import CICStateMachineLvl1 as CICwithCGL1
from mp.state_machines import MPStateMachine as MPwith... |
the-stack_0_16490 | """
(c) 2020 Spencer Rose, MIT Licence
Python Landscape Classification Tool (PyLC)
Reference: An evaluation of deep learning semantic segmentation
for land cover classification of oblique ground-based photography,
MSc. Thesis 2020.
<http://hdl.handle.net/1828/12156>
Spencer Rose <spencerrose@uvic.ca>, June 2020
Uni... |
the-stack_0_16491 | ## @ingroupMethods-Noise-Fidelity_One-Propeller
# noise_propeller_low_fidelty.py
#
# Created: Mar 2021, M. Clarke
# Modified: Jul 2021, E. Botero
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import SUAVE
fr... |
the-stack_0_16492 | from struct import pack, unpack
import hashlib
import sys
import traceback
from electrum import bitcoin
from electrum.bitcoin import TYPE_ADDRESS, int_to_hex, var_int
from electrum.i18n import _
from electrum.plugins import BasePlugin
from electrum.keystore import Hardware_KeyStore
from electrum.transaction import Tra... |
the-stack_0_16493 | import os
import random
import string
import time
from collections import defaultdict
from contextlib import contextmanager
import pendulum
import pytest
from dagster import (
Any,
Field,
ModeDefinition,
daily_partitioned_config,
fs_io_manager,
graph,
pipeline,
repository,
solid,
)... |
the-stack_0_16494 | # coding=utf-8
#
# Copyright 2015-2016 F5 Networks 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... |
the-stack_0_16495 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import inspect
from pandapower.auxiliary import _check_bus_index_and_print_warning_if_high, \
_check_gen_index_and_print_warn... |
the-stack_0_16496 | import argparse
import gym
import numpy as np
import os
import tensorflow as tf
import tempfile
import time
import json
import random
import rlattack.common.tf_util as U
from rlattack import logger
from rlattack import deepq
from rlattack.deepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer
from rlattack.... |
the-stack_0_16497 | # 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 ... |
the-stack_0_16500 | # Unwinder commands.
# Copyright 2015 Free Software Foundation, Inc.
# This program 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 option) any later version.
#
... |
the-stack_0_16501 | from collections import defaultdict
import errno
import math
import mmap
import os
import sys
import time
import multiprocessing as mp
from six.moves import range
import numpy as np
from .lib import Bbox, Vec, mkdir
SHM_DIRECTORY = '/dev/shm/'
EMULATED_SHM_DIRECTORY = '/tmp/cloudvolume-shm'
EMULATE_SHM = not os.pa... |
the-stack_0_16502 | # pcost.py
import report
def portfolio_cost(filename):
'''
Computes the total cost (shares*price) of a portfolio file
'''
portfolio = report.read_portfolio(filename)
return portfolio.total_cost
def main(args):
if len(args) != 2:
raise SystemExit('Usage: %s portfoliofile' % args[0])
... |
the-stack_0_16503 | # Copyright 2020 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
the-stack_0_16505 | import spidev, time
spi = spidev.SpiDev()
spi.open(0,0)
def analog_read(channel):
r = spi.xfer2([1, (8 + channel) << 4, 0])
adc_out = ((r[1]&3) << 8) + r[2]
return adc_out
while True:
reading = analog_read(0)
voltage = reading * 3.3 / 1024
print("Reading=%d\tVoltage=%f" % (reading, voltage))... |
the-stack_0_16506 | """
Compare two or more phasings
"""
import logging
import math
from collections import defaultdict
from contextlib import ExitStack
import dataclasses
from itertools import chain, permutations
from typing import Set, List, Optional, DefaultDict, Dict
from whatshap.vcf import VcfReader, VcfVariant, VariantTable, Ploid... |
the-stack_0_16507 | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... |
the-stack_0_16509 | import asyncio
import os.path
import time
import sys
import platform
import queue
import traceback
import os
import webbrowser
from decimal import Decimal
from functools import partial, lru_cache
from typing import (NamedTuple, Callable, Optional, TYPE_CHECKING, Union, List, Dict, Any,
Sequence, Ite... |
the-stack_0_16512 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0004_auto_20150820_2156'),
]
operations = [
migrations.AlterModelOptions(
name='product',
... |
the-stack_0_16513 | import argparse
import os
import shutil
import sys
import cv2
def label(img_dir, scale_factor):
img_extensions = {'jpg', 'jpeg', 'png', 'bmp'}
images = sorted([os.path.join(img_dir, f)
for f in os.listdir(img_dir)
if os.path.isfile(os.path.join(img_dir, f)) and
... |
the-stack_0_16514 | import tensorflow as tf
import abc
import logging
LOSS_REGISTRY = {}
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Default margin used by pairwise and absolute margin loss
DEFAULT_MARGIN = 1
# default sampling temperature used by adversarial loss
DEFAULT_ALPHA_ADVERSARIAL = 0.5
# Default ma... |
the-stack_0_16515 | import avroconvert as avc
from multiprocessing import cpu_count
import concurrent
class Execute:
def __init__(self, source: str, bucket: str, dst_format: str, outfolder: str, prefix: str = '', **kwargs):
'''
A wrapper class to run the avro convert operation. This class
calls the reader me... |
the-stack_0_16516 | import logging
import os
import subprocess
logging.basicConfig()
logger = logging.getLogger("kalliope")
MPLAYER_EXEC_PATH = "/usr/bin/mplayer"
class Mplayer(object):
"""
This Class is representing the MPlayer Object used to play the all sound of the system.
"""
def __init__(self):
pass
... |
the-stack_0_16518 | import os
import requests
import prometheus_client
import threading
import logging
import time
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, REGISTRY
PORT=9387
APIBASEURL = os.environ['SABNZBD_BASEURL']
APIKEY = os.environ['SABNZBD_APIKEY']
loggin... |
the-stack_0_16519 | from subprocess import call
isbn_regex = '^(97(8|9)-?)?\d{9}(\d|X)$'
def fix_author(author):
parts = author.split(u', ')
if len(parts) == 2:
return parts[1] + u' ' + parts[0]
return author
def call_mktorrent(target, torrent_filename, announce, torrent_name=None):
args = [
'mktorren... |
the-stack_0_16521 | # pylint: disable=R0913
# pylint: disable=W0621
import os
from urllib.parse import quote
import pytest
from aiohttp import web
from simcore_service_storage.db import setup_db
from simcore_service_storage.dsm import setup_dsm
from simcore_service_storage.rest import setup_rest
from simcore_service_storage.s3 import se... |
the-stack_0_16522 | from telegram import Update
from telegram.ext import CallbackContext
from app.extensions import db
from app.lib.handlers.base import BaseHandler, app_context
from app.models import Channel
class MigrateFilter(BaseHandler):
@app_context
def handler(self, update: Update, context: CallbackContext):
mess... |
the-stack_0_16526 |
from django.conf import settings
from zerver.lib.actions import set_default_streams, bulk_add_subscriptions, \
internal_prep_stream_message, internal_send_private_message, \
create_stream_if_needed, create_streams_if_needed, do_send_messages, \
do_add_reaction_legacy
from zerver.models import Realm, UserP... |
the-stack_0_16527 | # -*- coding: utf-8 -*-
import scrapy
"""
需求: 大分类:名称,URL; 小分类名称,URL; 图书的标题,图片,出版商,价格信息
步骤:
1. 创建爬虫项目
2. 创建爬虫
3. 完善爬虫
3.1 修改起始URL
3.2 提取大分类,小分类标题和URL, 根据小分类的URL构建列表页请求
3.3 解析列表页, 提取图书标题和封面图片的URL, 构建详情页的请求
3.4 解析详情页, 提取出版社, 价格(构建价格请求)
3.5 解析价格
3.6 实现列表页分页
"""
from copy import deepcopy
import re
class BookSpider(scra... |
the-stack_0_16528 | # This file is part of Sequana software
#
# Copyright (c) 2016 - Sequana Development Team
#
# File author(s):
# Thomas Cokelaer <thomas.cokelaer@pasteur.fr>
# Dimitri Desvillechabrol <dimitri.desvillechabrol@pasteur.fr>,
# <d.desvillechabrol@gmail.com>
#
# Distributed under the terms of the 3-cla... |
the-stack_0_16529 | from __future__ import print_function
import numpy as np
import nlcpy as vp
import numba
from math import *
import time
# target libraries
nb = 'numba'
vp_naive = 'nlcpy_naive'
vp_sca = 'nlcpy_sca'
@numba.stencil
def numba_kernel_1(din):
return (din[0, 0, -1] +
din[0, 0, 0] +
din[0, 0, 1]... |
the-stack_0_16531 | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various command line arguments and configuration file parameters."""
import os
from test_framework.te... |
the-stack_0_16532 | from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = raw_input("Input lower case senrence:")
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
cl... |
the-stack_0_16534 | # This config does not work with the version of DD4hep that uses Geant4 units. This config performs a comparison
# with a reference geometry which might use the ROOT units convention. This mismatch somehow triggers a ROOT exception.
# We don't currently have a fix for this problem.
import FWCore.ParameterSet.Config as... |
the-stack_0_16535 | """empty message
Revision ID: 09b6565cf4e7
Revises: 1aae34526a4a
Create Date: 2018-02-12 12:21:05.984927
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '09b6565cf4e7'
down_revision = '1aae34526a4a'
branch_labels = None
depends_on = None
def upgrade():
# ... |
the-stack_0_16537 | "This is the locale selecting middleware that will look at accept headers"
from django.conf import settings
from django.core.urlresolvers import (
LocaleRegexURLResolver, get_resolver, get_script_prefix, is_valid_path,
)
from django.http import HttpResponseRedirect
from django.utils import translation
from django.... |
the-stack_0_16538 | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2018
from __future__ import print_function
from future.builtins import *
import sys
import sysconfig
import os
import argparse
import streamsx.rest
def _stop(sas, cmd_args):
"""Stop the service if no jobs are running unless force is set"... |
the-stack_0_16539 | # -*- coding: utf-8 -*-
# Third party imports
import pytest
# Local application imports
from mosqito.sq_metrics import loudness_zwtv
from mosqito.utils import load
from validations.sq_metrics.loudness_zwtv.validation_loudness_zwtv import (
_check_compliance,
)
@pytest.mark.loudness_zwtv # to skip or run only l... |
the-stack_0_16541 | """
sentry.buffer.redis
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import six
from time import time
from binascii import crc32
from datetime import datetime
from django.db imp... |
the-stack_0_16543 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
_DETECTRON_OPS_LIB = 'libcaffe2_detectron_ops_gpu.so'
_CMAKE_INSTALL_PREFIX = '/usr/local'
HIGHEST_BACKBONE_LVL = 5
LOWEST_BACKBONE_LVL = 2
import argparse
import cv2 ... |
the-stack_0_16545 | import komand
from .schema import UpdateSiteIncludedTargetsInput, UpdateSiteIncludedTargetsOutput, Input
# Custom imports below
from komand_rapid7_insightvm.util import endpoints
from komand_rapid7_insightvm.util.resource_requests import ResourceRequests
import json
class UpdateSiteIncludedTargets(komand.Action):
... |
the-stack_0_16549 | #!/usr/bin/env python3
import os
import sys
import urllib.request
import tarfile
import zipfile
import shutil
from typing import List, Optional
PLATFORM_WINDOWS = "windows"
PLATFORM_LINUX = "linux"
PLATFORM_MACOS = "mac"
DOTNET_RUNTIME_VERSION = "6.0.0"
DOTNET_RUNTIME_DOWNLOADS = {
PLATFORM_LINUX: "https://down... |
the-stack_0_16550 | import yaml
import json
from os import listdir
from os.path import isfile, join
"""
{ name, kingdom, imageUrl}
"""
path = "./data/raw/image-url.yml"
stream = open(path, "r")
data = yaml.load_all(stream, yaml.Loader)
data_dicts = [
{
"name": datum["name"].lower(),
"kingdom": datum["kingdom"],
... |
the-stack_0_16551 | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
from tools.modeltool import *
from tools.tool import *
from tools.modeltool import *
from tools.tool import *
from tools.pathtool import *
from tools.milltask import *
from guifw.gui_elements import *
import sys, os, os.path
from solids import *
f... |
the-stack_0_16554 | # model settings
temperature = 0.01
with_norm = True
query_dim = 128
model = dict(
type='UVCNeckMoCoTrackerV2',
queue_dim=query_dim,
patch_queue_size=256 * 144 * 5,
backbone=dict(
type='ResNet',
pretrained=None,
depth=18,
out_indices=(0, 1, 2, 3),
# strides=(1, 2,... |
the-stack_0_16555 | # container-service-extension
# Copyright (c) 2017 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
"""Basic utility methods to perform data transformation and file operations."""
import hashlib
import os
import pathlib
import platform
import stat
import sys
from typing import List
import url... |
the-stack_0_16557 |
import pandas as pd
# Lists are enclosed in brackets:
# l = [1, 2, "a"]
# Tuples are enclosed in parentheses:
# Tuples are faster and consume less memory
# t = (1, 2, "a")
# Dictionaries are built with curly brackets:
# d = {"a":1, "b":2}
# Sets are made using the set() builtin function
# Python List vs. Tuples (K... |
the-stack_0_16560 | # Copyright 2021 The TensorFlow Probability 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 o... |
the-stack_0_16561 | from ..layout import Channel, Layout, load_speakers, load_real_layout, Speaker, RealLayout
from ..geom import cart, PolarPosition, CartesianPosition
from ...common import PolarScreen, CartesianScreen
from attr import evolve
import pytest
import numpy as np
import numpy.testing as npt
@pytest.fixture
def layout():
... |
the-stack_0_16562 | import collections
import logging
from typing import Dict, List, Optional, Set, Tuple, Union, Callable
from blspy import AugSchemeMPL, G1Element
from chiabip158 import PyBIP158
from clvm.casts import int_from_bytes
from chia.consensus.block_record import BlockRecord
from chia.consensus.block_rewards import (
calc... |
the-stack_0_16563 | #!/usr/bin/env python3
import sys
import torch
import logging
import speechbrain as sb
import torchaudio
from hyperpyyaml import load_hyperpyyaml
from speechbrain.tokenizers.SentencePiece import SentencePiece
from speechbrain.utils.data_utils import undo_padding
from speechbrain.utils.distributed import run_on_main
""... |
the-stack_0_16564 | # Test functionality of sellers side
from emarket.client_seller import ClientSeller
from emarket.emarket import Item
import time
from os import environ as env
from dotenv import load_dotenv, find_dotenv
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
else:
raise FileNotFoundError("Could not locat... |
the-stack_0_16565 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
long_description = """
branching_process
"""
config = dict(
description='hawkes process fitting',
author='Dan MacKinlay',
url='URL to get it at.',
download_url='Where to download it.',
author_email='My e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.