text
string
size
int64
token_count
int64
#!/usr/bin/env python3 from random import randrange import random import pygame, sys from pygame.locals import * import string pygame.font.init() MENU_WIDTH = 1000 MENU_HEIGHT = 1000 GUESS_WIDTH = 1000 GUESS_HEIGHT = 650 HANGMAN_WIDTH = 1300 HANGMAN_HEIGHT = 720 BLACK = (0,0,0) WHITE = (25...
26,490
9,374
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Backend.Dnn import crossMapLRN, crossMapLRNBackward from PuzzleLib.Modules.LRN import LRN class CrossMapLRN(LRN): def __init__(self, N=5, alpha=1e-4, beta=0.75, K=2.0, name=None): super().__init__(N, alpha, beta, K, name) self.gradUsesOut...
2,018
891
import copy from typing import Iterable import numba as nb import numpy as np import spectrum_utils.spectrum as sus def dot(spectrum1: sus.MsmsSpectrum, spectrum2: sus.MsmsSpectrum, fragment_mz_tolerance: float) -> float: """ Compute the dot product between the given spectra. Parameters ----...
4,802
1,439
""" 这个例子将展示如何使用BP神经网络构建多分类的神经网络. """ import sys import classicML as cml DATASET_PATH = './datasets/iris_dataset.csv' CALLBACKS = [cml.callbacks.History(loss_name='categorical_crossentropy', metric_name='accuracy')] # 读取数据 ds = cml.data.Dataset(label_mode='one-hot', ...
797
374
__author__ = "arunrajms" from rest_framework import serializers from pool.models import Pool from rest_framework.validators import UniqueValidator import re TYPE_CHOICES = ['Integer','IP','IPv6','AutoGenerate','Vlan','MgmtIP'] PUT_TYPE_CHOICES = ['Integer','IP','IPv6','Vlan','MgmtIP'] SCOPE_CHOICES = ['global','fabri...
2,596
792
import os import platform from datetime import datetime import time from pathlib import Path import asyncio from dateutil.parser import parse as parsedate from dateutil import tz import aiohttp def longpath(p): if p is None or platform.system() != "Windows": return Path(p) return Path("\\\\?\\" + str...
3,735
1,056
def main(): print(2) print("b") print(2, "b")
58
26
# O(n) time | O(1) space class LinkedList: def __init__(self, value): self.value = value self.next = None def findLoop(head): slow = head.next fast = head.next.next while fast != slow: slow = slow.next fast = fast.next.next fast = head while fast != slow: ...
380
121
import pytest from layers.attention import AttentionLayer from tensorflow.keras.layers import Input, GRU, Dense, Concatenate, TimeDistributed from tensorflow.keras.models import Model import tensorflow as tf def test_attention_layer_standalone_fixed_b_fixed_t(): """ Tests fixed batch size and time steps E...
3,066
1,137
from itertools import zip_longest, islice def to_int_keys_best(l): seen = set() ls = [] for e in l: if not e in seen: ls.append(e) seen.add(e) ls.sort() index = {v: i for i, v in enumerate(ls)} return [index[v] for v in l] def suffix_array_best(...
1,572
655
# -*- coding: utf-8 -*- """ utils.py - Definition of utility functions. """ from collections import namedtuple from lgr.utils import format_cp VariantProperties = namedtuple('VariantProperties', ['cp', 'type', 'when', 'not_when', ...
1,329
402
#!/usr/bin/env python3 # import modules. import sys; sys.path.append("..") import hashlib import json import logging import os import plac import unittest import warnings from tomes_packager.lib.directory_object import * from tomes_packager.lib.file_object import * # enable logging. logging.basicConfig(level=logging....
2,386
788
from unv.web.helpers import url_with_domain, url_for_static def test_url_with_domain(): assert url_with_domain('/path') == 'https://app.local/path' def test_simple_static_url(): assert url_for_static('asd.txt') == '/static/asd.txt'
244
90
import pygame icon = pygame.image.load("diamond_pickaxe.png") screen_weight = 1750 screen_height = 980 pygame.init() window = pygame.display.set_mode((screen_weight, screen_height)) pygame.display.set_caption('Pickaxe clicker') pygame.display.set_icon(icon) # zmienne wytrzymałość_kilofa = 50 max_wytrzymałość_kilof...
10,829
3,923
import os from tempfile import NamedTemporaryFile import h5py import numpy as np import torch from skimage.metrics import adapted_rand_error from torch.utils.data import DataLoader from pytorch3dunet.datasets.hdf5 import StandardHDF5Dataset from pytorch3dunet.datasets.utils import prediction_collate, get_test_loaders...
4,383
1,526
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from catalog.models import Videos, Category, Docs, Subscriber from django.contrib.auth.decorators import login_required @login_required def home(request): template = 'home.html' category = Category....
2,560
797
import MySQLdb db = MySQLdb.connect('localhost', 'root', 'vis_2014', 'FinanceVis') cursor = db.cursor() sql = 'select predict_news_word from all_twitter where symbol=%s order by predict_news_word+0 desc' cursor.execute(sql, ('AAPL', )) results = cursor.fetchall() file_twitter_predict = open('twitter_predict_AAPL.csv...
519
181
""" Dot Plot ========= _thumb: .2, .8 _example_title: Plot distribution. """ import matplotlib.pyplot as plt import numpy as np import arviz as az az.style.use("arviz-darkgrid") data = np.random.normal(0, 1, 1000) az.plot_dot(data, dotcolor="C1", point_interval=True, figsize=(12, 6)) plt.show()
301
127
# https://open.kattis.com/problems/alphabetspam import sys import math xs = input() white = 0 lower = 0 higher =0 other = 0 for i in xs: if i == '_': white += 1 elif ('a' <= i) & (i <= 'z'): lower += 1 elif ('A' <= i) & (i <= "Z"): higher += 1 else: other += 1 print(...
405
166
import numpy as np from sympy import simplify, sqrt, symbols from sympy.stats import Normal, covariance as cov, variance as var def regcoeffs(x, y, z): covxy = cov(x, y) covyz = cov(y, z) varx = var(x) vary = var(y) varz = var(z) # forward f1 = simplify(covxy / varx) f2 = simplify(covy...
3,813
1,619
#!/usr/bin/env python2.7 # coding=<UTF-8> # tweetpic.py take a photo with the Pi camera and tweet it # by Alex Eames http://raspi.tv/?p=5918 import tweepy from subprocess import call from datetime import datetime import requests import json i = datetime.now() #take time and date for filename no...
2,290
890
from pathlib import Path import pandas as pd from torch.utils.tensorboard import SummaryWriter class Logger: def __init__(self, system, log_dir, overwrite=False): self.log_path = Path(log_dir) / 'history.csv' self.system = system self.tb_writer = None # Remove any previous Tens...
1,762
531
# -*- coding: utf-8 -*- ''' author: Soizic Laguitton organization: I2BM, Neurospin, Gif-sur-Yvette, France organization: CATI, France organization: IFR 49 License: `CeCILL version 2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.html>`_ ''' # # Soma-workflow constants # # ''' Job status: ''' NOT_SUBMITTED ...
3,369
1,344
# expected: fail # - this particular check isn't implemented yet # I would have expected this to be valid, but cPython and pypy err out saying "name 'x' is local and global" print "first" x = 1 def f(x): global x print "calling" f(2) print x
250
86
res_words = [] seps = [] ops = [] def load_dom(): with open('data/tokens', 'r') as f: for i in range(7): separator = f.readline().strip() if separator == "_": # Special case [SPACE] separator = " " seps.append(separator) for i ...
1,980
578
# encoding=utf-8 """ Auth: coco369 Email: 779598160@qq.com CreateTime: 2021/07/30 Desc: fastspider核心代码, 实体Item """ class BaseItemMetaClass(type): def __new__(cls, name, bases, attrs): attrs.setdefault("__name__", None) attrs.setdefault("__table_name__", None) attrs.setdefault("__update_key__", None) attrs...
1,101
477
#!/usr/bin/env python # # Public Domain 2014-present MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a com...
26,370
7,739
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'SumDialog.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, Qt...
29,997
11,909
from dataclasses import dataclass, field from typing import Optional from .t_expression import TExpression from .t_gateway import TGateway __NAMESPACE__ = "http://www.omg.org/spec/BPMN/20100524/MODEL" @dataclass class TComplexGateway(TGateway): class Meta: name = "tComplexGateway" activation_conditi...
684
226
# -*- coding: utf-8 -*- __author__ = 'M.Novikov' from model.project import Project # Проекты Mantis from pony.orm import * # Работа с базой данных from pymysql.converters import decoders #...
2,371
644
# Generated by Django 2.1.7 on 2019-02-23 18:47 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Address', fields=[ ...
3,577
1,004
from bs4 import BeautifulSoup from threading import Thread import requests from urllib.parse import urlparse,urljoin from urllib import parse class PageFetcher(Thread): def __init__(self, obj_scheduler): self.obj_scheduler = obj_scheduler def request_url(self,obj_url): """ Faz ...
2,713
807
from factories.celery import create_celery from factories.application import create_application celery = create_celery(create_application())
141
36
# MIT License # # Copyright (c) 2020 Anderson Vitor Bento # # 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...
2,098
688
import socket import os from _thread import start_new_thread ip = "localhost" port = 1234 global number_of_connections number_of_connections = 0 server = socket.socket() server.bind((ip, port)) server.listen(5) def handle_client(socket_client): global number_of_connections msg = "You are connected!" ...
1,365
424
#coding=utf-8 import os delete_files=["RCCall.mm","RCCXCall.m"] start_key = "RCCallKit_Delete_Start" end_key = "RCCallKit_Delete_end" def delete_used(file_path): print(file_path) f = open(file_path,"r") lines = f.readlines() f.close() # print(lines) result = [] flag = False for l in lines: if start_key...
658
292
#!/usr/bin/python #-*- coding: utf-8 -*- #--------------------------------------- # # Copyright(c) Aixi Wang 2014-2015 #--------------------------------------- # v1 -- initial version #--------------------------------------- #----------------------- # mail #----------------------- global mail_sender,mail_smtpserver,ma...
525
176
#-*- coding:utf-8 _*- """ @author:charlesXu @file: urls.py @desc: 接口url @time: 2019/05/10 """ # =============== # # apis 下面的路由 # # =============== from django.urls import path from intent_rest_controller import intent_controller from entity_extraction_controller import entity_ext_controller from bot_controll...
631
251
# (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2020 from __future__ import absolute_import import time import urllib3 import unittest import tests.apps.flask_app from ..helpers import testenv from instana.singletons import agent, tracer class TestWSGI(unittest.TestCase): def setUp(self): "...
14,334
5,067
import math import os import random import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision def xyxy2xywh(x): # Transform box coordinates from [x1, y1, x2, y2] (where xy1=top-left, xy2=bottom-right) to [x, y, w, h] y = torch.zeros_like(x) if isinsta...
16,178
6,404
#!/usr/bin/env python # encoding: utf-8 # # 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 Licens...
4,934
1,441
# -*- coding:utf-8 -*- """ Test module docstring. """ import threading from typing import Type class UnsetType: """ Test docstring. """ __slots__ = [] _instance: 'UnsetType' = None _lock: threading.Lock = threading.Lock() def __str__(self): return 'Unset' def __repr__(self)...
926
304
""" Event handler decorators for common Lambda events """ from .api_gateway import ApiGatewayResolver from .appsync import AppSyncResolver __all__ = ["AppSyncResolver", "ApiGatewayResolver"]
193
57
import itertools as it from torch.optim import Optimizer class LookAhead(Optimizer): def __init__(self, base_optimizer,alpha=0.5, k=6): if not 0.0 <= alpha <= 1.0: raise ValueError(f'Invalid slow update rate: {alpha}') if not 1 <= k: raise ValueError(f'Invalid lookahead steps...
1,351
403
from tkinter import * # import expdate import mysql.connector db_connect=mysql.connector.connect(host="localhost",user="root",password="maan",database="expense") db_cursor=db_connect.cursor() def add_expense(day,month,year): print("add exp") window=Tk() window.title("Expense list") l_message=Label(w...
2,263
976
from __future__ import division from BlackJack.UserInterface import tk from BlackJack.UserInterface import tkFont from BlackJack.UserInterface import BlackJackWindows from BlackJack.UserInterface import SelectGameType from BlackJack.UserInterface import Helpers class BlackJackUI(object): def __init__(self): ...
1,217
392
from .country import Country from .game import Game from .game import Bid from .user import User from .grape import Grape from .wine import Wine from .base import new_id __all__ = [ "new_id", "Country", "Game", "Grape", "User", "Wine", ]
263
94
import random p = str(input('digite o nome do primeiro aluno :')) s = str(input('o nome do segundo aluno :')) t = str(input('o nome do terceiro aluno :')) q = str(input('o nome do quato aluno :')) lista = [p, s, t, q] aluno = random.choice(lista) print('o aluno sorteado foi {}'.format(aluno))
295
108
#!/usr/bin/env python3 import gym import torch import numpy as np import multiprocessing as mp import os import pickle import sys import time import logging import cma import argparse from torchmodel import StandardFCNet def _makedir(name): if not os.path.exists(name): os.makedirs(name) def get_logger():...
12,389
4,236
""" 気温の関するモジュール """ import numpy as np def get_corrected_TMP(TMP: np.ndarray, ele_gap: float) -> np.ndarray: """気温の標高補正 Args: TMP (np.ndarray): 気温 [℃] ele_gap (np.ndarray): 標高差 [m] Returns: np.ndarray: 標高補正後の気温 [C] Notes: 気温減率の平均値を0.0065℃/mとする。 """ return TM...
342
216
from abc import (ABC, abstractmethod) import os import rastervision as rv class LabelStoreDefaultProvider(ABC): @staticmethod @abstractmethod def is_default_for(task_type): """Returns True if this label store is the default for this tasks_type""" pass @staticmethod @abstractmetho...
2,386
745
import sys import os from flask import Flask, flash, redirect, render_template, request, url_for, session from flaskext.mysql import MySQL from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_session import Session from database import Database from makedb import MakeDB from helpers import ge...
6,425
1,728
from django.db import models # Create your models here. class GuestBook(models.Model): user = models.CharField(max_length=15, verbose_name="User") date = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name="Published") content = models.TextField(verbose_name="Content") class Me...
448
141
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import pandas as pd import random import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense,Flatten,GlobalAveragePooling2D,Input,Lambda from tensorflow.keras.models import Model,load_model import tensorflow.kera...
34,859
14,325
import numpy as np import astropy.units as u def snr(signal, detector): """ Calculate the SNR of a signal in a given detector, assuming that it has been detected with an optimal filter. See e.g. arxiv.org/abs/1408.0740 Parameters ---------- signal : Source A Source object which ...
1,027
348
''' Script to plot the accuracy and the fairness measures for different algorithms from the log files ''' import matplotlib matplotlib.use('agg') from matplotlib import pyplot as plt import os print(os.getcwd()) import numpy as np plt.style.use('ggplot') def create_acc_lists(filepath): train_acc = [] train_d...
6,898
2,771
import requests from satella.coding.decorators import retry @retry(3, exc_classes=requests.RequestException) def get_yandex_request(url, arguments) -> dict: """ Return a JSON object querying Yandex at provided parameters. Handling CSRF will be done automatically. :param url: URL to ask :param ar...
682
199
# Copyright (c) Microsoft Corporation # # All rights reserved. # # MIT License # # 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...
6,142
1,911
import tkinter as tk import sys class PrintLogger(): # create file like object def __init__(self, textbox): # pass reference to text widget self.textbox = textbox # keep ref def write(self, text): self.textbox.insert(tk.END, text) # write text to textbox # could also scroll to end ...
1,090
287
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================ # ByteWeiser - Byte comparison and replacement tool # Main script # Copyright (C) 2021 by Ralf Kilian # Distributed under the MIT License (https://opensource.org/licenses/MIT) # # GitHub: https...
2,695
813
import altair as alt import os import pandas as pd import streamlit as st import sys from datetime import datetime from dateutil.relativedelta import relativedelta from dotenv import load_dotenv from plaid.api_client import ApiClient from plaid.exceptions import ApiException from pathlib import Path from traceback imp...
9,798
3,012
import yaml import argparse import sys import os import subprocess import time def get_devvnet(filename): with open(filename, "r") as f: buf = ''.join(f.readlines()) conf = yaml.load(buf, Loader=yaml.Loader) # Set bind_port values port = conf['devvnet']['base_port'] for a in conf['devv...
16,818
5,516
#!/usr/bin/env python # coding: utf-8 # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. ''' This tool submits a QASM file to any backend and show the result. It requires 'Qconfig.py' to set a token o...
5,896
1,968
"""adding usrname column Revision ID: 175f5441bd46 Revises: 186abcf43cae Create Date: 2021-11-20 22:54:04.157131 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '175f5441bd46' down_revision = '186abcf43cae' branch_labels = None depends_on = None def upgrade()...
445
204
from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from nucleus.models import ( AbstractBaseModel, EmailRecord, TeamMember, ) User = get_user_model() class Team(AbstractBaseModel): name = models.CharField(max_length=255) logo_url = models...
2,356
714
""" Lazy loading modules """ import sys import importlib.util class DeferredModuleError: """ Class to throw an error if you try to use a modules that wasn't loaded """ def __init__(self, moduleName): self._moduleName = moduleName @property def moduleName(self): """ Return the name o...
1,826
546
import numpy as np from keras.optimizers import Adam, SGD from tensorflow.keras.metrics import AUC import metrics from networks.unet_nn import unet from networks.unet_res_se_nn import unet_res_se from networks.focus import get_focusnetAlpha from networks.resnet import get_res from data_processing.generate_new_dataset...
4,811
1,972
""" An implementation of Bohnanza @author: David Kelley, 2018 """ import random from collections import defaultdict class Card: """Card Object Name and point thresholds are the only properties. The point thresholds are organized the way they are on the card - to get 1 point, you need th number of...
9,466
2,971
"""Tests for calling other functions, and the corresponding checks.""" from pytype import utils from pytype.tests import test_inference class CallsTest(test_inference.InferenceTest): """Tests for checking function calls.""" def testOptional(self): with utils.Tempdir() as d: d.create_file("mod.pyi", "...
1,872
673
import unittest import lecture1_code00 as dl from sklearn.datasets.samples_generator import make_blobs class TestDeepLearning(unittest.TestCase): def setUp(self): self.X, self.Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60) def tearDown(self): del self.X del ...
724
334
#-*-coding: utf-8 -*- """ /dms/edumediaitem/views_manage.py .. enthaelt den View fuer die Management-Ansicht des Medienpaketes Django content Management System Hans Rauch hans.rauch@gmx.net Die Programme des dms-Systems koennen frei genutzt und den spezifischen Beduerfnissen entsprechend angepasst werden. ...
2,389
802
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .feature_engineering import get_features_for_deep_gaussian from .convnet import ConvModel from .rnn import RNNModel...
414
128
from django.http import HttpResponse, JsonResponse, Http404 from django.core.exceptions import PermissionDenied from rest_framework.parsers import JSONParser, FormParser, MultiPartParser from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework import generics from rest_framework.response im...
3,546
922
import ddt import mock from unittest import TestCase from muduapiclient.client import MuduApiClient, gen_signed_params import time @ddt.ddt class MuduApiClientTests(TestCase): @ddt.unpack @ddt.data( ('ACCESS_KEY', 'SECRET_KEY', {'page':1, 'live_status':2}), ) def test_gen_signed_params(self, a...
1,089
429
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from productapp.views import product_list from reviewapp.views import index urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), ...
586
187
__doc__ = ''' 井字棋基础设施 包含棋盘类与单局游戏运行内核 ''' from threading import Thread from time import process_time if 'enums': OK = 0 # 游戏继续 ENDGAME = 1 # 形成三连 DRAW = 2 # 棋盘已满平局 INVALID = -1 # 非法返回值(类型错误/出界) CONFILCT = -2 # 冲突落子(下于已有棋子位置) ERROR = -3 # 代码报错 TIMEOUT = -4 # 代码超时 class Board: ""...
5,970
2,463
"""Escreva um programa que leia o valor em metros e o exiba convertido em centímetros e milímetros""" from utilidadescev.dado import leia_real n = leia_real('Digite a metragem: ') km = n / 1000 hec = n / 100 dam = n / 10 dec = n * 10 cent = n * 100 mil = n * 1000 print(f'{km:.3f}km') print(f'{hec:.2f}hm') print(f'{da...
400
203
import os import pyowm from datetime import datetime from timezone_conversion import gmt_to_eastern #API_KEY = os.environ['API_KEY'] owm=pyowm.OWM('0833f103dc7c2924da06db624f74565c') mgr=owm.weather_manager() def get_temperature(): days = [] dates = [] temp_min = [] temp_max = [] forecaster = mgr...
1,015
351
import copy import datetime import json import math import multiprocessing import numpy as np import os import pandas as pd import pydotplus import random import re import time from math import * from sklearn import metrics _CLUSTER_DATA = './bike_sharing_data/mydata' RATEDATA = './bike_sharing_data/my...
82,647
26,017
## @ingroup Components-Energy-Storages-Batteries-Constant_Mass # Lithium_Ion_LiFePO4_18650.py # # Created: Feb 2020, M. Clarke # Modified: Sep 2021, R. Erhard # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- ...
4,692
1,435
# Copyright 2011-2012 10gen, 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 to in writing,...
83,182
22,601
''' Created on Oct 20, 2015 @author: bardya ''' import os import argparse from Bio import SeqIO def parse_args(): parser = argparse.ArgumentParser(description='Delete all duplicate entries (header+sequence) in fasta. If only sequence identical, add "| duplicate" to header.') parser.add_argument('-i', des...
3,544
1,136
def log_improvement(value): """function to log improvements to the command line. Parameters ---------- value : int or float The value for the improvement """ print("Improvement : " + str(value)) def log_passed_worse(value): """function to log the passing of worse solutions...
491
142
# https://github.com/pokidovea/immobilus/issues/30 from immobilus import immobilus # noqa from immobilus.logic import fake_time, fake_localtime, fake_gmtime, fake_strftime, fake_mktime from datetime import datetime class SomeClass(object): method = None def test_fake_time(): SomeClass.method = fake_time ...
897
318
import abc class Plotter(abc.ABC): def __init__(self, ax=None, bokeh_fig=None): if not ax and not bokeh_fig: raise ValueError('ax or bokeh_fig should be provided.') self._ax = ax self._bokeh_fig = bokeh_fig def plot(self, *args, **kwargs): raise NotImplementedErro...
322
111
#!/usr/bin/env python import re from param import * from emit import Emit # Emit docs in a form acceptable to the APM wiki site class WikiEmit(Emit): def __init__(self): wiki_fname = 'Parameters.wiki' self.f = open(wiki_fname, mode='w') preamble = '''#summary Dynamically generated lis...
2,531
819
#!/usr/bin/env python from PIL import Image import os, os.path import cv2 import sys # Detect faces, then returns number of faces. def detect_face(image_path, face_cascade): img = cv2.imread(image_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Change the values based on needs. faces = face_cascade.detect...
1,038
420
from.Model import Model import numpy as np def majority(values): return max(set(values), key=values.count)#melhor valor def average(values): return sum(values)/len(values)#ou a media class Ensemble(Model): def __init__(self, models, fvote, score): super(Ensemble, self).__init__() self.m...
1,241
390
#!/usr/bin/env python """pygto900 contains commands to interface with a astro-physics gto900 mount """ import serial import io import sys import string import math import time from binutils import * from datetime import datetime from astropy.coordinates import Angle def airmass(a): ang = Angle(90, unit='degree'...
11,915
4,330
# -*- coding: utf-8 -*- """ Created on Wed Jun 23 15:56:55 2021 @author: Kathryn Haske Create plotly graphs for webpage """ import pandas as pd import plotly.graph_objs as go def line_graph(x_list, df, name_col, y_cols, chart_title, x_label, y_label): """ Function to create plotly line graph Args: ...
2,850
880
import jax.numpy as jnp from jax import vmap from jax.scipy.optimize import minimize import chex import typing_extensions from typing import Any, NamedTuple import warnings from jsl.experimental.seql.agents.agent_utils import Memory from jsl.experimental.seql.agents.base import Agent from jsl.experimental.seql.util...
2,505
748
from .abusech import AbuseCh from collections import namedtuple from datetime import datetime class UrlHaus(AbuseCh): base_url = 'https://urlhaus.abuse.ch' urls = namedtuple('UrlHaus', ['id', 'date_added', 'url', 'url_status', 'threat', 'tags', 'urlhaus_link', 'reporter']) payloads = namedtuple('Payload',...
2,379
790
# Copyright 2021 John Reese # Licensed under the MIT license from .cli import CliTest from .core import CoreTest
114
38
"""eafm fixtures.""" import pytest from tests.async_mock import patch @pytest.fixture() def mock_get_stations(): """Mock aioeafm.get_stations.""" with patch("homeassistant.components.eafm.config_flow.get_stations") as patched: yield patched @pytest.fixture() def mock_get_station(): """Mock aio...
442
158
import os from django.conf import settings from django.core.checks import Error, register from thorbanks.settings import configure, parse_banklinks @register def check_model_settings(app_configs, **kwargs): issues = [] manual_models = getattr(settings, "THORBANKS_MANUAL_MODELS", None) if manual_models...
5,894
1,515
"""Defining and analysing axisymmetric optical systems.""" import itertools from functools import singledispatch from dataclasses import dataclass from abc import ABC, abstractmethod from typing import Sequence, Tuple, Mapping import numpy as np import scipy.optimize from . import abcd, paraxial, functions, ri from .fu...
36,028
11,495
from sys import argv, exit from os.path import expanduser as expu, expandvars as expv from os.path import basename, dirname, abspath, isdir, exists from subprocess import Popen, PIPE from builtins import input from rm_protection.config import Config c = Config() evaledpaths = [] def pprint(msg): global c pr...
4,705
1,364
"""Модуль для создания и работы с токенами""" import logging import re import string from enum import IntEnum from functools import lru_cache from typing import Tuple, Iterator from nltk.corpus import stopwords from nltk.tokenize import ToktokTokenizer from nltk.tokenize.api import TokenizerI from ..config import Reg...
6,856
2,620
from array import array import rx import rxsci as rs def test_to_array(): actual_result = [] source = [1, 2, 3, 4] rx.from_(source).pipe( rs.data.to_array('d') ).subscribe( on_next=actual_result.append ) assert actual_result == [array('d', [1, 2, 3, 4])]
299
119
#!/usr/bin/env python3 """============================================================================= los for Little-Oven. los (Little Oven Setup) prepares a Raspberry Pi for Little-Oven development. This module does the actual work. los (no extension) is a bash script that creates a service that runs this...
18,942
6,424