content stringlengths 5 1.05M |
|---|
from typing import Tuple
from pydantic import BaseSettings
from pydantic.env_settings import SettingsSourceCallable
class Settings(BaseSettings):
my_api_key: str
class Config:
@classmethod
def customise_sources(
cls,
init_settings: SettingsSourceCallable,
... |
import alsaaudio
class SoundManager(object):
try:
m = alsaaudio.Mixer()
except alsaaudio.ALSAAudioError:
# no master, we are on a Rpi
m = alsaaudio.Mixer("PCM")
@classmethod
def set_volume(cls, volume_level):
cls.m.setvolume(int(volume_level))
@classmethod
de... |
import logging
log = logging.getLogger("amaptor")
from amaptor.version_check import ARCMAP
if ARCMAP:
FileExistsError = OSError # define it for Python 2, basically raise an OSError in that case
FileNotFoundError = OSError
class MapExists(FileExistsError):
"""
Raised when a map or data frame already exists beca... |
import flask
from . import main
from .forms import MessageForm
from meli.morse.app.swagger import SWAGGER_URL
from meli.morse.domain.morse import MorseTranslator
TRANSLATOR = MorseTranslator()
@main.route('/', methods=['GET', 'POST'])
def index():
form = MessageForm()
if form.validate_on_submit():
tr... |
in_channels = None
out_channels = None
kernel_sizes = None
strides = None
from torch import nn
from torch.nn import functional as F
def swish(x):
return x * x.sigmoid()
def mish(x):
return x * F.softplus(x).tanh()
class Swish(nn.Module):
def __init__(self):
super().__init__()
def forward(s... |
import csv
import os
from collections import Counter
csvpath = os.path.join('resources', 'election_data.csv')
output_file = os.path.join('resources', 'Election_Results.txt')
with open(csvpath, 'r', newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
# Defines o... |
from PyREMOT.data.inputDataGeneral import *
from PyREMOT.data.inputDataReactor import *
from PyREMOT.data.initData import *
from PyREMOT.data.componentData import *
from PyREMOT.data.dataGasViscosity import *
|
import plotly.express as px
import matplotlib.pyplot as plt
data = px.data.iris()
fig, ax = plt.subplots()
species = ["setosa", "virginica", "versicolor"]
markers = ["d", "v", "s"]
colors = ['red', 'green', 'blue']
for s, m, c in zip(species, markers, colors):
ax.scatter(x="sepal_width", y="sepal_length", data=d... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import dash_table
from dash.exceptions import PreventUpdate
import flask
from flask import Flask
import pandas as pd
import dateutil.relativedelt... |
import numpy as np
#from pylab import *
import math
import scipy.linalg
#from cvxpy import *
#from qcqp import *
import pdb
def get_coefficient(G,S,method = 2):
try:
num_reward = G.shape[0]
coe = np.ones((num_reward))
H = np.dot(S, G.T)
SS = np.dot(S, S.T)
if method == 1:
... |
# encoding: UTF-8
'''
用到的vnpy的相关接口
'''
from __future__ import division
import logging
from datetime import datetime
import time
import numpy as np
import talib
# from vnpy.event import *
# from vnpy.event.eventType import EVENT_TIMER
# from vnpy.trader.vtObject import VtBaseData
# from vnpy.tra... |
from . import applicant_report
|
# Lint as: python3
# Copyright 2020, The TensorFlow Federated 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 ... |
from . import FullAtomModel
from . import Volume
from . import ReducedModel
from . import RMSD |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
INSTALLED_APPS = [
'constance',
'constance.backends.database',
'app',
'django.contrib.admin',
'django.contrib.auth',
'django... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-27 15:44
from tests.resources import res
CWS_DEBUG = res('tests/resources/cws/debug.txt')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Consul methods module."""
from hvac import exceptions, utils
from hvac.api.vault_api_base import VaultApiBase
DEFAULT_MOUNT_POINT = "consul"
class Consul(VaultApiBase):
"""Copnsul Secrets Engine (API).
Reference: https://www.vaultproject.io/api/secret/consul/... |
# Project: ChessEngineAASpr2022
# Author: Braden Stonehill
# Date: 03/24/2022
# Last Updated: 03/24/2022
# Version: 1.0
import chess
from Search import iterativedeepening
from Evaluate import eval, calculate, evaluateScore, calculateRapid
from Utilities import Memo
class Engine:
def __ini... |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/902/B
#通过三个列表(cl,pl,sl)实现了并查的部分思想.
n = int(input()) #1e4
pl = list(map(int,input().split()))
cl = list(map(int,input().split()))
pl = [0] + [p-1 for p in pl]
sl = [None]*n #None=unvisit, False=non-root, True=root
for i in range(n):
if sl[i... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from lxml import etree
def _parse_xml_file_keypoints(xml_file, max_size=320):
"""Get the keypoints and their id from a .xml file.
Arguments:
xml_file: String, the path to the .xml ... |
# -*- coding: utf-8 -*-
# This file is part of the OpenSYMORO project. Please see
# https://github.com/symoro/symoro/blob/master/LICENCE for the licence.
"""
This module contains the functions for the computation of Inertia
matrix.
"""
import sympy
from sympy import Matrix
from pysymoro.geometry import compute_r... |
import boto3
import pytest
from moto import mock_ec2, mock_elb, mock_elbv2, mock_s3
from cloud_governance.zombie_cluster.zombie_cluster_resouces import ZombieClusterResources
from cloud_governance.common.aws.ec2.ec2_operations import EC2Operations
tags = [
{'Key': 'kubernetes.io/cluster/unittest-test-cluster', 'Va... |
from nose.tools import eq_
from rdkit import Chem
from third_party.mordred import Calculator, Descriptor
from third_party.mordred.error import Error
class RaiseDescriptor(Descriptor):
def parameters(self):
return ()
def __init__(self, e, critical):
self.e = e
self.critical = critical... |
from typing import List
from pydantic import BaseModel, EmailStr, validator
from core.config import (
PASSWORD_ERROR_MESSAGE,
PASSWORD_MAX_LENGTH,
PASSWORD_MIN_LENGTH,
USERNAME_ERROR_MESSAGE,
USERNAME_MAX_LENGTH,
USERNAME_MIN_LENGTH,
)
from models.base import DBModel, WithLicense
# Shared prop... |
import typing
def main() -> typing.NoReturn:
n = int(input())
a = list(map(int, input().split()))
a.sort()
y = a[n - 1]
x = -1
mx = 0
for j in range(n - 1):
d = min(a[j], y - a[j])
if d < mx: continue
x = a[j]
mx = d
print(y, x)
main() |
"""Download and reformat the MIT ECG database.
This script downloads a subset of the MIT-BIH Arrhythmia Database.
Note that rerunning might change the pickle files.
However, it is very likely that these changes are only caused by small differences in the compression.
These changes should not be committed to git again... |
import heterocl as hcl
import hlib
import numpy as np
import numpy.testing as tst
def elemwise_test(in_size, func, dtype):
hcl.init(dtype)
in1 = hcl.placeholder(in_size)
in2 = hcl.placeholder(in_size)
def elem_func(in1, in2):
return func(in1, in2)
s = hcl.create_schedule([in1, in2], elem_f... |
import aquests
def request_finished (r):
print (r.cookie)
def test_cookie ():
aquests.configure (1, cookie = True, callback = request_finished)
aquests.get ("https://www.google.co.kr/?gfe_rd=cr&ei=3y14WPCTG4XR8gfSjoK4DQ")
aquests.get ("https://aws.amazon.com/")
aquests.fetchall ()
|
# Copyright 2014. Amazon Web Services, 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 by applicab... |
#!/usr/bin/env python
'''
Send Cluster Metrics checks to Zagg
'''
# vim: expandtab:tabstop=4:shiftwidth=4
#
# Copyright 2015 Red Hat 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 Licens... |
# coding: utf-8
import django_filters
from rest_framework import viewsets, filters
from django.shortcuts import render
from .tables_models import Column, No_Relation_Table, Relation_Table, No_Relation_Columns, Relation_Columns, No_Relation_Options, Relation_Options, Columns, Tables
def tables_index(request):
#but... |
# Script will power cycle neato.
# Author: Brannon Vann - brannon.vann@gmail.com
# License: MIT
# run this script directly from the neato directory: python3 -m scripts.power_cycle
import time
import sys
from src.neato_driver_python import neato_driver as robot
sys.path.append("..")
try:
robot.init("/dev/neato... |
import sqlite3
__author__ = 'Oyewale Ademola'
class DBHelper:
def __init__(self, dbname="mood.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def setup(self):
stmt = "CREATE TABLE IF NOT EXISTS mood (current_mood text)"
self.conn.execute(stmt)
self.... |
import sys
import email,email.encoders,email.mime.base
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from socket import *
# Choose a mail server (e.g. Google mail server) and call it mailserver
serverName = sys.argv[1]
serverPort = int(sys.argv[... |
"""
Duplicate Managers module:
- Duplicates in folder
- Compare two folders
"""
from .duplicates_in_folder import DuplicatesInFolder
from .compare_folders import CompareFolders
|
from typing import Dict, List
from models.hardware_command_model import HardwareCommandModel
from utils.database.base.database_base import DatabaseBase
from pymongo.collection import Collection
class HardwareCommand(DatabaseBase):
def __init__(self, db, logger, hardware_collection_name="HardwareCommands"):
... |
import sys
import requests
import json
from PyQt5 import QtWidgets, uic
from model.cockpit_model import CockpitModel
ui_file = 'view/cockpit.ui'
Ui_CockpitView, QtBaseClass = uic.loadUiType(ui_file)
URL = 'http://localhost:5000/'
class CockpitView(QtWidgets.QMainWindow, Ui_CockpitView):
def __init__(self):
... |
# -*- coding: utf-8 -*-
""" Update Readme.md and cumulative_gans.jpg """
from __future__ import print_function
from __future__ import division
from wordcloud import WordCloud
from wordcloud import STOPWORDS
import numpy as np
import matplotlib.pyplot as plt
import sys
import datetime
import pandas as pd
import csv
imp... |
import ast
import json
import re
from pytube.exceptions import HTMLParseError
def parse_for_all_objects(html, preceding_regex):
"""Parses input html to find all matches for the input starting point.
:param str html:
HTML to be parsed for an object.
:param str preceding_regex:
Regex to fin... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 05:34:07 2018
@author: Ibrahim El-Shal
"""
# In[1]: Import Packages
import numpy as np
import time
import math
# In[2]: Function Implementation
def Gererate_Distance_Matrix(Row,Column,Matrix):
t1 = time.time()
Distance = 0
Distance_Vact = np.zeros(... |
# 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
#
# 示例:
#
# 输入: "25525511135"
# 输出: ["255.255.11.135", "255.255.111.35"]
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/restore-ip-addresses
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class Solution:
def is_valid(self, addr: str) -> bool:
n... |
from django.db import transaction
from django.http import HttpResponseRedirect
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.exceptions import ParseError
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from kl... |
import sys
import copy
THIS = sys.modules[__name__]
GRAPH_VARIABLE = 'rgp:index'
GRAPH_VERTEX = 'rgp:vertex'
GRAPH_VERTEX_ALL = 'rgp:vertex_all'
GRAPH_VERTEX_OUT = 'rgp:vertex_out'
GRAPH_VERTEX_IN = 'rgp:vertex_in'
GRAPH_VERTEX_INDICES = 'rgp:vertex_indices'
GRAPH_EDGE = 'rgp:edge'
GRAPH_EDGE_ALL = 'rgp:edge_all'
GRA... |
"""
Shared code for the `missing_intervals` and `stop_intervals` scripts.
"""
from typing import Callable, Optional
import osmnx as ox
from .page import Page
from .routing import RestrictedGraph, configure_osmnx
from .interval import Interval
from .calculation import IntervalCalculation
def enable_logging() -> None:
... |
import torch
import numpy as np
def segment_iou(target_segment,candidate_segments):
tt1 = torch.max(target_segment[0], candidate_segments[:, 0])
tt2 = torch.min(target_segment[1], candidate_segments[:, 1])
# Intersection including Non-negative overlap score.
segments_intersection = (tt2 - tt1).clamp(mi... |
from __future__ import unicode_literals
# import frappe
# from _future_ import unicode_literals
import frappe
import frappe.utils
from frappe.utils.oauth import get_oauth2_authorize_url, get_oauth_keys, login_via_oauth2, login_via_oauth2_id_token, login_oauth_user as _login_oauth_user, redirect_post_login
import json
f... |
# Generated by Django 2.0.4 on 2018-09-08 04:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
#Copyright 2018 Infosys Ltd.
#Use of this source code is governed by Apache 2.0 license that can be found in the LICENSE file or at
#http://www.apache.org/licenses/LICENSE-2.0 .
from utilities.sf_operations import Snowflakeconnection
connection = Snowflakeconnection(profilename ='snowflake_host')
sfconnectionr... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from typing import Any, Optional
from pydantic import BaseModel
class ModelSignature(BaseModel):
input: Optional[Any]
output: Optional[Any] |
import pickle
from DataLoader import load_tokenized_X
import pandas as pd
from DataLoader import load_Y
from DataLoader import save_XYs
from DataPreprocessing import make_eng_col
from DataPreprocessing import segment_Y
from ._parsing import parsing
from ._padding import padding
from ._train_test_split import train_... |
from pathlib import Path
import os
import subprocess
import sys
# test sources
SRC_DIR = Path(os.environ["SRC_DIR"])
TESTS = SRC_DIR / "src/tests"
COV_THRESHOLD = 90
os.environ.update(
# see https://github.com/CycloneDX/cyclonedx-python-lib/issues/202
PYTHONHASHSEED="0",
# expects importable paths
PYT... |
class Solution:
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
for i in reversed(range(32)):
prefixes = set(x >> i for x in nums)
ans <<= 1
candidate = ans + 1
for p in prefixes:
... |
from typing import Dict, Tuple
from unittest.mock import Mock
from synapse.module_api import ModuleApi
from matrix_synapse_user_directory_search_dinum.user_directory_search import (
ModuleConfig,
UserDirectorySearchModule,
)
def create_user_directory_search_module_with_config(
config: Dict,
) -> Tuple[U... |
from __future__ import absolute_import
from __future__ import division
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# Sandesh Client
#
from builtins import object
from past.utils import old_div
from .gen_py.sandesh.ttypes import SandeshRxDropReason, SandeshTxDropReason
from .protocol impor... |
def fUsage(sMainScriptName, sFeatureName):
################################################################################
print("Show all licenses registered for use by the current user on this system or in");
print("a license file.");
print("Usage:");
print(" %s %s" % (sMainScriptName, sFeatureName... |
from logging import getLogger
log = getLogger(__name__)
LOG_TPL = '%s <--%s'
def find_one(conn, table, filter_, fields=None):
sql, values = find_one_sql(table, filter_, fields)
log.debug(LOG_TPL, sql, values)
return conn.fetchrow(sql, *values)
def find_one_sql(table, filter_, fields=None):
'''
... |
from discord.ext import commands
class Help(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(
name="help",
aliases=["commands"],
usage = "`g.help [command name]`",
help = "Help ##This command will display the available commands and when ... |
from pathlib import Path
from gsa_framework.utils import *
from gsa_framework.convergence_robustness_validation.robustness import Robustness
from gsa_framework.visualization.plotting import (
plot_max_min_band_many,
plot_ranking_convergence_many,
)
from gsa_framework.sensitivity_methods.saltelli_sobol import *
... |
import Image
import sys
image = Image.open(raw_input("Image Name? ")).convert("1");
wrap = 15
for pixel in list(image.getdata()):
wrap += 1
if wrap == 16:
wrap = 0
sys.stdout.write("\n HEX ");
sys.stdout.write("FF " if pixel else "00 ");
print("");
wrap = -1
wrap... |
#!/usr/bin/python
import os
word = ""
word_length = 0
max_steps = word_length * 2 - 1
# production rules
start_symbol = "S" # <-- CHANGE THIS HERE
productions = { # <-- ENTER YOUR OWN PRODUCTIONS
# works perfect with this simple grammer
# "S": ("SA", "AB"),
# "A": ("AB", "a"),
# "B": ("BB", "b"),
# remember to... |
"""Celery Task Status"""
from flask_restful import Resource, reqparse
from flask import Response, json
from app.tasks.task_work import training
class TaskStatus(Resource):
"""Task Status class
Args:
Resource (Resource): RESTFul resource
"""
def __init__(self, configuration):
self.confi... |
db.define_table('page_visit_count',
Field('page_name'),
Field('counter', 'integer'),
)
db.define_table('page_visit_data',
Field('page_name'),
Field('last_visited','datetime'),
Field('args'),
Field('vars'),
) |
"""Convert a sam/bam to a psl, gzip output implied from output filename
.. warning:: Requires a reference fasta now but we could change this behavior in the future to extract the necessary target lengths from the header
"""
import sys, argparse, inspect, os, gzip
#from seqtools.format.fasta import FASTAData
from... |
# import statement
from PyMathTools import *
# * will import all of the functions
# binary_search
a = [6,7,8,9,10]
print(binary_search(a, 8)) # returns 2
# mod
print('34 mod 7 = ' + str(mod(34,7))) # returns 6
print('1/4 mod 7 = ' + str(mod(1/4,7))) # returns 2
# print('4 mod 5.5 = ' + str(PyMathTools().mod(4, 5.5))... |
from setuptools import setup
setup(name = "asfsp",
version = '0.1',
description = 'A package for claculating popgen statistics based on SFS and operating on SFS.',
author = 'Xiaodong Liu',
author_email = 'liuxiaodong.uu@gmail.com',
license = 'MIT',
packages = ['sfs'],
python_r... |
import core.decorators
from core.sql.db_connect import Connection
from core.sql.handler_sql import Sql_Badword_Select
@core.decorators.admin.user_admin
def init(update, context):
connector = Connection()
chatid = str(update.message.chat_id)
query = Sql_Badword_Select.SQL
connector.cur.execute(query,[ch... |
from unittest import TestCase
from Localization.extended_kalman_filter import extended_kalman_filter as m
print(__file__)
class Test(TestCase):
def test1(self):
m.show_animation = False
m.main()
|
import pandas as pd
from pprint import pprint
import boto3
class Searcher:
''' a search class to return search result'''
def __init__(self, searchTerm:str, key, pw, region = 'ap-southeast-1',
endpoint = 'https://search-villa-cloudsearch-2-4izacsoytzqf6kztcyjhssy2ti.ap-southeast-1.cloudsearch.amazona... |
"""Main URLs module."""
# Django
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import include, path
# Vistas
from andromeda.tasks.reports import report
from andromeda.tas... |
from django.test import TestCase
class PageNotFoundTest(TestCase):
def test_that_404_contains_no_errors(self):
response = self.client.get("/a-404-url/")
self.assertEqual(response.status_code, 404)
def test_that_404_uses_react_template(self):
response = self.client.get("/a-404-url/")
... |
"""Time routines for Astronomy
The heart of these routines is software written by Pat Wallace.
I have converted his code and algorithms from FORTRAN to Python
and added my own code.
This Software is made available free of charge for use by:
a) private individuals for non-profit research; and
b) non-profit educationa... |
from enum import Enum
from src.u2_net.model import U2NET, U2NETP
from src.bas_net.model import BASNet
class Model(Enum):
U2NET = U2NET # U2NET
U2NETP = U2NETP # U2NETP
U2NETPORTRAIT = U2NET # U2NETPORTRAIT
BASNet = BASNet # BASNet
def __str__(self):
return self.name
@staticmeth... |
# -*- coding: utf-8 -*-
import django
from django.apps import AppConfig
if django.VERSION < (2, 0):
from django.utils.translation import ugettext_lazy as _
else:
from django.utils.translation import gettext_lazy as _
class RedirectsConfig(AppConfig):
name = 'redirects'
verbose_name = _('Redirects')
... |
'''
This module contains the model creation: functions, basic-blocks and instructions
'''
from types import *
class MModule:
'''
Represent a python module, contain code
self.code = Code Object of the module
'''
def __init__(self, code):
self.code = code
# All functions defined in... |
# -*- coding: utf-8 -*-
"""Test config"""
import json
import unittest
from imap_cli import config
from imap_cli import const
class ConfigTest(unittest.TestCase):
def setUp(self):
pass
def test_default_config(self):
self.conf = config.new_context()
for key, value in config.DEFAUL... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 07:39:47 2021
@description: This module allows you to draw on your screen using OpenCV
In order to add more colors please add the respective colour in myColorValues
Also, use the create_mask.py to create a mask for that color and add to myCol... |
import numpy as np
from combine1d.core.cost_function import create_cost_fct
from scipy.optimize import minimize
from combine1d.sandbox.idealized_experiments_help_functions import \
define_geometry, define_mb_model, create_measurements, get_reg_parameters,\
get_bounds
from combine1d.core.first_guess import get_... |
"""
Reads each line of a control file where each line corresponds to one test
case for regridding from a source file coordinate grid to a destination file
coordinate grid. Parses each line and retrieves the source and destination
files from a remote server if they do not already exist locally. On parallel
computers... |
NAMES = [
'EGF',
'R',
'Ra',
'R2',
'RP',
'PLCg',
'R_PL',
'R_PLP',
'PLCgP',
'Grb2',
'R_G',
'SOS',
'R_G_S',
'G_S',
'Shc',
'R_Sh',
'R_ShP',
'ShP',
'R_Sh_G',
'Sh_G',
'R_Sh_G_S',
'Sh_G_S',
'PLCgP_I',
]
for idx, name in enumerate(NAME... |
class Config():
def __init__(self):
self.PORT = 4242
self.PATH = "./data/dogscats/"
self.sz = 224
self.model = 'dogscats_resnet50'
|
# -*- coding: utf-8 -*-
print "\n\nand"
print "True and True = %r" % (True and True)
print "\n\ndel"
a = [0, 1, 2, 3, 4, 5]
print "a = ", a
print "del a[0]"
del a[0]
print "a = ", a
print "\n\nfrom"
print "from ex25 import *"
from ex25 import *
print "%r" % break_words(".,., .,., .,., .,., .,.,")
print "\n\nnot"
pri... |
"""Base validator for token based authentication."""
from authlib.jose import errors as jwt_errors
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.middleware.authentication import AuthenticationErr... |
#------------------------------------------------------------------------------
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
# Portions Copyright 2001-2007, Computronix (Canada) Ltd., Edmonton, Alberta,
# Canada. Al... |
from .ast_builder import AstBuilder
class TokenFormatterBuilder(AstBuilder):
def __init__(self):
self.reset()
def reset(self):
self._tokens = []
def build(self, token):
self._tokens.append(token)
def start_rule(self, rule_type):
pass
def end_rule(self, rule_type... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from day import Day
class Day03(Day):
def __init__(self):
super(Day03, self).__init__(3)
def parse_data(self):
return [
[(s[0], int(s[1:])) for s in d.split(",")]
for d in self.raw_data]
def part_1(self):
visited = set()
position =... |
import operator
from functools import reduce
from django.db.models import Q
from wagtail.search.backends import get_search_backend
try:
from django.contrib.admin.utils import lookup_spawns_duplicates
except ImportError:
# fallback for Django <4.0
from django.contrib.admin.utils import lookup_needs_dist... |
import collections
import csv
import os
import random
import shutil
import string
import sys
import networkx
import schema
import metapaths
import nxutils
valid_file_chars = set("-_.()[]{}&#@!~+= %s%s" % (string.ascii_letters, string.digits))
def string_to_valid_filename(s):
"""Return the string with invalid fi... |
from functools import wraps
from flask import Blueprint, url_for, request
from uchan.lib import roles
from uchan.lib.action_authorizer import NoPermissionError
from uchan.lib.moderator_request import request_has_role, get_authed
mod = Blueprint('mod', __name__, url_prefix='/mod', template_folder='templates', static_... |
#!/usr/bin/env python3
# Recommended: Python 3.6+
"""
Collatz Conjecture - Python
The Collatz conjecture, also known as the
3x + 1 problem, is a mathematical conjecture
concerning a certain sequence. This sequence
operates on any input number in such a way
hat the output will always reach 1.
The Collat... |
import importlib
from pyqtgraph.flowchart.NodeLibrary import NodeLibrary
class ReloadableNodeLibrary(NodeLibrary):
""" A version of NodeLibrary that enables reloading node classes dynamically (to enable updating them after running). """
@property
def register_custom_nodes_function(self):
"""The r... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import sys
if (sys.version_info < (3, 0)):
raise Exception( 'python3 or bust' )
import os
sys.path.append( os.environ['ezbCTL__ENCLOSING_PROJECT_PATH'] )
import datetime, json, unittest
from easyborrow_controller_code.classes.tunneler_runners import IlliadApiRunner
from easyborrow_controller_code.classes.basics i... |
import math
numberOfTests = int(input())
for _ in range(numberOfTests):
encodedMessage = input()
rowLength = int(math.sqrt(len(encodedMessage)))
rows = []
for rowIndex in range(rowLength):
row = ""
for columnIndex in range(rowLength):
index = rowLength * rowIndex + columnIn... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Make subpackages available:
from . import (
latest,
v20151031,
v20170515preview,
v20180115,
v20180630,
v20200113preview,
)
|
def contagem(i, f, p=0):
"""
:param i: Inicio da contagem
:param f: Final da contagem
:param p: Passo da contagem
"""
print(f'Contagem de {i} ate {f} de {abs(p)} em {p}')
f += p
for c in range(i, f, p):
print(c, end=' ')
print()
i = int(input('Inicio: '))
f = int(input('Fin... |
from systems.plugins.index import BaseProvider
class Provider(BaseProvider('data_processor', 'shuffle')):
def exec(self, dataset):
return dataset.sample(frac = 1)
|
# -*- coding: utf-8 -*-
import scrapy
import re
from scrapy.linkextractors import LinkExtractor
from NewsCrawler.utilities import formatdate
from scrapy.spiders import CrawlSpider, Rule
from scrapy import Request
from NewsCrawler.items import NewsCrawlerItem
from NewsCrawler.settings import PERIODISTA_VARS,NEWSIT_VARS,... |
from math import sqrt, log
from copy import deepcopy
from random import choice, random
from time import clock
from gamestate import GameState
from uct_mcstsagent import Node, UctMctsAgent
from meta import *
class RaveNode(Node):
def __init__(self, move=None, parent=None):
"""
Initialize a new nod... |
#
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
import logging
from sqlalchemy.sql import text
from werkzeug.exceptions import NotFound
from rdr_service.dao.resource_dao import ResourceDataDao
from rdr_service.resource import generator... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.