text
string
size
int64
token_count
int64
""" References: https://github.com/scaelles/OSVOS-TensorFlow """ from __future__ import print_function import os import random import tensorflow as tf import time import numpy as np from utils import models from utils.load_data_finetune import Dataset from utils.logger import create_logger # seed seed = random.randin...
7,273
2,310
from dataclasses import field, dataclass from typing import List from kinopoisk_unofficial.contract.response import Response from kinopoisk_unofficial.model.season import Season @dataclass(frozen=True) class SeasonsResponse(Response): total: int items: List[Season] = field(default_factory=list)
307
89
import subprocess import os import shutil import tempfile import random import string import yaml src_dir=os.path.dirname(os.path.realpath(__file__)) def codepod(*,repository='',image=None,volumes=[],mount_tmp=True,host_working_directory=None,docker_opts=None,git_smart=False,no_pull=False,command=False): if not d...
4,906
1,639
#! /usr/bin/env python3 # coding=utf-8 # Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved. # Copyright 2021 The MLPerf 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...
5,040
1,632
import binaryRepr # Create decorator function to see how many times functions are called def call_counter(func): def helper(*args, **kwargs): helper.calls += 1 return func(*args, **kwargs); helper.calls = 0 helper.__name__= func.__name__ return helper; # Calculate Partition (C_k, ...
3,047
1,008
import os import numpy as np import pandas as pd import experiments.benchmarks.benchmark as benchmark class ActivityBenchmark(benchmark.Benchmark): def __init__(self): super().__init__('activity', (('--sequence_length', 64, int), ('--max_samples', 40_00...
1,712
498
import xml.etree.ElementTree as et from dateutil import parser from django.shortcuts import render from django.shortcuts import redirect from django.core.urlresolvers import reverse import untangle from .forms import MenuplanSearchForm from .forms import MenuplanCreateForm from .tables import MenuplanTable from ....
4,685
1,335
from contextlib import closing from io import StringIO import numpy import pandas from airflow.providers.postgres.hooks.postgres import PostgresHook from psycopg2.extensions import connection as psycopg2_connection from data_detective_airflow.dag_generator.works import WorkType from data_detective_airflow.operators.s...
6,448
1,994
def convert_str_to_date(string): from datetime import datetime datetime.strptime(string, "%Y-%m-%d %H:%M:%S.%f") def create_database(): from attendance.models.Student import Student from attendance.models.WorkingDay import WorkingDay from attendance.models.LectureAttendance import LectureAttendanc...
1,981
672
"""Plangym API implementation.""" from abc import ABC from typing import Any, Callable, Dict, Generator, Iterable, Optional, Tuple, Union import gym from gym.envs.registration import registry as gym_registry from gym.spaces import Space import numpy import numpy as np wrap_callable = Union[Callable[[], gym.Wrapper],...
32,588
8,988
# Layer 2 server script # project worker '''-. +#_pü'-..... ö*+...:(loop):.............................................. m}°: \ €>!: 1. register clients \ &w^: 2. distribute WLs and add them to pending \...
6,426
2,343
import factory from spaceone.core import utils from spaceone.statistics.model.schedule_model import Schedule, Scheduled, JoinQuery, Formula, QueryOption class ScheduledFactory(factory.mongoengine.MongoEngineFactory): class Meta: model = Scheduled cron = '*/5 * * * *' interval = 5 minutes = ...
2,677
804
from datetime import datetime from sqlalchemy import Boolean, Column, DateTime, Integer, SmallInteger, String from app.config import settings from app.db.base_class import Base from app.models.task import Task # noqa class Iteration(Base): __tablename__ = "iteration" id = Column(Integer, primary_key=True, ...
1,324
399
import uuid, hashlib, os, yaml, logging.config, json, requests, re from bcrypt import hashpw, gensalt from collections import namedtuple from sqlalchemy import create_engine from datetime import datetime CONFIG_FILE = os.environ.get('CONFIG_PATH_FILE') ZimbraGrant = namedtuple( 'ZimbraGrant', [ 'target_name', ...
2,833
978
import struct from typing import BinaryIO class CIOType: """ Overview: Basic IO type. Used as base class of all the IO types. """ def read(self, file: BinaryIO): """ Read from binary IO object. :param file: Binary file, ``io.BytesIO`` is supported as well. ...
3,569
1,027
# Mendel's First Law # http://rosalind.info/problems/iprb/ import sys import unittest class iprb: def main(self, hom_dom, het, hom_rec): total = hom_dom + het + hom_rec p_hom_dom = hom_dom / total p_het = het / total p_hom_rec = hom_rec / total prob = 1 prob -= p_hom_rec * ((hom_rec-1)/(total-1)) pro...
958
447
#MAIN method and graphics try: from OpenGL.GL import * from OpenGL import GLU import OpenGL.GL.shaders except: print("OpenGL wrapper for python not found") import glfw import numpy as np from computation import Computation class Graphics: def __init__(self,width,height, computation): ...
3,679
1,262
#!/usr/bin/env python from itertools import chain from pathlib import Path from typing import List INPUT_FILE = Path.cwd().parent / "inputs" / "day06.txt" AnswerGroup = List[str] def transform_input(input: str) -> List[AnswerGroup]: return [x.split("\n") for x in input.strip().split("\n\n")] def part1(groups...
706
257
from symopt.base import SymOptExpr import sympy as sym class ObjectiveFunction(SymOptExpr): """ Symbolic (non)linear optimization objective function. """ def __init__(self, obj, prob, **kwargs): """ Symbolic (non)linear optimization objective function. Parameters ---------- o...
933
258
import json import glob from tqdm import tqdm import os contract_dir = 'contract_data' cfiles = glob.glob(contract_dir+'/contract*.json') cjson = {} print "Loading contracts..." for cfile in tqdm(cfiles): cjson.update(json.loads(open(cfile).read())) results = {} missed = [] print "Running analysis..." for c in...
771
321
#! /usr/bin/python # -*- coding: utf-8 -*- import pytest import numpy as np from textory.util import neighbour_diff_squared, num_neighbours, neighbour_count, create_kernel from textory.statistics import variogram, pseudo_cross_variogram @pytest.fixture def init_np_arrays(): """Inits two random np arrays""" np...
2,266
853
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:152 ms, 在所有 Python3 提交中击败了96.83% 的用户 内存消耗:14 MB, 在所有 Python3 提交中击败了12.45% 的用户 解题思路: 见代码注释 """ class Solution: def lemonadeChange(self, bills: List[int]) -> bool: five = ten = 0 # 5元10元初始各0个 for bill in bills: if bill == 20: # 对于20,...
827
370
#Leia o sexo de uma pessoa, só aceite as letras M ou F; Caso contrario, peça a digitação novamente sexo= str(input('Digite seu sexo [M/F]: ')).strip().upper()[0] while sexo not in 'MF': sexo=str(input('DIGITE O SEXO [M/F]: ')).strip().upper()[0] print('seu sexo é {} e está registrado com sucesso!'.format(sexo))
319
129
from nonebot.adapters.onebot.v11.event import MessageEvent from nonebot.typing import T_State from nonebot.adapters.onebot.v11 import Bot, Message from plugins.uma.plugins.uma_whois.data_source import UmaWhois from plugins.uma import chara #matcher =on_endswith({'是谁','是谁?','是谁?'},priority=5) matcher =UmaWhois().on_reg...
2,157
912
from django.http import HttpResponse from pyspark.sql import SparkSession from django.shortcuts import render from datetime import datetime from core.chartfactory import createBarChart, createPieChart from core.dataprocessor import DataProcessor def sample(request): """ sample python report """ keys =...
8,288
2,592
from mxnet import nd import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))) import utils.common as dataset_commons import cv2 import numpy as np import glob import pandas as pd from gluoncv.data.transforms.presets.ssd import SSDDefaultTrainTransform from matplotlib import...
4,668
1,623
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 # noqa: E501 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ApplyLibraryItemResponse...
12,235
3,610
np_pressures_hPa * math.exp(-gravit_acc * molar_mass_earth* height/(gas_constant*standard_temperature))
103
38
from pytest import mark # if setup.py present, code could be installed as library # so that there's no need include path # pip install -e . from pytest_resources import do_lower_case # from src.for_testing import do_lower_case @mark.coverage def check_lower_case(): assert do_lower_case('SomeThing') == 'something...
322
99
import re import os def changed(lines, token): for line in lines: if line.find(token) != -1: return True return False # copy required files def copy_files(): os.system("cp flow_radar.h ../build/bm/src") # change actions.c to add flow_radar lock def change_actions_c(): actions_c = open("../build/bm/src/actio...
3,476
1,569
#!/usr/bin/python3 # -*- coding: utf-8 -*- # calculation tool for a bridge circuit with two input current sources # two current sources can supply from both of top of the bridge and middle of the bridge # define the voltage name as follows: # Vp: voltage at the top of the bridge # Vn: voltage at the middle of the brid...
2,807
1,196
#Program to check whether the number is an armstrong number or not #Ask user to enter the number number=int(input("Enter the number you want to check armstrong: ")) #To calculate the length of number entered. order=len(str(number)) #Initialise sum to 0 sum=0 temp=number while temp>0: num=temp%10 sum+=num**o...
618
193
from pyexlatex.models.sizes.textwidth import TextWidth from pyexlatex.models.format.rule import Rule class HLine(Rule): """ Draws a horizontal line across the text width. """ def __init__(self, thickness: float = 0.4): super().__init__(length=TextWidth(), thickness=thickness)
304
93
from math import sqrt import asks import datetime import numpy as np import random from PIL import Image from PIL.ImageDraw import Draw from PIL.ImageEnhance import Brightness from PIL.ImageFont import truetype from curio import spawn_thread from curious.commands import Context, Plugin, command from io import BytesIO ...
4,038
1,219
import logging from maskgen import video_tools import random import maskgen.video_tools import os import maskgen import json plugin = "DonorPicker" def transform(img, source, target, **kwargs): valid = [] possible = [] data = {} logging.getLogger('maskgen').info(str(kwargs)) for f in os.listdir(kwa...
2,669
783
import caffe import numpy as np import os import sys import track_model_train as track_model import train_config max_iter = 1000 def eval_avg_scores(config): with open('./track_model/scores.prototxt', 'w') as f: f.write(str(track_model.generate_scores('', config))) caffe.set_device(config.gpu_id) ...
1,228
505
# # Copyright (C) 2014 Conjur Inc # # 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, distri...
1,968
684
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: D:\dev\TS4\_deploy\Client\Releasex64\Python\Generated\protocolbuffers\Social_pb2.py # Compiled at: 2020-12-13 14:24:09 # Size of sourc...
99,362
40,334
__all__ = ["NumpyUtility"] from .NumpyUtility import *
56
22
import sweetviz import pandas as pd if __name__ == '__main__': df = pd.read_csv("BankChurners_clean.csv") report = sweetviz.analyze(df, "Attrition_Flag") report.show_html()
188
72
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from multiprocessing import Process from pyftpdlib import servers from time import sleep from requests import get import socket import psutil import win32api # Al0nnso - 2019 # FTP Reverse Shell # NOT TESTED WITH EXTERN NETWOR...
5,046
1,452
#!/usr/bin/env python3 # coding: utf-8 import os import pytest from deep_reference_parser.io.io import ( read_jsonl, write_jsonl, load_tsv, write_tsv, _split_list_by_linebreaks, _unpack, ) from deep_reference_parser.reference_utils import yield_token_label_pairs from .common import TEST_JSON...
8,321
3,329
import json import responses def test_get_priorities(api, mock, host): mock.add_callback( responses.GET, '{}index.php?/api/v2/get_priorities'.format(host), lambda x: (200, {}, json.dumps([{'id': 1, 'priority': 1}, {'id': 4, 'priority': 4}])) ) resp = api.priorities.get_priorities...
389
152
# ___________________________________________________________________________ # # Prescient # Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # This software is ...
37,185
13,350
from django.contrib import admin from inbound.models import Rule, InboundIP # Register your models here. class InboundIPInline(admin.TabularInline): ''' Inline of Inbound Rule ''' model = InboundIP readonly_fields = ['cidr'] extra = 1 class RuleAdmin(admin.ModelAdmin): model = Rule list_dis...
615
200
from django import forms class LoginForm(forms.Form): userName = forms.EmailField(label='User Name', max_length=55, required=True, \ widget=forms.EmailInput(attrs={'placeholder': 'Username that sends via mail'})) password = forms.CharField(label='Password', max_length=55, required=True, \ widge...
397
113
from collections import Counter def refine(s): result = [] for i in range(len(s) - 1): bigram = s[i:i+2].lower() if bigram.isalpha(): result.append(bigram) return result def solution(str1, str2): counter1, counter2 = Counter(refine(str1)), Counter(refine(str2)) set1, se...
751
288
#!/bin/env python # Copyright STIFTELSEN SINTEF 2016 import suds import urllib2 import sys if len(sys.argv) < 4: print ("Usage:") print ("\t %s gss-url outputfilename token" % sys.argv[0]) exit() # get url: url = sys.argv[1] outputfileName = sys.argv[2] sessionToken = sys.argv[3] wsdlLocation = "https:...
1,226
372
#!/usr/bin/python3 from requests import Request, Session from requests.exceptions import ReadTimeout import urllib3, requests, collections, http.client, optparse, sys, os print("""\033[1;36m _____ _ |__ /_ __ ___ _ _ __ _ __ _| | ___ _ __ / /| '_ ` _ \| | | |/ _` |/ ...
6,728
2,107
#coding: utf-8 #import cl_to_xi_full from __future__ import print_function from builtins import range import numpy as np from cosmosis.datablock import option_section, names as section_names from cl_to_xi import save_xi_00_02, save_xi_22, arcmin_to_radians, SpectrumInterp from legendre import get_legfactors_00, get_leg...
3,397
1,205
""" The ``video`` taxon groups applets implementing video interfaces, that is, interfaces for periodic transfers of 2d arrays of samples of electromagnetic wave properties. Examples: VGA output, TFT LCD capture, TFT LCD output. Counterexamples: SCSI scanner (use taxon ``photo``), SPI LCD output (use taxon ``display``)...
326
93
""" The vasprun.xml parser interface. --------------------------------- Contains the parsing interfaces to ``parsevasp`` used to parse ``vasprun.xml`` content. """ # pylint: disable=abstract-method, too-many-public-methods import numpy as np from parsevasp.vasprun import Xml from parsevasp import constants as parseva...
22,329
6,367
from django.contrib import admin from .models import Produto, TipoProduto, Estoque # Register your models here. class TipoProdutoAdmin(admin.ModelAdmin): search_fields = ['descricao',] admin.site.register(TipoProduto, TipoProdutoAdmin) class EstoqueAdmin(admin.ModelAdmin): search_fields = ['produto__nome'] ...
704
248
import gd, itertools from cube import calculate_cube from ball import calculate_ball from helpers import average client = gd.Client() def calculate_ship(editor: gd.api.Editor, level: gd.Level, portal: gd.api.Object, speed, portal_count: int): pass def calculate_ufo(editor: gd.api.Editor, level: gd.Level, portal:...
3,137
1,150
from collections import defaultdict c=defaultdict(set) f=lambda:[int(i) for i in input().split()] a,b=f() s,e=f() for i in range(s,e+1): x=i%a==0 y=i%b==0 if x and y: c[3].add(i) elif x and not y: c[1].add(i) elif y and not x: c[2].add(i) else: c[4].add(i) o=[] for i in range(1,5): o.append(str(len(c[i])...
341
172
"""Module with useful exceptions for Parser.""" class BadOperationIdentifier(Exception): """Bad operation identifier used.""" class BadOperationArgument(Exception): """Bad argument provided to operation.""" class BadInPlaceValue(Exception): """Bad in-place value provided as argument.""" class Parsin...
520
138
class Singleton(object): _instances = {} def __new__(cls, *args, **kwargs): if cls not in cls._instances: # noinspection PyArgumentList cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instances[cls]
286
93
import json import next.utils as utils from next.apps.AppDashboard import AppDashboard class MyAppDashboard(AppDashboard): def __init__(self,db,ell): AppDashboard.__init__(self,db,ell) def most_current_ranking(self,app, butler, alg_label): """ Description: Returns a ranking of arms in ...
1,919
532
import os import compas from compas.datastructures import Mesh HERE = os.path.dirname(__file__) DATA = os.path.join(HERE, 'data') FILE = os.path.join(DATA, 'faces.obj') mesh = Mesh.from_obj(FILE) print(mesh.summary())
221
86
#!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # 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, merg...
3,957
1,069
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from database.database import ma from models import KoeFavorite from .user_schema import UserSchema from .koe_schema import KoeSchema class KoeFavoriteSchema(ma.SQLAlchemyAutoSchema): Koe = ma.Nested(KoeSch...
408
147
import pickle import sys import numpy as np def geomean(iterable): a = np.array(iterable).astype(float) prod = a.prod() prod = -prod if prod < 0 else prod return prod**(1.0/len(a)) # Define the valid programs here def is_valid_pgm(pgm): pgms = ['471', '4926', '12092', '3449', '4567', '16510', '6118'...
2,786
1,243
import unittest import pandas as pd import numpy as np import os import tempfile import shutil from signatureanalyzer.signatureanalyzer import run_spectra from signatureanalyzer.bnmf import ardnmf from signatureanalyzer.utils import file_loader SPECTRA_ARROW = "../../examples/example_luad_spectra_1.tsv" SPECTRA_WORD ...
3,349
1,322
from .python_utils import make_print_if_verbose def get_child_module_by_names(module, names): obj = module for getter in map(lambda name: lambda obj: getattr(obj, name), names): obj = getter(obj) return obj def get_leaf_modules(module, verbose=False): vprint = make_print_if_verbose(verbose) ...
767
249
""" RRFS-CMAQ File Reader """ import numpy as np import xarray as xr from numpy import concatenate from pandas import Series def can_do(index): if index.max(): return True else: return False def open_mfdataset( fname, convert_to_ppb=True, mech="cb6r3_ae6_aq", var_list=None, ...
32,615
11,287
load("@com_github_atlassian_bazel_tools//multirun:def.bzl", "command") load("@bazel_skylib//lib:shell.bzl", "shell") def copy_to_workspace(name, label, file_to_copy, workspace_relative_target_directory): command( name = name, command = "//build:copy_to_workspace", data = [label], ar...
816
249
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
4,471
1,230
from dataclasses import dataclass from typing import Iterable import torch from torchmetrics import ConfusionMatrix from collections import defaultdict argmax = lambda l: l.index(max(l)) BIRAD_MAP = ['2', '3', '4', '5'] def _lbm(): global BIRAD_MAP BIRAD_MAP = torch.load("./data/BIRADs/meta.pt")['classname...
2,640
988
# # dporules.py # # Author(s): # Matteo Spallanzani <spmatteo@iis.ee.ethz.ch> # # Copyright (c) 2020-2021 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.apach...
34,361
13,061
# -*- coding: utf-8 -*- # System imports import json # Third-party imports import falcon from news_api.endpoints.vespaSearcher import vespaSearch from news_api.endpoints.top_entities import getTopNewEntities from news_api.endpoints.top_clusters import getTopNewCluster # Local imports # from news_api import settings ...
5,896
1,551
#9-Faça um programa que leia um número indeterminado de notas. Após esta entrada de dados, faça seguinte: #. Mostre a quantidade de notas que foram lidas. #. Exiba todas as notas na ordem em que foram informadas. #. Calcule e mostre a média das notas. #. Calcule e mostre a quantidade de notas acima da média calculada. ...
858
321
from fractions import gcd def smallestDiv(): """Finds smallest number that is evenly divisible from 1 through 20""" return reduce(lambda x,y: lcm(x,y), range(1,21)) def lcm(a,b): return (a*b) / gcd(a,b) if __name__ == '__main__': print smallestDiv()
257
105
import argparse import csv import glob import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set() shapes = ['TriangPrismIsosc', 'parallelepiped', 'sphere', 'wire'] def main(): trainsizes = [] avg_acc = [] for f in glob.glob('model/resnet18-all-Adam-l...
1,249
498
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Keith Yang' __email__ = 'yang@keitheis.org' __version__ = '0.1.0' from pyramid.settings import asbool from .bootstrap import BootstrapFactory def includeme(config): DEFAULT = { 'versions': '3.0.3', 'use_min_file': True, 'use_c...
1,482
470
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, no...
3,043
1,008
from quo import Console from quo.pretty import Pretty from quo.panel import Panel DATA = "My name is Quo" console = Console() for w in range(130): console.echo(Panel(Pretty(DATA), width=w))
199
73
#-*- coding: utf-8 -*- from django.conf import settings WYSIHTML5_EDITOR = { # Give the editor a name, the name will also be set as class # name on the iframe and on the iframe's body 'name': 'null', # Whether the editor should look like the textarea (by adopting styles) 'style': 'true', # Id...
4,856
1,556
from protocols import reports_3_0_0 as participant_old from protocols import participant_1_0_0 from protocols.migration import BaseMigration class MigrationParticipants100ToReports(BaseMigration): old_model = participant_1_0_0 new_model = participant_old def migrate_pedigree(self, old_instance): ...
6,496
2,238
from builtins import object from datetime import timedelta import factory from django.utils.timezone import now from bluebottle.pages.models import Page from .accounts import BlueBottleUserFactory class PageFactory(factory.DjangoModelFactory): class Meta(object): model = Page language = 'en' ti...
584
176
# Copyright The IETF Trust 2020, All Rights Reserved # -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-01-17 12:32 from django.db import migrations def create_or_delete_ipr_doc_events(apps, delete=False): """Create or delete DocEvents for IprEvents Mostly duplicates IprEvent.create_doc_even...
2,403
745
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 23:52:04 2020 @author: Madhur Gupta """ from __future__ import print_function import cv2 import argparse ap=argparse.ArgumentParser() ap.add_argument('-i','--image',required=True,help='path to image') args=vars(ap.parse_args()) image=cv2.imread(args['...
788
376
# -*- coding: utf-8 -*- """ ACLReader test cases """ import unittest from kazoo.security import ACL, Id from zk_shell.acl import ACLReader class ACLReaderTestCase(unittest.TestCase): """ test watcher """ def test_extract_acl(self): acl = ACLReader.extract_acl('world:anyone:cdrwa') expected...
665
258
"""Base validators.""" import re from dictator.errors import ValidationError from dictator.validators import Validator from typing import Type, Callable, Any, Tuple, Union HEX_REGEX = re.compile(r"^(0x)?([0-9A-Fa-f]+)$") BIN_REGEX = re.compile(r"^(0b)?([0-1]+)$") class ValidateType(Validator): """Type validator...
3,815
1,107
from .ReportParser import ReportParser class ReportParserMoieties(ReportParser): def __init__(self): ReportParser.__init__(self) def parseLines(self, lines): # type: ([str]) -> None current = self.skip_until(lines, 0, 'Link matrix(ann)') if current == -1: return ...
554
159
import torch.nn as nn import torch class EncoderRNN(nn.Module): def __init__(self, vocab_size, hidden_size, nlayers=2): super(EncoderRNN, self).__init__() self.nlayers = nlayers self.hidden_size = hidden_size self.embedding = nn.Embedding(vocab_size, hidden_size) self.gru ...
1,575
526
import torch import torch.nn as nn from torch.optim.lr_scheduler import CosineAnnealingLR, CosineAnnealingWarmRestarts import itertools import matplotlib.pyplot as plt initial_lr = 0.1 class model(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(in_channels=3, out_c...
1,087
486
from django.urls import path from .views import events_calendar, calendar_event_detail, past_competitions app_name = 'events_calendar' urlpatterns = [ path('past_competitions/', past_competitions, name='past_competitions'), path('<int:year>/<int:month>/<int:day>/<int:hour>/<slug:event>/', calendar_...
432
143
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pdb import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from trading_gym.utils.data.toy import create_toy_data from trading_gym.envs.portfolio_gym.portfolio_gym import PortfolioTradingGym order_book_id_number = 100 toy_data = cr...
1,236
462
"""session speaker Revision ID: 6f98e24760d Revises: 58588eba8cb8 Create Date: 2013-11-22 17:28:47.751025 """ # revision identifiers, used by Alembic. revision = '6f98e24760d' down_revision = '58588eba8cb8' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
619
251
#!/usr/bin/python """ this is the code to accompany the Lesson 3 (decision tree) mini-project use an DT to identify emails from the Enron corpus by their authors Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess impor...
1,124
324
''' mode: python; py-indent-offset: 4; tab-width: 4; coding: utf-8 Copyright (C) 2020 Airbus SAS ''' import unittest import time import numpy as np import pandas as pd from sos_trades_core.execution_engine.execution_engine import ExecutionEngine from climateeconomics.sos_processes.iam.witness.witness_dev.usecase_witnes...
49,588
18,365
import os import csv import h5py import numpy as np from neuron import h from .sim_module import SimulatorMod from bmtk.simulator.bionet.biocell import BioCell from bmtk.simulator.bionet.io_tools import io from bmtk.simulator.bionet.pointprocesscell import PointProcessCell pc = h.ParallelContext() MPI_RANK = int(pc....
11,383
3,929
class PresenterInfo(): """ | Class to fetch information about the current nanome session's presenter. """ def __init__(self): self._account_id = "" self._account_name = "" self._account_email = "" self._has_org = False self._org_id = 0 self._org_name = ""...
1,930
582
import time client_msg_type = 689 reserved_data_field = 0 def assemble_login_str(room_id): res = "type@=loginreq/roomid@=" + str(room_id) + "/" return res def assemble_join_group_str(room_id): res = "type@=joingroup/rid@=" + str(room_id) + "/gid@=-9999/"; return res def assemble_heartbeat_str(): ...
1,217
483
# ------------------------------------------------------------- # # 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 unde...
2,976
922
from .home import Steg __all__ = ['Steg',]
43
18
import ctypes from ctypes import wintypes, windll import win32api import win32con import win32gui # PUL = ctypes.POINTER(ctypes.c_ulong) PUL = ctypes.c_void_p class KeyBdMsg(ctypes.Structure): """ 键盘回调函数用结构体 """ _fields_ = [ ('vkCode', wintypes.DWORD), ('scanCode', wintypes.DWORD), ...
4,364
1,911
from django.shortcuts import render import numpy as np def index(request): return render(request, 'simple/index.html') def room(request, room_name): safe = np.random.normal(size=20, loc=0, scale=1) return render(request, 'simple/room.html', { 'room_name': room_name, 'some_thing': { ...
496
166
from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser, models.Model): """User Model""" name = models.CharField(max_length=500, blank=True, null=True) tz = models.CharField(max_length=500, blank=True, null=True) USERNAME_FIELD = 'name...
752
248
from .validators import Validator, BaseRule __all__ = ('Validator', 'BaseRule',)
83
27