text
string
size
int64
token_count
int64
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="django_home_urls", version="0.1.0", author="Yuji Koseki", author_email="pxquuqjm0k62new7q4@gmail.com", description="Django home urlconf.", long_description=long_description, long_d...
662
223
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This script provide a class to read and save files Created on Sat July 21 2018 @author: cttsai """ import pandas as pd from Utility import CheckFileExist from LibConfigs import logger, hdf5_compress_option, fast_hdf5_compress_option class DataFileIO(object): ""...
3,553
1,091
#!/bin/python from roomai.sevenking import SevenKingEnv from roomai.sevenking import SevenKingAction import unittest class testSevenKing(unittest.TestCase): def show_hand_card(self,hand_card): str = "" for c in hand_card: str += "," + c.key print (str) def testEnv(self): ...
885
285
import attr import os import tarfile from pyamazonlandsat.utils import get_path_row_from_name from pyamazonlandsat.downloader import Downloader @attr.s class Product: """Class that represent a Product :param name: name of the Product. type name: str. :param output_path: path where save the downloaded...
1,776
521
from __future__ import division from skimage.segmentation import slic, mark_boundaries from skimage.util import img_as_float from skimage import io import numpy as np import matplotlib.pyplot as plt import os from cv2 import boundingRect #from argparse import ArgumentParser img_width = 50 img_height = 50 img_depth = ...
5,352
2,053
"""Parse CWL and create a JSON file describing the workflow. This dictionary is directly suitable for display by vis.js, but can be parsed for any other purpose.""" # Copyright (c) 2019 Seven Bridges. See LICENSE from ..cwl.lib import ListOrMap def cwl_graph(cwl: dict): graph = { "nodes": [], ...
1,797
661
def double_char(s):
21
10
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin from django.conf import settings class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates a...
2,561
770
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reviews', '0005_auto_20160203_1247'), ] operations = [ migrations.AddField( model_name='review', nam...
477
155
# AUTOGENERATED! DO NOT EDIT! File to edit: 04kraus.ipynb (unless otherwise specified). __all__ = ['apply_kraus', 'partial_trace_kraus', 'povm_map'] # Cell import numpy as np import qutip as qt # Cell def apply_kraus(dm, kraus): r""" Applies a Kraus map to a density matrix $\rho$. The Kraus map consists in some nu...
2,191
799
n = int(input()) num = 1 while num <= n: print(num) num = num * 2 + 1
78
36
import sys sys.path.insert(0,'..') sys.path.insert(0,'../..') from bayes_opt import BayesOpt,BayesOpt_KnownOptimumValue import numpy as np #from bayes_opt import auxiliary_functions from bayes_opt import functions from bayes_opt import utilities import warnings #from bayes_opt import acquisition_maximization import...
4,129
1,638
import icalendar import uuid from datetime import datetime import pytz cst = pytz.timezone('Asia/Shanghai') class Calendar(icalendar.Calendar): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.add('prodid', '-//CDFMLR//coursesical//CN') self.add('VERSION', '2.0...
2,258
789
#!/usr/bin/python3.2 import unittest from minesweeper.message import * class UTSMessageTest(unittest.TestCase): def test_parse_infer_type(self): """ Instantiates one object for every concrete subclass of UTSMessage using the type-inferring factory method parse_infer_type(), checking that...
816
236
from distutils.core import setup from distutils.command.build_py import build_py import os import shutil import stat from RunnerPyzza import __version__ class runner_build_py(build_py): def runner_install(self): print "RunnerPyzza basic configuration ..." try: os.mkdir("/etc/runnerpyzz...
1,640
528
class Solution: def _equalize_length(self, *args) -> tuple: max_len = max(map(len, args)) return tuple(map(lambda x: x.zfill(max_len), args)) def _add(self, *args) -> str: return str(sum(map(int, args))) def _sub(self, num1: str, num2: str) -> str: return str(int(num1) -...
1,142
491
""" Here for compat. with objectstore. """ class ObjectNotFound(Exception): """ Accessed object was not found """ pass class ObjectInvalid(Exception): """ Accessed object store ID is invalid """ pass
220
60
import asyncio import inspect import logging import os import random import time import uuid from abc import ABC, abstractmethod from functools import cached_property, wraps from logging import Logger from typing import Any, Callable, Dict, List, Optional, Tuple from aiohttp.client import ClientConnectionError, Client...
9,432
2,778
import syaml testcase = """--- key: key: f key2: l nest: inner: g nest2: nestted: 3 inner2: s outnest: 3 ha: g je: r --- key: value a_list: - itema - listlist: - itemitem - itemb - key1: bweh key2: bweh key3: bweh key4: bweh - innerList: - innerItem - indict:...
860
378
#!/usr/bin/env python import os import sys def dict_to_csv(comps, filename): ## print column headings then all attributes for each company f = open(filename, 'wb') columns = [x for x in comps[comps.keys()[0]].keys() if x != 'name'] columns = ['name'] + columns f.write(','.join(columns) +...
478
168
# Generated by Django 2.2.5 on 2020-02-22 22:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0015_auto_20200222_2200'), ] operations = [ migrations.RemoveField( model_name='subject', name='handedness', ...
543
176
""" Load and Display a Shape. Illustration by George Brower. (Rewritten in Python by Jonathan Feinberg.) The loadShape() command is used to read simple SVG (Scalable Vector Graphics) files into a Processing sketch. This library was specifically tested under SVG files created from Adobe Illustrator. For now, we c...
799
265
""" Custom tokenization routines for the 'ons' corpus. Special care is taken to metadata tokens such as === Report: 12345 === that were inserted to distinguish between multiple documents of a client. They will be properly handled during the tokenization and sentence segmentation stage. """ import re import spacy from...
4,015
1,352
# Django from django.conf import Settings, settings # APPs from systemtest.quality import forms as quality_forms, models as quality_models from systemtest.utils.db2 import Database def get_quality_status(status_name: str) -> quality_models.QualityStatus: """ Gets a specific QualityStatus by exact name ...
1,219
363
# -*- coding: utf-8 -*- import asyncio import logging import aiohttp from cibopath import readme_parser, github_api from cibopath.templates import Template logger = logging.getLogger('cibopath') class CibopathError(Exception): """Custom error class for the app.""" class CookiecutterReadmeError(CibopathError...
1,849
558
# Goal: # Demonstrate the A/B switch functionality of the SpikeSafe PSMU while operating in DC mode # # Expectation: # Channel 1 will run in DC mode with the switch set to Primary. # Afterward the Switch be set to Auxiliary mode, in which another source may operate connected to the SpikeSafe # After the Auxiliary s...
5,400
1,636
# 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. import logging import os import py_utils import time from telemetry.page import legacy_page_test from telemetry.util import image_util class Screenshot(leg...
1,886
604
# Copyright 2016 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
2,474
766
import numpy as np import torch from collections import deque, namedtuple import cv2 import os import carla from .model_supervised import Model_Segmentation_Traffic_Light_Supervised from .model_RL import DQN, Orders class AgentIAsRL: def __init__(self, args=None, **kwargs): super().__init__(**kwargs) ...
8,621
2,727
n = int(input()) for i in range(1 , n + 1 ): x = input().split() a,b,c = x print('{:.1f}'.format((float(a) * 2 + float(b) * 3 + float(c) * 5) / 10))
162
81
import base64 import binascii import datetime import os import subprocess import random import sys BECH_SYMBOLS = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" OUR_BINARY = None LIBBECH32ENC_BINARY = None LIBBECH32DEC_BINARY = None NODE_REF = "node . " # region Encoding def node_encode(hrp, data_hex): str_in = NODE_REF +...
10,547
3,882
#!/usr/bin/env python3 """ #------------------------------------------------------------------------------ # # SCRIPT: forecast_task_07.py # # PURPOSE: Combine all non-precip 6-hourly files into one file and copy BCSD # precip files in to the same directory Based on FORECAST_TASK_07.sh. # # REVISION HISTORY: # 24 Oct 2...
3,166
1,091
""" 10. Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Farenheit. """ celsius = float(input('Informe o valor em Celsius (ºC): ')) fahrenheit = (celsius * (9/5)) + 32 print('{} ºC é igual a {:.1f} ºF'.format(celsius, fahrenheit))
271
113
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.distributions import Normal def squash(s, dim=-1, eps=1e-8): """ "Squashing" non-linearity that shrunks short vectors to almost zero length and long vectors to a length slightly below 1 v_j = ||s_j||...
12,178
4,995
#!python3 import contextlib import json import logging import os from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from dcos_e2e import cluster from dcos_e2e import node from dcos_test_utils impo...
16,807
5,260
def sumOf(s, offset): sum = 0 n = len(s) for i in range(0, len(s)): if s[i] == s[(i + offset) % n]: sum += int(s[i]) return sum file = open("./input/input1.txt", "r") for s in file: s = s.strip() print('Part 1: ', sumOf(s, 1)) print('Part 2: ', sumOf(s, int(len(s)/2))) file.close()
308
159
import numpy as np from cops.graph import Graph from cops.clustering import ClusterProblem, ClusterStructure, inflate_agent_clusters def test_activationinflate1(): G = Graph() G.add_connectivity_path([0, 1]) G.add_connectivity_path([0, 2]) agent_positions = {0: 0, 1: 1, 2: 2} G.init_agents(agent...
2,123
919
import csv from sys import argv from os import getcwd def generate_memory_list_view(expected_memory) -> str: """ Convert expected memory's bytestring to a list of Cells (in string) :param expected_memory: "A00023" :return: [Cell("A0"), Cell("00"), Cell("23")] """ list_view = "[" for i in ra...
3,243
1,035
car = ['volvo', 'toyota', 'BMW', 'Yes?'] message = f"I would like to own a {car[1].title()}" print(message)
108
45
""" File: my_drawing Author name: Alan Chen ---------------------- This program will draw a recently famous picture of Gian(技安), one of the main characters in doraemon(哆啦A夢). This is a picture that originally Gian was scared by something. Here, I reassign the things that scared him is the Illuminati symbol with a strin...
10,677
5,071
""" This module doesn't provide a register method and should be skipped. This ensures that the error handling logic works. """
127
29
import json import os import subprocess import requests from bs4 import BeautifulSoup from ciri import HelpStr from ciri.utils import ciri_cmd, eor @ciri_cmd(pattern="red(?:dit)? (.*)") async def reddit(e): url = e.pattern_match.group(1) if not url: return await e.edit("`No url provided?`") if n...
3,196
1,176
import requests, json import numpy as np import importlib import pandas as pd import os import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline import pdb import warnings warnings.filterwarnings('ignore') def plot_barh(s_to_plot, title = '', xlabel = '', ylabel = '', color_palette = 'YlGnBu', pre_u...
2,343
739
from re import I import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import sensor from esphome.const import CONF_ID, STATE_CLASS_MEASUREMENT, UNIT_EMPTY, UNIT_METER # DEPENDENCIES = ["i2c"] AUTO_LOAD = ["sensor", "binary_sensor", "text_sensor"] MULTI_CONF = True CONF_ROODE_ID ...
4,373
1,821
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\Projects\Python\Folder Maker\GUI\main.ui' # # Created by: PyQt5 UI code generator 5.12.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(s...
7,767
2,721
# -------------- # Import packages import numpy as np import pandas as pd from scipy.stats import mode # code starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) # code ends h...
1,632
640
import pytest import torch from espnet2.tts.feats_extract.energy import Energy @pytest.mark.parametrize( "use_token_averaged_energy, reduction_factor", [(False, None), (True, 1), (True, 3)] ) def test_forward(use_token_averaged_energy, reduction_factor): layer = Energy( n_fft=128, hop_length=...
1,718
640
"""Official merge script for PI-SQuAD v0.1""" from __future__ import print_function import os import argparse import json import sys import shutil import scipy.sparse import scipy.sparse.linalg import numpy as np import numpy.linalg def get_q2c(dataset): q2c = {} for article in dataset: for para_idx...
4,699
1,585
from functools import cached_property from datetime import datetime from math import degrees, radians, sin, cos import numpy as np from orbit_predictor import coordinate_systems from .utils import get_timezone_from_latlon from .time import make_utc from ._time import datetime2mjd from .solar import sun_pos_mjd from ....
3,918
1,231
import subprocess import numpy as np import pickle import argparse import os from rl_baselines.student_eval import allPolicy from srl_zoo.utils import printRed, printGreen from rl_baselines.evaluation.cross_eval_utils import EnvsKwargs, loadConfigAndSetup, policyEval,createEnv def dict2array(tasks,data): res=[]...
4,559
1,540
#! /usr/bin/env python import os os.system("make clean; make; \\rm *.log log.list") ############################################ #dir1='TriggerValidation_223_HLT' #dir2='TriggerValidation_224_HLT' #out='223_vs_224' #samples=['LM1'] #prefix1 = "histo_" #prefix2 = "histo_" #sufix1 = "_IDEALV11" #sufix2 = "_IDEALV11_v...
6,304
2,333
from curses import echo from importlib.metadata import metadata import sqlite3 import sys import sqlalchemy import os from sqlalchemy import Column, Integer, String, ForeignKey, Table, MetaData, create_engine, engine_from_config from sqlalchemy.orm import relationship, backref, sessionmaker from sqlalchemy.ext.declarat...
2,275
663
# -*- coding: utf-8 -*- from django_cas.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, redirect from mecc.apps.years.models import UniversityYear @login_required def home(request): """ root of all evil: dispatch according to us...
1,602
486
# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlNetwerklinkMediumtype(KeuzelijstField): """Mogelijke waarden voor het type dra...
2,695
798
import logging import threading import time class StatusProcessor: MAX_NUM_MESSAGES_PER_UPDATE = 10 GET_MESSAGES_TIMEOUT_S = 0.5 LIVENESS_TIMEOUT_S = 5 def __init__( self, status_consumer, msg_processor, logger=logging.getLogger(__name__), time_function=time.ti...
1,617
504
from befh.ws_api_socket import WebSocketApiClient from befh.market_data import L2Depth, Trade from befh.exchanges.gateway import ExchangeGateway from befh.instrument import Instrument from befh.util import Logger from befh.clients.sql_template import SqlClientTemplate import time import threading import json from funct...
9,045
2,806
from cloudflare_ddns.configuration import Configuration, SiteConfiguration from cloudflare_ddns.ddns import CloudflareDDNS __all__ = ["CloudflareDDNS", "Configuration", "SiteConfiguration"]
191
53
from .base import PipBaseRecipe class TwistedRecipe(PipBaseRecipe): def __init__(self, *args, **kwargs): super(TwistedRecipe, self).__init__(*args, **kwargs) self.sha256 = 'a4cc164a781859c74de47f17f0e85f4b' \ 'ce8a3321a9d0892c015c8f80c4158ad9' self.pythons = ['python...
587
216
#!/usr/bin/python # combiner.py import sys word_count = 0 line_count = 0 for line in sys.stdin: words, lines = line.strip().split('\t') word_count += int(words) line_count += int(lines) print("{0}\t{1}".format(word_count, line_count))
250
98
import re from radish.stepregistry import step from radish import when, then from radish.terrain import world @step(re.compile("I have the number in user data as (.+)")) def have_number(step, input_variable): if world.config.user_data: if input_variable in world.config.user_data: step.context...
1,376
401
from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.http.response import HttpResponseBadRequest, HttpResponseRedirect from django.urls import reverse_lazy from django.urls.base import...
3,462
990
#!/usr/bin/env python from distutils.core import setup setup( name = 'pydouban', version = '1.0.0', description = 'Lightweight Python Douban API Library', author = 'Marvour', author_email = 'marvour@gmail.com', license = 'BSD License', url = 'http://i.shiao.org/a/pydouban', packages = ...
336
122
from imutils import face_utils from scipy.spatial import distance import cv2 import dlib import imutils import pygame import time # Initializing the alert sound pygame.mixer.init() alert_sound = pygame.mixer.Sound("alert_sound.wav") default_volume = 0.2 # Eye-Aspect-Ratio data EAR_threshhold = 0.17 # One valid frame ...
3,234
1,206
#!/usr/bin/env python3 # < trunk-tap.py > # Version 1.0 < 20171022 > # Copyright 2017: Alexander Schreiber < schreiberstein[at]gmail.com > # https://github.com/schreiberstein/trunk-tap.py # MIT License: # ============ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and...
11,809
3,815
# Copyright 2020 Microsoft Corporation # # 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...
4,404
1,582
from __future__ import print_function import os import neat # 2-input XOR inputs and expected outputs. xor_inputs = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)] xor_outputs = [(0.0,),(1.0,),(1.0,),(0.0,)] def eval_genomes(genomes, config): for genome_id, genome in genomes: genome.fitness = 4.0 ...
1,474
569
""" _ _____ _ _ |_| __ | |___ ___| |_ | | __ -| | . | _| '_| |_|_____|_|___|___|_,_| iBlock is a machine learning video game! This game is played on a 8x6 board (48 spaces) and the goal is to fill up the enemy's column with your pieces! Once that happens the game will reset and log all the data for the ...
16,866
7,778
def main(): import webbrowser recherche = 0 while True: if recherche >= 2: print("Vous avez fait " + str(recherche) + " recherches.") recherche += 1 adresse = input("Quel adresse veut-tu ouvrir") webbrowser.open(adresse) if __name__ == "__main__": main()
319
106
"""Action Module circuits component to update incidents from QRadar Ariel queries""" import logging from datetime import datetime import time import copy import json from string import Template from pkg_resources import Requirement, resource_filename import resilient_circuits.template_functions as template_functions fr...
6,502
1,987
#! /usr/bin/env python # -*- coding: utf-8 -*- from email import encoders from email.header import Header from email.mime.multipart import MIMEBase, MIMEMultipart from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib # 格式化一个邮件地址 def _format_addr(s): # parseaddr:解析字符串中的...
2,371
1,090
#!/usr/bin/env python # encoding=utf-8 """ Copyright (c) 2021 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFT...
1,519
485
__author__ = 'schien' from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.contrib.admin import BooleanFieldListFilter from api.models import Scan, Measure, InstalledMeasure, MeasureCategory, App, MessageThread, RedirectUrl, Trackabl...
2,895
943
import numpy as np from scipy.sparse import csc_matrix, diags, tril from .basis import Basis __author__ = 'Randall' # TODO: complete this class # todo: compare performance of csr_matrix and csc_matrix to deal with sparse interpolation operators # fixme: interpolation is 25 slower than in matlab when 2 dimensions!! 2x ...
7,359
2,398
import os import os.path import sys # Modified version from Python-3.3. 'env' environ dict override has been added. def which(cmd, mode=os.F_OK | os.X_OK, env=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file...
2,279
698
"""Defines the classes SymbolTable and SymbolTableNode""" import sys from numpy import ones class SymbolTableNode: """Defines a class SymbolTableNode which stores the nodes in the SymbolTable""" def __init__(self, name, type_name, parameters = None, size = None): """Initializes the Node""" sel...
6,469
1,837
from setuptools import setup, version setup( name="NorthNet", version="0.0", author="William E. Robinson", packages = ["NorthNet"], )
151
51
"""Class with high-level methods for processing NAPS and NAPS BE datasets.""" from config import DATA_NAPS_BE_ALL from lib import partition_naps from lib import plot from lib import plot_clusters from lib import plot_clusters_with_probability from lib import plot_setup from lib import read_naps from lib import read_na...
13,380
4,458
""" 1618. Maximum Font to Fit a Sentence in a Screen Medium You are given a string text. We want to display text on a screen of width w and height h. You can choose any font size from array fonts, which contains the available font sizes in ascending order. You can use the FontInfo interface to get the width and heigh...
2,936
934
''' Copyright 2022 Airbus SAS 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 writing, software dis...
6,407
2,021
#!/usr/bin/env python3 """ The PyMKM example app. """ __author__ = "Andreas Ehrlund" __version__ = "2.0.4" __license__ = "MIT" import os import csv import json import shelve import logging import logging.handlers import pprint import uuid import sys from datetime import datetime import micromenu import progressbar i...
56,368
14,470
import ee from ee_plugin import Map dataset = ee.Image('CSP/ERGo/1_0/US/physioDiversity') physiographicDiversity = dataset.select('b1') physiographicDiversityVis = { 'min': 0.0, 'max': 1.0, } Map.setCenter(-94.625, 39.825, 7) Map.addLayer( physiographicDiversity, physiographicDiversityVis, 'Physiographic...
333
140
from django import forms from . import models class PunchLogForm(forms.ModelForm): latitude = forms.DecimalField(widget=forms.HiddenInput()) longitude = forms.DecimalField(widget=forms.HiddenInput()) class Meta: model = models.PunchLog fields = ()
281
79
# -*- coding: utf-8 -*- import base64 print('Choose your choice:') n=''' 1:Encode string to base64 2:Decode base64 to string ''' c=int(eval(input(n))) #定义菜单变量 if c == 1: #进入菜单1的判断 print('Type string to be encoded:') inp=input() out = str(base64.encodebytes(inp.encode("utf-8")), "utf...
497
213
import time, os, sys import scsynth, scosc server = 0 # reference to app's sc server process sndLoader = 0 synthon = 0 # did we start the scsythn process? ##workingpath = os.getcwd() # must be set to the right path in case something special is need sndpath = os.path.join( os.getcwd() , 'sounds' ) synthdefpath = os....
9,781
2,847
import pytest from fastapi import FastAPI from httpx import AsyncClient from starlette.status import HTTP_200_OK pytestmark = pytest.mark.asyncio async def test_about_route_if_status_code_is_ok(app: FastAPI, client: AsyncClient): response = await client.request("GET", app.url_path_for("index_router")) assert...
357
117
import linefinder.linefinder as linefinder import linefinder.config as linefinder_config import linefinder.utils.file_management as file_management ######################################################################## sim_name = 'm12i' '''The simulation to run tracking on.''' tag = '{}_sightline'.format( sim_nam...
2,614
904
# 47. 求1+2+3+...+n # 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 # -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here res = n if(res): res += self.Sum_Solution(n-1) return res
285
145
from django.urls import path from .views import AboutTemplateView urlpatterns = [path("", AboutTemplateView.as_view(), name="about")]
137
40
''' send out activitypub messages ''' from base64 import b64encode from Crypto.PublicKey import RSA from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from datetime import datetime import json import requests from fedireads import incoming from fedireads.settings import DOMAIN def get_recipients(us...
2,969
901
from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext, loader from .models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_...
733
215
from __future__ import division from builtins import str from builtins import range from astropy.utils.misc import isiterable from past.utils import old_div import copy import collections import numpy as np import healpy as hp import astropy.units as u import matplotlib.pyplot as plt import matplotlib as mpl from sci...
48,562
14,446
# File: sshcustodian/sshcustodian.py # -*- coding: utf-8 -*- # Python 2/3 Compatibility from __future__ import (unicode_literals, division, absolute_import, print_function) from six.moves import filterfalse """ This module creates a subclass of the main Custodian class in the Custodian project ...
15,227
4,009
''' Sherlock: Distributed Locks with a choice of backend ==================================================== :mod:`sherlock` is a library that provides easy-to-use distributed inter-process locks and also allows you to choose a backend of your choice for lock synchronization. |Build Status| |Coverage Status| .. |Bu...
17,217
4,612
from typing import List, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import random from skimage.draw import random_shapes import os import json def get_masks_for_training( mask_shapes: List[Tuple] = [(1, 128, 128), (1, 64, 64), (1, 32, 32), (1, 1...
7,199
2,350
import math from typing import Dict, List, Tuple, Union from EasyMCDM.models.MCDM import MCDM # Instant-Runoff Multicriteria Optimization (IRMO) class Irmo(MCDM): # Memory allocation __slots__ = ['verbose', 'matrix', 'names', 'indexes', 'preferences', 'matrix'] # Constructor def __init__...
4,204
1,351
import numpy as np from rpy2.robjects import FloatVector from rpy2.robjects.packages import importr from rpy2 import robjects stats = importr('stats') base = importr('base') def matrix_to_r_dataframe(x): rx = FloatVector(np.ravel(x)) rx = robjects.r['matrix'](rx, nrow = len(x), byrow=True) ret...
2,046
764
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import unittest from azure.functions.decorators.constants import TIMER_TRIGGER from azure.functions.decorators.core import BindingDirection, DataType from azure.functions.decorators.timer import TimerTrigger class TestTim...
1,138
305
import socket import threading import time from threading import Thread import utilities as utils import error_handling as check BUFFER_SIZE = 1024 BROADCAST_MAC = "FF:FF:FF:FF:FF:FF" class ClientThread(threading.Thread): """ Initializes the client. The event synchronization primitive, among the initial...
8,368
2,327
import json from great_expectations.core.util import convert_to_json_serializable from great_expectations.types import SerializableDictDot, safe_deep_copy from great_expectations.util import deep_filter_properties_iterable class Builder(SerializableDictDot): """ A Builder provides methods to serialize any bu...
2,569
727
# #1. Health check # # Ask user for their temperature. # # If the user enters below 35, then output "not too cold" # # If 35 to 37 (inclusive), output "all right" # # If the temperature over 37, then output "possible fever" # user_temp = float(input('What is your temperature?')) if user_temp < 35: print('not too ...
449
155