text
string
size
int64
token_count
int64
# coding: utf-8 # funcions for quick testing import numpy as np # helper functions def normalization(arr, normalize_mode, norm_range = [0,1]): """ Helper function: Normalizes the image based on the specified mode and range Args: arr: numpy array normalize_mode: either "whiten", "normalize_cl...
4,138
1,246
import datetime t = (3, 30, 2019, 9, 25) x = datetime.datetime(t[2], t[3], t[4], t[0], t[1]) print(x.strftime("%m/%d/%Y %H:%M"))
130
74
# Autoencoder based on: https://towardsdatascience.com/predictive-maintenance-of-turbofan-engine-64911e39c367 import argparse import pandas as pd import numpy as np import itertools import logging import random import os from scipy.spatial.distance import pdist, squareform from sklearn.metrics import confusion_matrix...
8,654
3,143
#! /usr/bin/env python # vim: set fileencoding=utf-8 import sys import json def main(): args = sys.argv[1:] fn = args[0] with open(fn) as fp: d = json.load(fp) # Using sorted() to get same results in Python 2 and 3. for k, v in sorted(d.items()): assert isinstance(v, list) ...
437
174
# -*- coding: utf-8 -*- import os import datetime import time import MySQLdb as mdb LIB_INDEXES = 'D:\\TEMP\\librusec' MYSQL_HOST = '127.0.0.1' MYSQL_BASE = 'books100' MYSQL_LOGIN = 'root' MYSQL_PASSW = 'qwerty' SQL_CHECK_BASE = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%s'" SQL_CREATE...
6,070
2,041
# -*- coding: utf-8 -*- import Shift as shi import Enum as enu def evalShift(individual): """ This method is grobal method. This method is evaluation. If you need new evaluation method, you must define it as follows. RETURN: evaluation values """ shift = shi.Shift(individual) # Get indiviaual of ...
1,328
620
from .version import __version__ __version__
46
14
from sqlalchemy import Column, Integer, String from app.database import Base class Word(Base): id = Column(Integer, primary_key=True, index=True, autoincrement=True) origin = Column(String, index=True, unique=True, nullable=False) pronunciation = Column(String) translation = Column(String) creat...
375
112
from PIL import Image import matplotlib.pyplot as plt import numpy as np import bdlb import torch import json # path_img = './data/test_result/t5/' # path_img = './results_18_ce_noshuffle/2_' # # image = Image.open(path_img + '100.png') # plt.imshow(image) # plt.show() # # overlay = Image.open(path_img + 'overlay.png'...
912
385
import telebot bot = telebot.TeleBot("879497357:AAHxUAZR2ZMy7q1dsC12NoFOmvBnKo9a3FA") @bot.message_handler(content_types=['text']) def echo_all(message): bot.send_message(message.chat.id, message.text) bot.polling( none_stop = True )
238
112
# -*- coding: utf-8 -*- from model.address import Address import random import string import os.path import json import getopt import sys import jsonpickle try: opts, args = getopt.getopt(sys.argv[1:], 'n:f:', ['number of address', 'file']) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n ...
2,980
901
"""``phyphy`` package for automating and parsing HyPhy (>=2.3.7) standard analyses. Written by Stephanie J. Spielman. Test modules ---------------- * phyphy_test """ from phyphy import *
192
68
import scripts.screen_interface as si import scripts.game_interface as gi import ctypes import os import keyboard import uuid GI = gi.GameInterface() # find center of screen user32 = ctypes.windll.user32 screenSize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) centerPoint = tuple(i/2 for i in screenSize) p...
613
216
import json import queue from control.WorkerQueue import WorkerQueue as WQ from data.StorageIO import StorageIO ''' The WorkerControl coordinates workers and assigns jobs. Worker register themself at startup. The controller queues workers as well as jobs in two seperate queues. As soon as a worker and a job are availa...
4,052
1,146
import discord import sys import random import aiohttp import logging token = sys.argv[1] group = sys.argv[2] tokenno = sys.argv[3] msgtxt = sys.argv[4] useproxies = sys.argv[5] logging.basicConfig(filename='RTB.log', filemode='w', format='Token {}'.format(str(tokenno))+' - %(levelname)s - %(message)s',le...
986
350
# Generated by Django 3.1.7 on 2021-05-07 03:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('school', '0017_emplois_emp'), ] operations = [ migrations.CreateModel( name='ListEmplois', fields=[ ...
570
183
from model.gpt import gpt import tensorflow as tf import numpy as np def gpt_encoder(model_config, features, labels, mode, target, reuse=tf.AUTO_REUSE): input_ids = features["input_ids"] past = features.get('past', None) model = gpt.GPT(model_config) if model_config.get("scope", None): scope = model_config...
522
220
import os def gcat(filenames): for filename in filenames: with open(filename) as f: for line in f: yield line def ggrep(pattern, filenames): for filename in filenames: with open(filename) as f: for line in f: if pattern in line: ...
900
279
import binaryninja from .breach_arch import BreachArch BreachArch.register() from .breach_programview import BreachProgramView BreachProgramView.register() from .breach_calling_convention import BreachCallingConvention from .breach_platform import BreachPlatform
265
77
from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError from rest_framework.decorators import api_view from rest_framework import status from swot_item_vote.models import Vote from swot_item.models import SwotItem from .serializers import serialize, get_item_confidence from swot.m...
2,460
805
#!/usr/bin/env python3 ################################################################################# ################# Helper Module ################################################# ################# Provides abstraction to car sensors and PHY layer ############# ##################################################...
30,553
10,904
def partition(a, start, end): pivot = a[start] left = start + 1 right = end met = False # Iterate until i reaches j in the middle while not met: while left <= right and a[left] <= pivot: left = left + 1 while right >= left and a[right] >= pivot: right = right - 1 ...
879
410
""" Copyright (c) 2021 Aiven Ltd See LICENSE for details Algorithms to help with redistributing parts across servers for tables using the Replicated family of table engines. This does not support shards, but this is the right place to add support for them. """ from astacus.common.ipc import SnapshotFile from astacus....
5,787
1,819
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2012 Timothy Farrell # # See the included LICENSE.txt file for licensing details. # Import System Modules import sys import unittest # Import Custom Modules import rocket # Define Constants PY3K = sys.version_info[0] > 2 # Define T...
1,301
464
from setuptools import setup setup( name='Unet', version='', packages=['models'], url='', license='', author='hemanth sharma', author_email='', description='' )
206
69
import pygame from side_scroller.constants import BLACK from side_scroller.settings import GameSettings, Fonts from side_scroller.player import Player, Hitbox from side_scroller.constants import GAME_NAME class Game(): def __init__(self): self.player = Player(0, Player.y_bottom_barrier) self.scree...
2,757
883
def get_min_drops(N, k): if N == 0 or N == 1 or k == 1: return N possibilities = list() for i in range(1, N + 1): possibilities.append( max(get_min_drops(i-1, k-1), get_min_drops(N-i, k)) ) return min(possibilities) + 1 # Tests assert get_min_drops...
366
155
#coding=utf-8 import sys, os import socket import hashlib import virus_total_apis from PyQt4 import QtCore sys.path.append("..") from publicfunc.fileanalyze import PEFileAnalize, getFileInfo class UploadFile(QtCore.QThread): finishSignal = QtCore.pyqtSignal(int, tuple) ''' @文件名 @用户公钥 ''' def ...
3,525
1,182
import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("tt0815550@gmail.com", "AureliaK1609") msg = "YOUR MESSAGE!" server.sendmail("e.kaczmarek01@gmail.com", "tt0815550@gmail.com", msg) server.quit()
240
117
#!/usr/bin/env python # -*- coding: utf-8 -*- import string class Caesar(object): def __init__(self): self.ALPHABET = string.ascii_letters def character_type(self, character): """ Returns the alphabet box """ if character.isupper(): return string.ascii_uppercase ...
1,450
398
# Informe um nº e mostre sua tabuada print('-' * 36) n = int(input('Digite um nº e veja sua tabuada: ')) print('=' * 36) for i in range(1, 11): print(n, 'x', i, '=', n * i) print('=' * 36)
193
95
""" Split: dividir string Join: juntar uma lista (str) Enumerate: enumerar elementos da lista (iteráveis) """ string ='O Brasil é o pais do futebol, o Brasil é penta.' lista_1 = string.split(' ') lista_2 = string.split(',') print(lista_1) print(lista_2) palavra = '' contagem = 0 for valor in lista_1: print(f'A pal...
473
183
import pytest from commitizen import cmd @pytest.fixture(scope="function") def tmp_git_project(tmpdir): with tmpdir.as_cwd(): cmd.run("git init") yield tmpdir @pytest.fixture(scope="function") def tmp_commitizen_project(tmp_git_project): with tmp_git_project.as_cwd(): tmp_commitize...
484
172
list = [3, 4] "{3}".format(*[1, 2, *list]) "{4}".format(*[1, 2, *list]) "{1}".format(*[1, 2, *list]) "{3}".format(*[*list, 1, 2]) "{4}".format(*[*list, 1, 2]) "{1}".format(*[*list, 1, 2])
188
115
import sys import re from typing import Any, Optional, IO, Sequence from argparse import ArgumentParser as CoreArgumentParser, Namespace, _SubParsersAction from .markdown import MarkdownFormatter, MarkdownHelpAction from .bashcompletion import BashCompletionAction, hook as bashcompletion_hook ArgumentSubParser = _S...
2,547
700
from flask import Flask, render_template, request, redirect,Blueprint, json, url_for, session from modules import dataBase,usuario import psycopg2, os, subprocess, bcrypt # #def getData(): # DATABASE_URL = os.environ['DATABASE_URL'] # con = psycopg2.connect(DATABASE_URL, sslmode='require') # return con ###...
524
181
import plistlib from pathlib import Path from datetime import datetime, timezone, timedelta class Validate: """ Validate an unpacked .ipa file in various ways The following rules are enforced. All are treated as errors, except as noted: req-001: The root must contain a sub-directory called 'Payload' ...
6,192
1,844
import pandas import rtree import networkx import numpy as np import cv2 from skimage.measure import regionprops from merlin.core import analysistask from merlin.util import imagefilters class SumSignal(analysistask.ParallelAnalysisTask): """ An analysis task that calculates the signal intensity within the ...
6,183
1,803
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from nornir.core.task import Task from netests import log from netests.tools.file import open_file from netests.protocols.facts import Facts from netests.select_vars import select_host_vars from netests.comparators.log_compare import log_compare, log_no_yaml_data from net...
3,012
950
#おまじない from tkinter import Tk, Button, X, Frame, GROOVE, W, E, Label, Entry, END import numpy as np import os from matplotlib import pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # プロットする関数 def graph(data): # 大きさ(6,3)のグラフを生成する fig = plt.Figure(figsize=(6,3...
1,579
833
# coding=utf-8 """ """ from . import mutation from . import crossover from . import base class BinaryGA(base.GeneticAlgorithm): """A binary encoded genetic algorithm.""" def num_bits(self): """Return the number of bits used by the encoding scheme. Returns: int: The number of bi...
1,326
393
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import os # TODO: Remove entirely if you don't register GStreamer elements below import pygst pygst.require('0.10') import gst import gobject from mopidy import config, ext __version__ = '0.1.0' # TODO: If you ne...
1,230
384
"""Farmer class tests. :author: Someone :email: someone@pnnl.gov License: BSD 2-Clause, see LICENSE and DISCLAIMER files """ import unittest from im3agents import FarmerOne class TestFarmers(unittest.TestCase): def test_farmerone(self): error_min_age = FarmerOne(age=-1) error_max_age ...
698
249
from tool.runners.python import SubmissionPy WHITE = 0 BLACK = 1 DIRECTIONS = { "e": (-1, 0), # (x, y) with axes right/bottom "se": (-0.5, 1), "sw": (0.5, 1), "w": (1, 0), "nw": (0.5, -1), "ne": (-0.5, -1), } class ThChSubmission(SubmissionPy): def run(self, s): flipped_tiles = {...
1,744
733
n = int(input()) l1 = list() l2 = list() for _ in range(n): t, v = input().split() l1.append(int(t)) l2.append(float(v)) result = 0 for i in range(len(l1) - 1): result += ((l2[i] + l2[i + 1]) / 2) * (l1[i + 1] - l1[i]) print(result / 1000)
259
133
__version__ = '3.1.0rc1' __license__ = "Apache Software License"
66
28
n = int(input()) a, l, p = map(int, input().split()) if a >= n and l >= n and p >= n: print("S") else: print("N")
126
56
"""---------------------------------------------------------------------------- This is the core of the parsing stage: *re_find comments will search for everything between the $$ and EOL *re_findDataLabels will search for everything between the start of a tag (##) and the start of the next tag ignoring the...
643
183
# This is a lightweight ML agent trained by self-play. # After sharing this notebook, # we will add Hungry Geese environment in our HandyRL library. # https://github.com/DeNA/HandyRL # We hope you enjoy reinforcement learning! import pickle import bz2 import base64 import numpy as np import torch import torch.nn as ...
607,382
498,379
# -*- coding: utf-8 -*- # # Copyright: (c) 2019, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2...
5,879
1,822
############################################################################ # # Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). # Contact: http://www.qt-project.org/legal # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # ...
3,062
873
from ..open_oas.builder.builder import OasBuilder from unittest import TestCase from ..tests.schemas.schemas import PaginationSchema from ..open_oas.decorators import Deferred, path_parameter class TestPathParameter(TestCase): def run_tests(self, builder: OasBuilder): data = builder.get_data() par...
3,618
893
from load import * from _2048 import _2048 from numpy import * from pybrain.datasets import ClassificationDataSet from pybrain.utilities import percentError from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure.modules ...
3,214
1,185
#!/usr/bin/env python3.8 from passwords import Credentials from login import accounts import random #create credentials func def create(fname,lname,user,passwords,email): newCredentials = Credentials(fname,lname,user,passwords,email) return newCredentials #delete ''' function to delete credentials & accounts '...
2,757
733
from django.test import TestCase from django.test.client import RequestFactory from django.template import Template, Context from django.template.loader import render_to_string from .models import Author, Book expected_headers = ''' <tr> <th>Name</th><th>The title</th><th>Comment</th><th>Stars</th><th>AuthorID</th> <...
815
252
#!/usr/bin/env python import sys import copy import rospy import tf_conversions import tf.transformations as transform import tf from math import pi import math import thread import os import random import geometry_msgs.msg from geometry_msgs.msg import Pose, PoseArray from trajectory_msgs.msg import JointTrajectory, J...
103,875
33,444
from workflow import web class APIException(Exception): def __init__(self, status, message, url): self.status = status self.message = message self.url = url super(APIException, self).__init__( "{status} > {message}".format( status=self.status, ...
1,378
407
from setuptools import setup, find_packages setup( name='CosmOrc', version='0.1', include_package_data=True, packages=find_packages(), python_requires='>=3.6', install_requires=[ 'Click==7.0', 'numpy==1.16.2', 'pandas==0.24.2', 'pyaml==19.4.1', 'PySnooper...
555
232
from ralph.admin.filters import DateListFilter class BuyoutDateFilter(DateListFilter): def queryset(self, request, queryset): queryset = super().queryset(request, queryset) if queryset is not None: queryset = queryset.filter(model__category__show_buyout_date=True) return querys...
323
93
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
3,976
1,660
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_eda.ipynb (unless otherwise specified). __all__ = ['palet', 'seed_everything', 'print_competition_data', 'get_train_pivot', 'get_train_df', 'count_pct', 'get_classification_df', 'rle2mask', 'make_mask', 'mask2rle', 'plot_mask_image', 'plot_defected_image', ...
9,512
3,517
import pickle import zlib from django.core.cache import cache from fila_da_creche.queries.dt_atualizacao import get_dt_atualizacao from rest_framework.response import Response from rest_framework.views import APIView from vaga_remanescente.queries.distrito import get_distritos from vaga_remanescente.queries.dr...
1,548
558
import glob from flask import Markup SERVER_OPTIONS = [{'text': 'Local Host', 'value': '127.0.0.1'}, {'text': 'Test weved23962', 'value': '10.201.144.167'}, {'text': 'Stage weves31263', 'value': '10.50.8.130'}, {'text': 'Prod wevep31172', 'value': '10.48.164.198'} ...
2,310
739
import streamlit as st from xkcd import xkcd_plot from shared import translate, LANGUAGE_DICT # Set page properties for the app st.set_page_config( page_title="Streamlit & XKCD", layout="wide", initial_sidebar_state="expanded", ) # Initialize the session states - f_list has functions and colors if 'f_list...
2,237
745
""" * Copyright (c) 2008, Flagon Slayer Brewery * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of ...
5,798
2,025
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-12-16 02:43 from __future__ import unicode_literals from django.db import migrations, models import oidc_provider.fields class Migration(migrations.Migration): dependencies = [ ('oidc_provider', '0027_swappable_client_model'), ] opera...
1,018
322
""" This module masks faces using kpts already detected """ import numpy as np import argparse import cv2 #from RCN.preprocessing.tools import BGR2Gray from PIL import Image import h5py def get_parsed_keypoints(path): with open(path) as f: x = f.read() y=x.split('\n') z=[[int(i) for i in ...
4,693
1,862
import cv2 as cv import numpy as np img = cv.imread('test.png') # 将图片大小改为1920*1080h,s,v = cv.split(hsvimg) img = cv.resize(img, dsize=(1920, 1080), fx=1, fy=1, interpolation=cv.INTER_NEAREST) # hsv图像 hsvimg = cv.cvtColor(img, cv.COLOR_BGR2HSV) lower_y = np.array([20, 43, 46]) upper_y = np.array([34, 255, 220]) mask ...
589
332
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-26 00:00 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('parking', '0001_initial'), ] ope...
926
286
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2021/2/26 12:07 下午 @Author : hcai @Email : hua.cai@unidt.com """ import textembedding.get_embedding import textembedding.load_model name = "textbedding" # 加载wv model def load_word2vect(filepath): model = textembedding.load_model.load_word2vect(fil...
988
398
# Import matplotlib.pyplot import matplotlib.pyplot as plt # Set start and end dates start = date(2016, 1, 1) end = date(2016, 12, 31) # Set the ticker and data_source ticker = 'FB' data_source = 'google' # Import the data using DataReader stock_prices = DataReader(ticker, data_source, start, end) # Plot Close stoc...
385
145
# !/usr/bin/env python # coding=utf8 import json import traceback from tornado.web import RequestHandler from pfrock.cli import logger from pfrock.core.constants import PFROCK_CONFIG_SERVER, PFROCK_CONFIG_ROUTER, PFROCK_CONFIG_PORT, ROUTER_METHOD, \ ROUTER_PATH, ROUTER_OPTIONS, ROUTER_HANDLER from pfrock.core.lib...
2,808
841
from typing import List, Union import torch from torch import nn from torch.nn import functional as F from src.modules.max_mahalanobis import MaxMahalanobis, GaussianResult from src.modules.normalize import Normalize from src.resnet.bottleneck_block_v2s3 import create_bottleneck_stage_v2s3 from src.resnet.shared impo...
3,722
1,451
systemMenu = {"ไก่ทอด": 35, "เป็ดทอด": 45, "ปลาทอด": 55, "ผักทอด": 20} menuList = [] def showBill(): print("---- My Food----") totalPrice = 0 for number in range(len(menuList)): print(menuList[number][0],menuList[number][1]) totalPrice += int(menuList[number][1]) print("Totalprice :", t...
504
197
# -*- coding: utf-8 -*- import requests import os # 6000 is a large number to make sure we get all the components of a collection. Please do note that RISE also has a pagination feature, # which can be implemented by clients if they wish. per_page = 6000 # getting the list of collections that the user has access to: ...
2,229
694
# ___ ___ ___ _ _ # |_ _| _ \___| __(_)_ _ __| |___ _ _ # | || _/___| _|| | ' \/ _` / -_) '_| # |___|_| |_| |_|_||_\__,_\___|_| # Made by Robertas64 #Importing the module import os from time import * banner = """ ___ ___ ___ _ _ |_ _| _ \___| __(_)_ _ __| |_...
612
261
import pandas as pd import matplotlib.pyplot as plt def retrieve_data(): train_data = 'data/Nov_btc.csv' test_data = 'data/btc_test_data.csv' df = pd.read_csv(test_data) df = df.drop(columns=['date', 'weighted','volume']) # Columns are set at close, high, low and open. df = df.dropna() data = ...
348
126
import argparse import os import torch import torch.nn as nn import torch.optim as optim import argparse from torch.utils.data import DataLoader from torchvision import transforms from dataset.main import Flickr8kDataset from dataset.caps_collate import CapsCollate from dataset.download import DownloadDataset from mode...
4,715
1,708
import unittest from unittest import TestCase from Implementations.FastIntegersFromGit import FastIntegersFromGit from Implementations.helpers.Helper import ListToPolynomial, toNumbers from Implementations.FasterSubsetSum.RandomizedBase import NearLinearBase from benchmarks.test_distributions import Distributions as d...
2,050
837
# Тип данных МНОЖЕСТВО (set)------------------------ #------------------------------------------ # Инициализация temp_set = {1,2,3} print(type(temp_set), temp_set) temp_list = [1,2,1,2,2,3,4,12,32] temp_set = set(temp_list) print(type(temp_set), temp_set) # Обращения к элементам множества print(100 in temp_s...
633
294
from fabric.api import cd, run, settings, sudo configurations = { 'daily': { 'branch': 'master', 'ssl': False, }, 'dev': { 'branch': 'master', 'ssl': False, }, 'prod': { 'branch': 'prod', 'ssl': False, }, 'staging': { '...
4,744
1,761
""" 파이썬으로 Tree Sort를 구현한 코드입니다. 정확히 말하자면 Binary Search Tree를 구현하였습니다. Binary Search Tree는 각 노드에 값이 있다. Root 노드가 존재한다. 노드의 왼쪽 서브트리에는 그 노드의 값보다 작은 값들을 지닌 노드들로 이루어져있다. 노드의 오른쪽 서브트리에는 그 노드의 값과 같거나 큰 값들을 지닌 노드들로 이루어져있다. 좌우 하위 트리는 각각이 다시 Binary Search Tree 이어야 합니다. """ from __future__ import print_funct...
1,863
1,002
# coding: utf-8 from __future__ import unicode_literals, absolute_import _NOTSET = type( b"NotSet", (object,), {"__repr__": lambda self: "<ValueNotSet>"} )() def get_by_path(keys, source_dict): if "." in keys: key, tail_keys = keys.split(".", 1) if key not in source_dict: ...
446
157
from typing import List import json import e2e.Libs.Ristretto.Ristretto as Ristretto from e2e.Libs.BLS import PrivateKey from e2e.Classes.Transactions.Transactions import Claim, Send, Transactions from e2e.Classes.Consensus.Verification import SignedVerification from e2e.Classes.Consensus.VerificationPacket import V...
3,030
1,176
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # This is an EXUDYN example # # Details: Simulate Chain with 3D rigid bodies and SphericalJoint; # Also test MarkerNodePosition # # Author: Johannes Gerstmayr # Date: 2020-04-09 # # Copyright:This file is part of Exudyn. Exu...
5,105
1,838
import logging import sys import time from typing import List, Optional import uvicorn from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import PlainTextResponse from sklearn.pipeline import Pipeline from src.entities import ( read_app_params, HeartDiseas...
1,915
604
import hashlib import hmac import json import datetime from abc import ABCMeta, abstractmethod from twisted.internet import protocol from mod_config.models import Rule, Actions from mod_honeypot.models import PiPotReport, Deployment from pipot.encryption import Encryption from pipot.notifications import Notification...
8,040
1,847
from sys import modules from functools import wraps from jsonschema import validate from pyhttptest.constants import ( HTTP_METHOD_NAMES, JSON_FILE_EXTENSION, ) from pyhttptest.exceptions import ( FileExtensionError, HTTPMethodNotSupportedError ) from pyhttptest.http_schemas import ( # noqa get_s...
4,852
1,312
from datetime import datetime import arrow import pytest from django.conf import settings from resources.models import Day, Period, Reservation, Resource, ResourceType, Unit TEST_PERFORMANCE = bool(getattr(settings, "TEST_PERFORMANCE", False)) @pytest.mark.skipif(not TEST_PERFORMANCE, reason="TEST_PERFORMANCE not ...
4,523
1,708
# Generated by Django 3.2.8 on 2021-10-12 22:34 from django.db import migrations, models def fill_in_datetime_fields(apps, schema_editor): # Old values in output field of delta table where string instead of json Job = apps.get_model("core", "Job") Job.objects.update( started_at=models.F("created_...
951
301
default_app_config = "wagtail_tag_manager.config.WagtailTagManagerConfig"
74
26
# Copyright 2015 ETH Zurich # # 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, sof...
12,081
3,927
# -*- coding: utf-8 -*- # # Copyright © 2021 Shuoyang Ding <shuoyangd@gmail.com> # Created on 2021-02-11 # # Distributed under terms of the MIT license. import argparse import logging import math import sys logging.basicConfig( format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=lo...
2,347
941
import collections from typing import List def maxDepth(s: str) -> int: stack = [] max_depth = 0 for character in s: if character == '(': stack.append(character) elif character == ')': stack.pop() max_depth = max(max_depth, len(stack)) return max_depth ...
8,865
2,692
#!/usr/bin/env python3 # # Stolen almost verbatim from: # https://gitlab.cern.ch/lhcb-rta/pidcalib2/-/blob/master/src/pidcalib2/pklhisto2root.py ############################################################################### # (c) Copyright 2021 CERN for the benefit of the LHCb Collaboration # # ...
4,684
1,664
d1 = {"koe":4,"slang":0,"konijn":4,"zebra":4} d1["koe"] d2 = {"vis":0,"beer":4,"kip":2} d1.update(d2) print (d1)
112
67
from app.database import crud from fastapi import HTTPException, status def check_for_team_existence(db, team_id): if crud.get_team(db, team_id=team_id) is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Team {} not found".format(team_id)) def check_for_player_existence(db, play...
958
338
""" This module represents the Consumer. Computer Systems Architecture Course Assignment 1 March 2020 """ from threading import Thread from time import sleep class Consumer(Thread): """ Class that represents a consumer. """ def __init__(self, carts, marketplace, retry_wait_time, **kwargs): "...
1,964
515
import torch.nn as nn import torch import numpy as np from torch.autograd import Variable class RNNModel(nn.Module): def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): super(RNNModel, self).__init__() self.hidden_dim = hidden_dim self.layer_dim = layer_dim self.rnn = ...
978
375
""" transaction_set.py Defines the Enrollment 834 005010X220A1 transaction set model. """ from typing import List, Optional from linuxforhealth.x12.models import X12SegmentGroup from .loops import Footer, Header, Loop1000A, Loop1000B, Loop1000C, Loop2000 from pydantic import root_validator, Field from linuxforhealt...
791
312