text
string
size
int64
token_count
int64
from sopel.module import commands, example from sopel import web import sopel.module import socket import re import urbandictionary as ud BOLD=chr(0x02) ITALICS=chr(0x1D) UNDERLINE=chr(0x1F) def ud_conv(s): italics = re.sub(r"\[([\w' \"_-]*)\]", f"{UNDERLINE}\\1{UNDERLINE}", s.strip()) newlines = re.sub(r...
1,854
704
# Conversor de CELSIUS para FAHRENHEIT v.0.1 # Por Dorcival Leite 202003362174 import time print("CONVERTER TEMPERATURA DE CELSIUS PARA FAHRENHEIT\n") c = float(input("Digite a temperatura em CELSIUS: ")) f = float((9 * c)/5)+32 print("\nA temperatura de", c, "graus CELSIUS é igual a", f, "graus FAHRENHEIT") time.sleep...
324
147
#encoding: utf-8 import sys reload(sys) sys.setdefaultencoding( "utf-8" ) import zmq, sys, json import seg import detoken import datautils from random import sample serverl=["tcp://127.0.0.1:"+str(port) for port in xrange(5556,5556+4)] def _translate_core(jsond): global serverl sock = zmq.Context().socket(zmq.R...
772
308
#!/usr/bin/env python3 import os import numpy as np import tensorflow as tf from tqdm import tqdm from glob2 import glob from skimage import transform from skimage.io import imread, imsave gpus = tf.config.experimental.list_physical_devices("GPU") for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, Tru...
10,995
4,230
"""Configuration defaults and loading functions. Pyleus will look for configuration files in the following file paths in order of increasing precedence. The latter configuration overrides the previous one. #. /etc/pyleus.conf #. ~/.config/pyleus.conf #. ~/.pyleus.conf You can always specify a configuration file when...
4,132
1,236
from shutil import rmtree from tempfile import mkdtemp import pytest import param import pydrobert.param.serialization as serial param.parameterized.warnings_as_exceptions = True @pytest.fixture(params=["ruamel_yaml", "pyyaml"]) def yaml_loader(request): if request.param == "ruamel_yaml": try: ...
1,318
451
import unittest import numpy as np import matplotlib.pyplot as plt from npaths import NPathNode, Filter, Circulator __all__ = [ 'TestNPathNode', 'TestFilter', 'TestCirculator' ] GHz = 1e9 ohm = 1 pF = 1e-12 freqs = np.linspace(0.001, 6, 500)*GHz class TestNPathNode(unittest.TestCase): def test_s...
1,942
905
import o80 import o80_pam import context class _Data: def __init__(self, observation): ball_states = observation.get_observed_states() self.ball_position = [None] * 3 self.ball_velocity = [None] * 3 for dim in range(3): self.ball_position[dim] = ball_states.get(2 * dim)...
2,896
889
# -*- coding: utf-8 -*- from __future__ import print_function, division import torch import json import math import random import numpy as np from scipy import ndimage from pymic.transform.abstract_transform import AbstractTransform from pymic.util.image_process import * class ChannelWiseThreshold(AbstractTransform)...
5,374
1,531
import os numeros = [0,0] numeros[0] = float(input('Digite o numero 1: ')) numeros[1] = float(input('Digite o numero 2: ')) print(f'o maior valor entre os dois é: {max(numeros)}') os.system('pause')
211
93
# -*- coding: utf-8 -*- # Citations from flask import (Blueprint, request, render_template, flash, url_for, redirect, session) from flask.ext.login import login_required, current_user import logging, sys, re from sqlalchemy.exc import IntegrityError, InvalidRequestError from DictionaryOfNewZealandE...
7,958
2,296
from random import random TABLE_NAME = f"test-django-dynamodb-cache-{random()}"
81
28
import psycopg2 as pg import os """ Database (Postgres) module connecting to the database for the simple greeting app. """ # The hostname where the database is running can be determined via environment PGHOST = os.getenv("PG_HOST") if os.getenv("PG_HOST") else "localhost" def get_pgconn(): """ Connects to t...
1,863
546
# 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 # -*- coding:utf-8 -*- # email:bingchengzhou@foxmail.com # create: 2020/11/25 from imgaug imp...
3,277
1,415
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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...
3,873
1,138
class Solution: def chooseandswap (self, A): opt = 'a' fir = A[0] arr = [0]*26 for s in A : arr[ord(s)-97] += 1 i = 0 while i < len(A) : if opt > 'z' : break while opt < fir : if o...
1,074
308
import argparse import csv import matplotlib import matplotlib.ticker as tck import matplotlib.pyplot as plt import numpy as np # Matplotlib export settings matplotlib.use('pgf') import matplotlib.pyplot as plt matplotlib.rcParams.update({ 'pgf.texsystem': 'pdflatex', 'font.size': 10, 'font.family': 'ser...
10,625
3,984
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.base.buil...
4,744
1,366
class AccountManager(object): def __init__(self, balance = 0): self.balance = balance def getBalance(self): return self.balance def withdraw(self, value): if self.balance >= value: self.balance = self.balance - value print('Successful Withdrawal.') ...
1,825
579
""" eZmax API Definition (Full) This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501 The version of the OpenAPI document: 1.1.7 Contact: support-api@ezmax.ca Generated by: https://openapi-generator.tech """ import unittest import eZmaxApi from eZmaxApi.a...
818
274
import tensorflow as tf import face_decoder import networks import losses from utils import * ############################################################################################### # model for single image face reconstruction ##############################################################################...
3,930
1,549
from django.contrib import admin from .models import * from .admin_inlines import * class AbstractAdmin(admin.ModelAdmin): list_display = ('name', 'description') class Media: js = ('js/textarea-autosize.js',) css = {'all': ('css/textarea-small.css',),} @admin.register(OrganizationalStructur...
2,002
610
import unittest from cosymlib import file_io from numpy import testing from cosymlib.molecule.geometry import Geometry import os data_dir = os.path.join(os.path.dirname(__file__), 'data') class TestSymgroupFchk(unittest.TestCase): def setUp(self): self._structure = file_io.read_generic_structure_file(d...
2,509
1,050
# -*- coding: utf-8 -*- # import the necessary packages from scipy.spatial import distance as dist from imutils.video import FileVideoStream from imutils.video import VideoStream from imutils import face_utils import numpy as np # 数据处理的库 numpy import argparse import imutils import time import dlib import cv2 def ey...
5,651
3,294
#! /usr/bin/env python3 # -*- coding:utf-8 -*- import rospy import numpy as np import tf import math import cv2 import time from geometry_msgs.msg import Twist, Vector3, Pose from nav_msgs.msg import Odometry from sensor_msgs.msg import Image, CompressedImage from cv_bridge import CvBridge, CvBridgeError import smach...
2,894
1,211
#!/usr/bin/python3 from pathlib import Path from types import SimpleNamespace from mseg_semantic.scripts.collect_results import parse_result_file from mseg_semantic.tool.test_oracle_tax import test_oracle_taxonomy_model REPO_ROOT_ = Path(__file__).resolve().parent.parent # Replace this variables with your own path...
2,041
884
class Response(object): """ """ def __init__(self, status_code, text): self.content = text self.cached = False self.status_code = status_code self.ok = self.status_code < 400 @property def text(self): return self.content def __repr__(self): retu...
375
118
# -*- coding: utf-8 -*- """Gymnasium implementation.""" # Django from django.core.validators import RegexValidator from django.db import models from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ # noqa class Gymnasium(models.Model): """Gymnasium model for the website."...
1,911
612
# Exercicio 01 Tuplas x = int(input('Digite o primeiro numero: ')) y = int(input('Digite o segundo numero: ')) cont = 1 soma = x while cont < y: soma = soma + x cont = cont + 1 print('O resultado eh: {}' .format(soma))
228
92
''' To have a error free way of accessing and updating private variables, we create specific methods for this. Those methods which are meant to set a value to a private variable are called setter methods and methods meant to access private variable values are called getter methods. The below code is an example of g...
832
265
#!/usr/bin/env python3 # coding: utf-8 # MIT License © https://github.com/scherma # contact http_error_418 @ unsafehex.com import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras...
21,013
6,413
import json class TestListRepo: def test_invalid(self, host): result = host.run('stack list repo test') assert result.rc == 255 assert result.stderr.startswith('error - ') def test_args(self, host, add_repo): # Add a second repo so we can make sure it is skipped add_repo('test2', 'test2url') # Run list...
4,104
1,569
class Solution: def isMatch(self, s: str, p: str) -> bool: # this is a dynamic programming solution fot this matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)] matrix[0][0] = True for i in range(1, len(matrix[0])): if p[i - 1] == "*": ...
769
278
# https://open.kattis.com/problems/luhnchecksum for _ in range(int(input())): count = 0 for i, d in enumerate(reversed(input())): if i % 2 == 0: count += int(d) continue x = 2 * int(d) if x < 10: count += x else: x = str(x) ...
405
150
import matplotlib.pyplot as plt import numpy as np def plot_chains(chain, fileout=None, tracers=0, labels=None, delay=0, ymax=200000, thin=100, num_xticks=7, truths=None): if chain.ndim < 3: print("You must include a multiple chains") return n_chains, length, n_var = chain.shape print(n...
2,531
1,062
## ## Evaluation Script ## import numpy as np import time from sample_model import Model from data_loader import data_loader from generator import Generator def evaluate(label_indices = {'brick': 0, 'ball': 1, 'cylinder': 2}, channel_means = np.array([147.12697, 160.21092, 167.70029]), data...
2,063
731
# -*- coding=utf-8 -*- """ # Copyright (c) 2020 PaddlePaddle Authors. 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...
7,793
2,721
import requests from requests import Response class Client: @staticmethod def request(method: str, url: str, **kwargs) -> Response: """ Request method method: method for the new Request object: GET, OPTIONS, HEAD, POST, PUT, PATCH, or DELETE. # noqa url – URL for the new Reques...
727
184
from castervoice.lib.ctrl.mgr.errors.base_class_error import DontUseBaseClassError class BaseGrammarContainer(object): def set_non_ccr(self, rcn, grammar): raise DontUseBaseClassError(self) def set_ccr(self, ccr_grammars): raise DontUseBaseClassError(self) def wipe_ccr(self): ra...
352
124
from django.urls import include, path from . import views from django.views.generic.base import RedirectView # アプリケーションの名前空間 # https://docs.djangoproject.com/ja/2.0/intro/tutorial03/ app_name = 'main' urlpatterns = [ path('', views.index, name='index'), ]
262
100
"""server URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
1,114
389
# coding: utf-8 """ FRED API FRED is a tool for automatically producing RDF/OWL ontologies and linked data from natural language sentences. The method is based on Combinatory Categorial Grammar, Discourse Representation Theory, Linguistic Frames, and Ontology Design Patterns. Results are enriched with NER and...
9,507
2,674
import json from ..connection import get_connection class Metadata: def __init__(self, database): self.connection = get_connection(database).connection # first list is default if nothing is specified (should be extended) # list is ordered as [edge_name, node1_id, edge_node1_id, edge_node2_id, n...
1,496
507
import requests from bs4 import BeautifulSoup def getSummary(link): #Get page response response = requests.get(link) #Parse the pgae soup = BeautifulSoup(response.content,'html.parser') #Find first paragraph summary_p = soup.find('p') #Get the first text summary = summary_p.text[:40] + ...
2,381
673
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path from datetime import date, datetime from sqlite3 import dbapi2 as sqlite from bs4 import BeautifulSoup import simplejson as json import xbmcvfs import xbmcgui import common import connection import database_common as db_common def create(): c = _datab...
18,573
5,628
import copy from configuration.configuration import QuestionnaireConfiguration from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db.models import F from django.template.loader import render_to_string from configuration.models import Configuration, Key, Value, Translati...
16,450
4,126
import matplotlib.pyplot as plt import distance from matplotlib import style from clustering_algorithms.affinity_propagation import AffinityPropagation from clustering_algorithms.custom_k_means import KMeans from clustering_algorithms.custom_mean_shift import MeanShift from clustering_algorithms.custom_mean_shift_strin...
10,152
3,635
# !/usr/bin/env python # -*- coding: utf-8 -*- """Conversion between single-channel integer value to 3-channels color image. Mostly used for semantic segmentation. """ from __future__ import annotations import numpy as np import torch from multipledispatch import dispatch from torch import Tensor from onevision.cv....
2,381
842
""" MIT License Copyright (c) 2019 Simon Olofsson 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 without limitation the rights to use, copy, modify, merge, publish...
5,932
2,644
from typing import Optional, List, Sequence, Union from snuba.datasets.schemas import Schema from snuba.datasets.schemas.tables import TableSchema, WritableTableSchema class DatasetSchemas(object): """ A collection of schemas associated with a dataset, providing access to schemas and DDL functions """ ...
1,831
498
from statistics import mean import csv from aalpy.SULs import DfaSUL, MealySUL, MooreSUL from aalpy.learning_algs import run_Lstar from aalpy.oracles import RandomWalkEqOracle from aalpy.utils import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine num_states = 1000 alph_size = 5 rep...
3,039
1,109
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** Thomas Larsson, Jonas Hauquier **Copyright(c):** MakeHuman Team 2001-2019 *...
2,505
778
#!/usr/bin/env python import sys from os.path import exists import numpy as np import pylab import scipy.interpolate def read_fortran(filename): """ Reads Fortran style binary data and returns a numpy array. """ with open(filename, 'rb') as f: # read size of record f.seek(0) n = np.fromfile(f, dtype='int32...
3,245
1,434
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager Description : Database manager plugin for QGIS (Oracle) Date : Aug 27, 2014 copyright : (C) 2014 by Médéric RIBREUX email : meder...
6,150
1,753
# with the TRACKBAR gui component # we can perform some action my moving cursor import cv2 import numpy as np def funk(): # create one funciton # Now we are not adding any action in it . # just pass pass def main(): img1 = np.zeros((512,512,3) , np.uint8) # create a imgae of size 512 x512 ...
1,711
554
import sys from PIL import Image from enum import Enum, unique # 模块: cd 文件夹路径 再ls ,读取文件! 若是上级界面,路径: ./ im = Image.open('test.png') print(im.format, im.size, im.mode) # 面向过程:函数化!!! # 面向对象(Object Oriented Programming,简称OOP):对象化(包含数据和函数)!!!高度封装 std1 = {'name': 'Machileg', 'score': 89} std2 = {'name': 'mahfljg', 'score'...
9,814
4,111
inputFile = "3-input" outputFile = "3-output" dir = {'L': [-1,0],'R': [1,0],'U': [0,1],'D': [0,-1]} def readFile(): file = open(inputFile, "r") A,B = file.readlines() A,B = [line.split(",") for line in [A,B]] file.close() return A,B def writeFile(a, b): file = open(outputFile, "w+") fil...
1,404
585
from nldi_el_serv.XSGen import XSGen from nldi_el_serv.dem_query import query_dems_shape import py3dep from pynhd import NLDI gagebasin = NLDI().get_basins("06721000").to_crs('epsg:3857') gageloc = NLDI().getfeature_byid("nwissite", "USGS-06721000").to_crs('epsg:3857') cid = gageloc.comid.values.astype(str) print(cid...
942
483
# PyVot # Copyright(c) Microsoft Corporation # 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 # # THIS CODE IS PROVIDED ON AN ...
3,437
1,065
from ralph.api.serializers import RalphAPISerializer from ralph.api.viewsets import RalphAPIViewSet, RalphReadOnlyAPIViewSet from ralph.api.routers import router __all__ = [ 'RalphAPISerializer', 'RalphAPIViewSet', 'RalphReadOnlyAPIViewSet', 'router', ]
271
88
from odoo import models, fields, api from odoo.exceptions import ValidationError class DemoOdooWizardTutorial(models.Model): _name = 'demo.odoo.wizard.tutorial' _description = 'Demo Odoo Wizard Tutorial' name = fields.Char('Description', required=True) partner_id = fields.Many2one('res.partner', strin...
727
219
from django.db import models class PartnerCharity(models.Model): slug_id = models.CharField(max_length=30, unique=True) name = models.TextField(unique=True, verbose_name='Name (human readable)') email = models.EmailField(help_text='Used to cc the charity on receipts') xero_account_name = models.TextFi...
659
203
__all__ = ['LightGBMRegressorModel'] from mmlspark.lightgbm.LightGBMRegressor import LightGBMRegressor, LightGBMRegressionModel from mmlspark.train import ComputeModelStatistics from pyspark.ml.evaluation import RegressionEvaluator from pyspark.sql import DataFrame import pyspark.sql.functions as F from python_data_u...
2,931
886
name = 'Urban Dictionary Therapy' __all__ = ['UDTherapy', 'helper']
80
29
import argparse import os import sys sys.path.append(os.environ['CI_SITE_CONFIG']) import ci_site_config import run import common parser = argparse.ArgumentParser() parser.add_argument("--prov", help="core provider", choices=["psm2", "verbs", \ "tcp", "udp", "sockets", "shm"]) parser.add_argument...
2,453
828
from typing import List def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ low = 0 high = len(nums) - 1 i = 0 ...
664
242
''' Classes ----- GroupXData Data object for holding a dense matrix X of real 64-bit floats, organized contiguously based on provided group structure. ''' import numpy as np from collections import namedtuple from bnpy.data.XData import XData from bnpy.util import as1D, as2D, as3D, toCArray from bnpy.util impo...
14,452
4,438
from django.contrib.auth.models import AbstractUser from django.db.models import BooleanField, CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharF...
915
257
"""Matrix linear algebra routines needed for GP models""" import scipy as SP import scipy.linalg as linalg import logging def solve_chol(A,B): """ Solve cholesky decomposition:: return A\(A'\B) """ # X = linalg.solve(A,linalg.solve(A.transpose(),B)) # much faster version X = ...
3,285
1,109
import ast from flask import Flask, request from flaskext.mysql import MySQL from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' mysql=MySQL() app.config['MYSQL_DATABASE_USER'] = 'admin' app.config['MYSQL_DATABASE_PASSWORD'] = 'noobmaster69' app...
12,504
3,843
from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators from wtforms.fields.html5 import EmailField from src.common.database import db from sqlalchemy import exc class RunnerRegistrationForm(Form): first_name = StringField('First name', [ validators.Length(min=2, max=...
3,514
1,069
import fourparts as fp import pandas as pd file_name = 'chorale_F' df = fp.midi_to_df('samples/' + file_name + '.mid', save=True) chords = fp.PreProcessor(4).get_progression(df) chord_progression = fp.ChordProgression(chords) # gets pitch class sets pitch_class_sets = chord_progression.get_pitch_class_sets() pd.Dat...
901
343
#!/usr/bin/env python3 # Display a Jenkins build job status and progress # Re-use animation functions from https://github.com/jgarff/rpi_ws281x/blob/master/python/examples/strandtest.py import argparse import random import sys import datetime import time from rpi_ws281x import Adafruit_NeoPixel, Color from requests ...
14,677
5,091
import numpy as np from pymoo.model.mutation import Mutation import copy import config as cf import random as rm class MyTcMutation(Mutation): def __init__(self): super().__init__() def _do(self, problem, X, **kwargs): # print("X mutate", X.shape) # for each individual for i i...
3,649
951
""" Defines models """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence from torch.nn.utils.rnn import pad_packed_sequence def init_weights(m): if type(m) == nn.Linear or ...
6,609
2,380
# -*- coding: utf-8 -*- """Operation to find an instance of a particular resource.""" from intercom import HttpError from intercom import utils class Find(object): """A mixin that provides `find` functionality.""" def find(self, **params): """Find the instance of the resource based on the supplied p...
1,007
278
# Time: O(n) # Space: O(n) # 1297 weekly contest 168 12/21/2019 # Given a string s, return the maximum number of ocurrences of any substring under the following rules: # # The number of unique characters in the substring must be less than or equal to maxLetters. # The substring size must be between minSize and maxSi...
4,743
1,622
# encoding:utf-8 from .protocol import Protocol from .protocol import find_head from .codec import BinaryEncoder from tools.converter import hexstr2bytes, str2hexstr from .data_container import * import time import struct from protocol.data_container import DataStruct IMG0203_HEAD = bytes([0x54,0x17,0xfe,0x02]) IMG0203...
2,899
937
"""This module contains the meta information of ConfigUCEstimateImpact ExternalMethod.""" from ..ucsccoremeta import MethodMeta, MethodPropertyMeta method_meta = MethodMeta("ConfigUCEstimateImpact", "configUCEstimateImpact", "Version142b") prop_meta = { "cookie": MethodPropertyMeta("Cookie", "cookie", "Xs:string...
936
330
""" This module provides an interface to MIDI things for OSC """ import sys import time import traceback import thread import threading import copy import string import re from threading import Thread,Lock from math import sqrt from ctypes import * from time import sleep from traceback import format_exc from array im...
2,315
926
import copy import logging from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem from api.models.guest import Guest from api.models.label import Label from api.tests.data.guests import TestGuests from api.tests.data.statuses import TestStatuses from api.tests.data.users import TestUsers from api....
7,128
2,351
import re from typing import Any, Type, Tuple, Union, Iterable from nonebot.typing import overrides from nonebot.adapters import Message as BaseMessage from nonebot.adapters import MessageSegment as BaseMessageSegment from .utils import escape, unescape from .api import Message as GuildMessage from .api import Messa...
5,106
1,565
""" A set of metrics used in machine learning that can be computed in a streaming fashion, without any loss in precision. """ from .accuracy import Accuracy from .accuracy import RollingAccuracy from .confusion import ConfusionMatrix from .confusion import RollingConfusionMatrix from .cross_entropy import CrossEntropy ...
2,689
971
# Future from __future__ import annotations # Standard Library from collections.abc import Callable from typing import Literal, TypeVar # Packages from discord.ext import commands # Local from cd import custom, exceptions __all__ = ( "is_player_connected", ) T = TypeVar("T") def is_player_connected() -> Ca...
628
183
"""Base test for TalisMUD tests. It creates an in-memory database for each test, so they run in independent environments. """ import unittest from pony.orm import db_session from data.base import db from data.properties import LazyPropertyDescriptor # Bind to a temporary database db.bind(provider="sqlite", filena...
986
281
''' This setup.py file sets up our package to be installable on any computer, so that folks can `import henrietta` from within any directory. Thanks to this file, you can... ...tell python to look for `henrietta` in the current directory (which you can continue to edit), by typing *one* of the following commands: `p...
4,074
1,166
import shutil import os import re import tempfile import click import zedenv.lib.be import zedenv.plugins.configuration as plugin_config import zedenv.lib.system from zedenv.lib.logger import ZELogger class SystemdBoot: systems_allowed = ["linux"] bootloader = "systemdboot" def __init__(self, zedenv_d...
18,739
5,454
import os import socket import ipaddress DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # NOTE: this is the MTA host, we need to update it. EMAIL_HOST = 'mailman-exim4-0.mail-suit-service.default.svc.cluster.local' EMAIL_PORT = 25 mailman_ip_address = socket.gethostbyname( os.environ....
1,158
435
# WearMask3D # Copyright 2021 Hanjo Kim and Minsoo Kim. All rights reserved. # http://github.com/jhh37/wearmask3d # # 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, includ...
16,381
6,828
from django.contrib import admin from .models import Admin, Profile # from userapp.models import Book # from driverapp.models import Bus admin.site.register(Admin) admin.site.register(Profile) # admin.site.register(Bus) # admin.site.register(Book)
249
73
''' All ldap operations for test. @author: quarkonics ''' from apibinding.api import ApiError import apibinding.inventory as inventory import apibinding.api_actions as api_actions import zstackwoodpecker.test_util as test_util import account_operations import config_operations import os import inspec...
41,807
14,312
import requests import sys requests.put(f"http://localhost:9200/{sys.argv[1]}?pretty") headers = {"Content-Type": "application/x-ndjson"} data = open(sys.argv[2], "rb").read() requests.post( f"http://localhost:9200/{sys.argv[1]}/_bulk?pretty", headers=headers, data=data )
293
120
class CudaSupportError(RuntimeError): pass
47
14
# -*- coding: utf-8 -*- """ Unit tests for Attributes. """ from __future__ import unicode_literals from __future__ import print_function import logging import os import shutil import tempfile from unittest import TestCase, SkipTest from unittest.mock import MagicMock from qgis.PyQt.QtCore import QVariant from qgis.co...
7,369
2,496
from django.conf import settings def shared_view_contexts(request): return { 'APP_NAME': settings.APPLICATION_NAME, 'SEASONABLE_EMOJI': settings.SEASONABLE_EMOJI, }
191
68
from enum import unique from typing import Reversible from flask import Flask, app, render_template, url_for, redirect, request #import flask from flask.helpers import flash from flask_login.utils import login_fresh from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_manager, login_user, Lo...
12,923
4,116
import torch import torch.nn.functional as F from torch.optim import Adam from torch.utils.data import DataLoader import torchvision from torchvision import transforms from torchvision.models import resnet101 import pytorch_lightning as pl from model.AEINet import ADDGenerator, MultilevelAttributesEncoder from model...
5,560
1,899
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ U0 link-maintenance timers. """ from nmigen import * class LinkMaintenanceTimers(Elaboratable): """ Timers which ensure link integrity is maintained in U0. These...
3,744
1,186
from objects.base_interactions import ProxyInteraction from sims4.utils import classproperty, flexmethod class EnsembleConstraintProxyInteraction(ProxyInteraction): INSTANCE_SUBCLASSES_ONLY = True @classproperty def proxy_name(cls): return '[Ensemble]' @classmethod def generate(cls, proxi...
769
225
import setuptools def get_readme(): with open('README.md') as f: return f.read() INSTALL_REQUIRES = [] TESTS_REQUIRE = ['pytest'] setuptools.setup( name='phonetic_alphabet', version='0.1.0', description='Convert characters and digits to phonetic alphabet equivalents.', long_description=...
742
253