text
string
size
int64
token_count
int64
import tensorflow as tf from parameterized import parameterized from opennmt.data import text class TextTest(tf.test.TestCase): def _testTokensToChars(self, tokens, expected_chars): expected_chars = tf.nest.map_structure(tf.compat.as_bytes, expected_chars) chars = text.tokens_to_chars(tf.constan...
3,633
1,451
import unittest import requests_mock from werkzeug.test import EnvironBuilder from werkzeug.wrappers import Request from perimeterx import px_constants from perimeterx.px_config import PxConfig from perimeterx.px_context import PxContext from perimeterx.px_proxy import PxProxy class Test_PXProxy(unittest.TestCase):...
4,277
1,553
# This just shifts 1 to i th BIT def BIT(i: int) -> int: return int(1 << i) # This class is equvalent to a C++ enum class EventType: Null, \ WindowClose, WindowResize, WindowFocus, WindowMoved, \ AppTick, AppUpdate, Ap...
1,683
494
class Users: usernamep = 'your_user_email' passwordp = 'your_password' linkp = 'https://www.instagram.com/stories/cznburak/'
144
54
import collections import functools import json import logging import multiprocessing import os import time from collections import OrderedDict from queue import PriorityQueue, Empty from typing import List, Tuple, Any from itertools import cycle, islice import minerl.herobraine.env_spec from minerl.herobraine.hero imp...
19,831
5,506
# Copyright 2021 MosaicML. All Rights Reserved. """The CPU device used for training.""" from __future__ import annotations import logging from contextlib import contextmanager from typing import Any, Dict, Generator, TypeVar, Union import torch from composer.core import Precision from composer.trainer.devices.devi...
1,461
462
import os import re import json import ast import csv import sys import shutil # ["allreduce-lambf16", "reducescatter-lamb-allgatherf16", "test-lambf16"] + \ # ["allreduce-adamf16", "reducescatter-adam-allgatherf16", "test-adamf16"] +\ all_binaries = ["adam-ar-c", "adam-rs-c-ag", "adam-fuse-rs-c-ag"] + \ ["lamb-...
4,208
1,605
import copy import torch.nn as nn import dgl from modules import MemoryModule, MemoryOperation, MsgLinkPredictor, TemporalTransformerConv, TimeEncode class TGN(nn.Module): def __init__(self, edge_feat_dim, memory_dim, temporal_dim, embedding_dim,...
3,409
1,003
""" Copyright (c) 2012-2013, Austin Noto-Moniz (metalnut4@netscape.net) Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND...
3,813
1,158
from typing import Type, TypeVar, MutableMapping, Any, Iterable from datapipelines import DataSource, DataSink, PipelineContext, Query, validate_query from cassiopeia_championgg.dto import ChampionGGStatsListDto, ChampionGGStatsDto from cassiopeia.datastores.uniquekeys import convert_region_to_platform from .common i...
2,255
688
import asyncio import json import os import random import re import urllib import urllib.request from glob import glob from os import getenv from random import choice import discord from discord.ext import commands from utils.cms import get_sponsor_intro, get_sponsor_audio from utils.commands import only_random, requ...
5,788
1,993
from django.test import TestCase from aluraflix.models import Programa from aluraflix.serializers import ProgramaSerializer class ProgramaSerializerTestCase(TestCase): def setUp(self): self.programa = Programa( titulo = 'Procurando ninguém em latim', data_lancamento = '2003-07-04',...
1,175
375
def add(m, n): """mとnを加算して返す""" return m - n
53
30
# -*- coding: utf-8 -*- """ gen ~~~~~~~~~~~~~~ Command gen. :copyright: (c) 2021 by weiminfeng. :date: 2021/9/1 """ import argparse import importlib.util import json import logging import os import re import shutil import sys from typing import List import inflection from flask import request fr...
16,720
4,892
# this example came from http://www.raspberrypi.org/phpBB3/viewtopic.php?f=32&t=29454&sid=4543fbd8f48478644e608d741309c12b&start=25 import smbus import time b = smbus.SMBus(1) d = [] addr = 0x27 b.write_quick(addr) time.sleep(0.05) d = b.read_i2c_block_data(addr, 0,4) status = (d[0] & 0xc0) >> 6 humidity = (((d[0] & 0x...
575
321
""" Tests for pika.frame """ try: import unittest2 as unittest except ImportError: import unittest from pika import exceptions from pika import frame from pika import spec class FrameTests(unittest.TestCase): BASIC_ACK = ('\x01\x00\x01\x00\x00\x00\r\x00<\x00P\x00\x00\x00\x00\x00\x00' '...
4,493
1,652
import logging from datetime import datetime, timedelta import requests from core.utils.customClasses import UserFilter from core.utils.default_responses import (api_accepted_202, api_bad_request_400, api_block_by_policy_451, ...
15,266
4,264
# vim:fileencoding=utf-8:noet # WARNING: using unicode_literals causes errors in argparse from __future__ import (division, absolute_import, print_function) import argparse import sys from itertools import chain from powerline.lib.overrides import parsedotval, parse_override_var from powerline.lib.dict import mergea...
7,102
2,460
import numpy as np import os import time import shutil import logging logger = logging.getLogger(__name__) class Experiment(object): """Create experiment directory structure, track, and store data. To be used as a base class or derived `Experiment` classes. """ def __init__(self, project_...
2,126
662
from django.db import migrations from decimal import Decimal from dateutil.relativedelta import relativedelta from datetime import date def fix_subscription(apps, schema_editor): Subscription = apps.get_model('confs', 'Subscription') SubscriptionType = apps.get_model('confs', 'SubscriptionType') # updat...
1,895
615
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 24 22:03:42 2018 @author: aditya """ import codecs import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import re import time import random training_errors= [2.880890389084816, 2.589109110832214, 2.529299919307232, 2.465622152...
1,771
1,376
from django.core.urlresolvers import reverse from django.test import TestCase from nc.tests import factories class ViewTests(TestCase): multi_db = True def test_home(self): response = self.client.get(reverse('nc:home')) self.assertEqual(200, response.status_code) def test_search(self): ...
2,926
892
import asyncio import json import time import sys import discord from discord.utils import get import create_action from db import database import beatsaver from cr_formulas import curves from general import full_clean beatsaver_interface = beatsaver.BeatSaverInterface() def read_f(path): f = open(path,'r') ...
24,706
6,671
import numpy as np import cv2 as cv import os from PIL import Image class preprocessing: def __init__(self, axial_path, coronal_path, sagittal_path): axial_path = axial_path[1:-1] coronal_path = coronal_path[1:-1] sagittal_path = sagittal_path[1:-1] axial_images = axial_path.split(',...
1,885
676
""" The system RoBERTa trains on the AGB dataset with softmax loss function. At every 1000 training steps, the model is evaluated on the AGB dev set. """ from torch.utils.data import DataLoader from sentence_transformers import models, losses from sentence_transformers import SentencesDataset, LoggingHandler, Sentence...
3,022
910
""" Base settings to build other settings files upon. """ import environ ROOT_DIR = environ.Path(__file__) - 3 # (palimpsest/config/settings/base.py - 3 = palimpsest/) APPS_DIR = ROOT_DIR.path('palimpsest') env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_...
9,730
3,130
import ipywidgets as widgets from traitlets import Unicode, Int, validate import os import json from datetime import datetime,timedelta from IPython.display import Javascript from IPython.display import HTML from cognipy.ontology import Ontology from IPython.display import clear_output _JS_initialized = False def _In...
5,992
1,855
INSTANCES = 405 ITERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100] N_ITERS = len(ITERS) # === RESULTS GATHERING ====================================================== # # results_m is a [INSTANCES][N_ITERS] matrix to store every test result results_m = [[0 for x in range(...
1,717
681
import subprocess import os from glim.core import Facade from glim import Log from glim import paths DEFAULT_CONFIG = { 'source': os.path.join(paths.APP_PATH, 'assets/js'), } class JSLint(object): def __init__(self, config): self.config = DEFAULT_CONFIG for key, value in config.items(): self.config[key] = ...
1,064
450
"""empty message Revision ID: 16d42da99601 Revises: deec8123583d Create Date: 2018-08-23 00:18:10.765086 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '16d42da99601' down_revision = '30b091260689' branch_labels = None depends_on = None def upgrade(): op...
777
322
import torchvision.transforms as transforms from eda.image.transforms.transform import EdaTransform class Normalize(EdaTransform): def __init__(self, mean, std, name=None, prob=1.0, level=0): self.mean = mean self.std = std self.transform_func = transforms.Normalize(mean, std) su...
457
143
import subprocess as subp def doc(): subp.run([ 'pdoc', '--html', '--overwrite', '--html-dir', 'docs', 'lcu_connectorpy' ])
150
58
from os import environ from unittest import TestCase from lemon_markets.account import Account client_id = environ.get('CLIENT_ID') client_token = environ.get('CLIENT_TOKEN') class _TestAccount(TestCase): def setUp(self): try: self.account = Account(client_id, client_token) except Ex...
894
274
N=input() num = [int(raw_input().split()[2]) for i in range(N)] num = list(set(num)) print num
95
40
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ 凯撒困在栅栏里了,需要你的帮助。 sfxjkxtfhwz9xsmijk6j6sthhj flag格式:NSFOCUS{xxx},以及之前的格式 """ def rail_fence(e): # e = 'tn c0afsiwal kes,hwit1r g,npt ttessfu}ua u hmqik e {m, n huiouosarwCniibecesnren.' elen = len(e) field = [] for i in range(2, ...
1,799
726
from django.contrib import admin from django.utils.html import format_html from django.contrib.auth.models import Permission from .models import * # Register your models here. admin.site.register(projectWorker) admin.site.register(project) admin.site.register(leadContact) class ClientAdmin(admin.ModelAdmin): lis...
470
135
import os import pandas as pd import numpy as np import torch from torchvision import transforms from torch.utils.data import Dataset import matplotlib.pyplot as plt from skimage import io import pdb class FrameDataset(Dataset): def __init__(self, csv_file, train_dir): self.labels = pd.read_csv(csv_file) ...
1,310
488
# Authors: James Bergstra # License: MIT import theano import theano.tensor as TT def pairwise_theano_tensor_prepare(dtype): X = TT.matrix(dtype=str(dtype)) dists = TT.sqrt( TT.sum( TT.sqr(X[:, None, :] - X), axis=2)) name = 'pairwise_theano_broadcast_' + dtype rval = t...
1,114
412
# -*- coding: utf-8 -*- # Copyright 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. ...
3,396
1,303
# -*- coding: utf-8 -*- # !/usr/bin/python # # example.py # # # Created by vinhntb on 6/27/17. # Copyright (c) 2017 geo_redis. All rights reserved. import sys from bunch import Bunch from constants import GEO_USER_VISITED from geo_redis.geo_redis import GeoRedis def add_user_visited(): user_1 = Bunch(longitu...
2,586
1,066
# Copyright 2017 F5 Networks 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 writi...
2,584
809
import torch import numpy as np from PIL import Image from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models # changing the already created codes in jupyter notebbooks to a functions def load_data(data_dir): train_transforms = transforms.C...
9,711
2,825
""" monotonic_cffi: Just a cffi version of existing monotonic module on PyPI. See: https://pypi.python.org/pypi/monotonic Tested with PyPy 2.6.1 and 4.0.0 on Windows, OSX and Ubuntu. Copyright 2015 Matt Jones <mattjones1811@hotmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may n...
4,232
1,331
# -*- coding: utf-8 -*- # Author: Jiajun Ren <jiajunren0522@gmail.com> # Weitang Li <liwt31@163.com> import pytest from renormalizer.mps import Mps, Mpo, MpDm, ThermalProp from renormalizer.mps.backend import np from renormalizer.tests.parameter import holstein_model from renormalizer.utils import Quantity ...
1,141
462
# -*- coding: utf-8 -*- import sys import numpy as np import torch from torch.autograd import Variable from pytorch2keras.converter import pytorch_to_keras import torchvision import os.path as osp import os os.environ['KERAS_BACKEND'] = 'tensorflow' from keras import backend as K K.clear_session() K.set_image_dim_or...
4,661
1,766
from typing import List, Union import json class Product: def __init__(self, name: str, code: str, price: float): self.name = name self.code = code self.price = price # Breakdown coupon's description into quantifiable attributes # For example: BOGO on coffee can be translated as an objec...
1,997
615
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
649
153
# -*- coding: utf-8 -*- """ PlexAPI Examples As of Plex version 0.9.11 I noticed that you must be logged in to browse even the plex server locatewd at localhost. You can run this example suite with the following command: >> python examples.py -u <USERNAME> -p <PASSWORD> -s <SERVERNAME> """ import argparse, sys from co...
4,409
1,436
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017 - hongzhi.wang <hongzhi.wang@moji.com> ''' Author: hongzhi.wang Create Date: 2019-09-04 Modify Date: 2019-09-04 ''' import unittest from .bowling_game import BowlingGame class TestBowlingGame(unittest.TestCase): def setUp(self): self.g...
1,070
443
from palo_alto_firewall_analyzer.core import register_policy_validator, BadEntry @register_policy_validator("BadGroupProfile", "Rule uses an incorrect group profile") def find_bad_group_profile_setting(profilepackage): device_groups = profilepackage.device_groups devicegroup_exclusive_objects = profilepackage...
1,873
508
# Copyright (c) 2018 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 # # Unless required by app...
15,574
5,183
import os from io import BytesIO import shutil from adaguc.CGIRunner import CGIRunner from lxml import etree from lxml import objectify import re ADAGUC_PATH = os.environ['ADAGUC_PATH'] class AdagucTestTools: def getLogFile(self): ADAGUC_LOGFILE = os.environ['ADAGUC_LOGFILE'] try: f ...
4,955
1,505
import os import wave from array import array from struct import pack from sys import byteorder import pyaudio import soundfile from .emotion_recognition import EmotionRecognizer from .utils import get_best_estimators THRESHOLD = 500 CHUNK_SIZE = 1024 FORMAT = pyaudio.paInt16 RATE = 16000 SILENCE = 30 def is_silen...
4,905
1,606
import numpy as np import torch.utils.data as data import csv import cv2 from PIL import Image from utils import progress_bar class CamelDataset(data.Dataset): """ camelyon17 dataset class for pytorch dataloader """ def __init__(self, csv_path='train.csv', limit=0, transform=None, target_transform=N...
2,032
639
from ..utils import get_env_var from pathlib import Path BASE_DIR = Path(__file__).parent.parent TG_TOKEN = get_env_var('TG_TOKEN') YMONEY_TOKEN = get_env_var('YTOKEN') PROMO_CODE = get_env_var('PROMO_CODE')
211
94
import gspread from oauth2client.service_account import ServiceAccountCredentials import pprint import logging import random # https://medium.com/daily-python/python-script-to-edit-google-sheets-daily-python-7-aadce27846c0 # tutorial is older, so the googple API setup is a little outdated # call directly to test # py...
5,365
1,810
import sys import re from typing import Sized def parse_models(models_file): color = re.compile(r'hasColor\(\d,\w+\)') shape = re.compile(r'hasShape\(\d,\w+\)') size = re.compile(r'hasSize\(\d,\w+\)') texture = re.compile(r'hasTexture\(\d,\w+\)') out_color = re.compile(r'outHasColor\(\d,\w+\)') ...
3,426
1,064
# coding=utf-8 import os import json # 获取最新模型预测数据文件夹 def get_latest_model_predict_data_dir(new_epochs_ckpt_dir=None): # 获取文件下最新文件路径 def new_report(test_report): lists = os.listdir(test_report) # 列出目录的下所有文件和文件夹保存到lists lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn)) # 按时间排序...
17,193
6,875
# # PySNMP MIB module SW-VLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-VLAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:12:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
18,656
7,585
from hera import ( InputArtifact, InputFrom, OutputArtifact, Task, Workflow, WorkflowService, ) def writer(): import json with open('/file', 'w+') as f: for i in range(10): f.write(f'{json.dumps(i)}\n') def fanout(): import json import sys indices = ...
1,007
370
"""parquet - read parquet files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .thrift_structures import parquet_thrift from .core import read_thrift from .writer import write from . import core, schema, conv...
424
123
#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id: InstructionTestGen.py $ """ Instruction Test Generator. """ from __future__ import print_function; __copyright__ = \ """ Copyright (C) 2012-2017 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox....
96,838
35,112
# -*- coding: utf-8 -*- """.. moduleauthor:: Artur Lissin""" import abc from copy import copy from dataclasses import dataclass from multiprocessing.managers import SharedMemoryManager from multiprocessing.shared_memory import SharedMemory from typing import Tuple, List, Optional, final, TypeVar, Generic from torch.ut...
6,169
1,995
"""Test IO capturing functionality""" import io import zmq from jupyter_client.session import Session from yap_kernel.iostream import IOPubThread, OutStream import nose.tools as nt def test_io_api(): """Test that wrapped stdout has the same API as a normal TextIO object""" session = Session() ctx = zmq...
1,090
352
"""Temporary Files Manager.""" import logging from configparser import ConfigParser from typing import Dict from OSIx.core.base_module import BaseModule from OSIx.core.temp_file import TempFileHandler logger = logging.getLogger() class TempFileManager(BaseModule): """Temporary File Manager.""" def run(se...
551
162
import math def vector_add(v, w): """adds corresponding elements""" return [v_i + w_i for v_i, w_i in zip(v, w)] def vector_subtract(v, w): """subtracts corresponding elements""" return [v_i - w_i for v_i, w_i in zip(v, w)] def vector_sum(vectors): return reduce(vector_add, vector...
1,124
456
#!/bin/python3 import exploit import ui_setup from time import sleep checkrain = exploit.Checkrain() checkrain.REMOTE_SSH_CC = 'kali@fancyrat.moo.com' window = ui_setup.UI.window keep_printing=True while True: if window['-OUTPUT-'].DisplayText.count('\n') >= 14: window['-OUTPUT-'].DisplayText = wind...
2,800
849
# Copyright (c) 2021 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import mock from sysinv.helm.base import BaseHelm from sysinv.helm.helm import HelmOperator from sysinv.tests import base as test_base class TestHelmBase(test_base.TestCase): def test_num_replicas_for_platform_app_0_control...
1,237
437
from decimal import Decimal from signal_ocean._internals import as_decimal def test_handles_None(): assert as_decimal(None) is None def test_handles_empty_strings(): assert as_decimal("") is None def test_parses_strings(): assert as_decimal("12.345") == Decimal("12.345") def test_handles_0(): a...
612
262
from flask import Flask, render_template, request, redirect, session, flash import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') app = Flask(__name__) app.secret_key = 'irtndvieurnviur' @app.route('/') def index(): return render_template("index.html") #check all for empty and pass...
1,610
507
import socket import struct import sys banner = """ _ _ _ _ | | | | | | | | ___| |_ ___ _ __ _ __ __ _| | __ _| |__ ___ ___| |_ / _ \ __/ _ \ '__| '_ \ / _` | |/ _` | '_ \ / _ \/ __| __| | __/ || __/ | | | | | (...
2,344
1,361
import os.path import sys import types import typing import unittest from datetime import datetime, date from functools import wraps from io import BytesIO, StringIO from typing import List, Tuple, Callable, Any, Optional, Union, Dict, Set, FrozenSet, NewType, TypeVar, Sequence, \ AbstractSet, Iterator, NamedTuple,...
63,998
21,184
# utility functions for manipulating MJCF XML models import xml.etree.ElementTree as ET import os import numpy as np from collections.abc import Iterable from PIL import Image from pathlib import Path import robosuite RED = [1, 0, 0, 1] GREEN = [0, 1, 0, 1] BLUE = [0, 0, 1, 1] TEXTURES = { "WoodRed": "red-wood....
12,391
3,837
'''initialize''' from .ski import SkiGame from .maze import MazeGame from .gobang import GobangGame from .tetris import TetrisGame from .pacman import PacmanGame from .gemgem import GemGemGame from .tankwar import TankWarGame from .sokoban import SokobanGame from .pingpong import PingpongGame from .trexrush import TRex...
1,106
358
# Generated by Django 2.1.7 on 2019-07-06 04:48 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('jobs', '0004_auto_20190706_0012'), ] operations = [ migrations.AddField( model_name='job', ...
486
168
import app import flask import flask_debugtoolbar app = flask.Flask(__name__) app.config.from_object('app.config') db = flask.ext.sqlalchemy.SQLAlchemy(app) mail = flask.ext.mail.Mail(app) app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True app.config['DEBUG_TB_PROFILER_ENABLED'] = True toolbar = flask_debugtoolb...
715
266
import os from app import create_app from dotenv import load_dotenv # .env dotenv_path = os.path.join(os.path.dirname(__file__), ".env") if os.path.exists(dotenv_path): load_dotenv(dotenv_path) app = create_app(os.environ.get("FLASK_CONFIG") or "default") if __name__ == "__main__": app.run()
304
116
class DFA: current_state = None current_letter = None valid = True def __init__( self, name, alphabet, states, delta_function, start_state, final_states ): self.name = name self.alphabet = alphabet self.states = states self.delta_function = delta_function ...
1,663
467
#!/bin/env python #using the wireframe module downloaded from http://www.petercollingridge.co.uk/ import mywireframe as wireframe import pygame from pygame import display from pygame.draw import * import time import numpy key_to_function = { pygame.K_LEFT: (lambda x: x.translateAll('x', -10)), pygame.K_RIGHT...
5,628
2,144
class LambdaError(Exception): def __init__(self, description): self.description = description class BadRequestError(LambdaError): pass class ForbiddenError(LambdaError): pass class InternalServerError(LambdaError): pass class NotFoundError(LambdaError): pass class ValidationError(L...
502
140
# -*- encoding=utf8 -*- from django.core.management.base import BaseCommand from datetime import timedelta, datetime from topbuzz.tasks import stat import argparse def valid_date(s): try: return datetime.strptime(s, "%Y-%m-%d") except ValueError: msg = "Not a valid date: '{0}'.".format(s) ...
810
251
# uncompyle6 version 3.6.4 # Python bytecode 2.7 # Decompiled from: Python 2.7.17 (default, Oct 23 2019, 08:25:46) # [GCC 4.2.1 Compatible Android (5220042 based on r346389c) Clang 8.0.7 (https:// # Embedded file name: <Angga> """ SILAHKAN RECODE SE ALAY MUNGKIN DAN TIRU GAYA TAMPILAN SAYA :) KASIH LOGO GEDE,...
5,276
3,814
from files import write_key, load_key, encrypt, decrypt import os from ipfs import add,pin,get_file def switch(option): return switcher.get(option, default)() # Encrypts file and adds to ipfs def encrypt_ipfs_add(): file=input("Enter the file name to be added - ") # Look for saved key, if not found then c...
2,712
870
import os import tensorflow as tf import numpy as np import mcubes from ops import * class ZGenerator: def __init__(self, sess, z_dim=128, ef_dim=32, gf_dim=128, dataset_name=None): self.sess = sess self.input_size = 64 self.z_dim = z_dim self.ef_dim = ef_dim self...
4,730
1,708
import pytest from faker import Faker from fastapi.encoders import jsonable_encoder from pydantic.types import SecretStr from sqlalchemy.orm import Session from app import crud, schemas from app.core import security def test_create_user(db: Session) -> None: faker = Faker() profile = faker.profile() emai...
2,410
775
from pathlib import Path from typing import Union import cv2 import pytest from layered_vision.cli import ( parse_value_expression, parse_set_value, get_merged_set_values, main ) EXAMPLE_IMAGE_URL = ( r'https://raw.githubusercontent.com/numpy/numpy' r'/v1.20.1/branding/logo/logomark/numpylo...
5,673
1,813
import os import re import base64 import keyring from cryptography.fernet import Fernet # Make sure the key, Fernet objects within scope of future dependencies # by setting to here (to nothing, for now) frn = Fernet(base64.b64encode(bytes(list(range(32))))) key = bytes(0) if os.path.isfile('./key'): # Check the 'key...
5,958
1,839
from base_classes import * class income_statement(financial_statement): ''' __init__ will create the necessary accounts for an income statement. -------------------------------------------------------------------------- No data must be added initially, use function add_data for this ''' def __init__(se...
38,462
10,138
import numpy as np from collections import Counter decay_rate = 0.97 n_rounds = 2000 bandit_count = 100 total_reward = None last_bandit = None last_reward = None his_hits = None his_record = None my_record = None my_hits = None wins = None losses = None bandits_record = None record_index = None x1 = None x2 = None ...
4,127
1,621
""" Lightweight testing class inspired by unittest from Pyunit https://docs.python.org/2/library/unittest.html Note that code is designed to be much simpler than unittest and does NOT replicate uinittest functionality """ class TestSuite: """ Create a suite of tests similar to unittest """ d...
1,156
334
#!/usr/bin/python3 # coding: utf-8 import sys import os, time, datetime import smtplib from email import (header) from email.mime import (text, multipart) with open(r'/home/jwc_notice.txt', "r+", encoding="utf-8") as file: #自行更改路径 a = file.read() send_title = "机器人风险提示" send_head = '<p style="color:#507383">亲爱的主人...
2,014
844
import os os.environ["PYRO_LOGFILE"] = "pyro.log" os.environ["PYRO_LOGLEVEL"] = "DEBUG" import Pyro4 import Pyro4.util import Pyro4.naming import sys import pprint """ Front end controller for the 2017/18 Networks and Distributed Systems Summative Assignment. Author: Z0954757 """ sys.excepthook = Pyro4.util.excepth...
6,328
1,674
import unittest from kleat.hexamer.search import plus_search, minus_search, search from kleat.hexamer.hexamer import extract_seq class TestSearchHexamer(unittest.TestCase): def test_plus_search(self): self.assertEqual(plus_search('GGGAATAAAG', 9), ('AATAAA', 16, 3)) self.assertEqual(plus_search('...
4,501
1,873
import nuke def delete_pt(): max_pts = int(nuke.thisNode().knob('Max PTS').value()) - 1 if max_pts < 2: nuke.message('Minimum 2 points') return pt_num = int(nuke.thisKnob().name()[6:]) node = nuke.thisNode() for pt in xrange(pt_num, max_pts): knob_name = 'pt' + str(pt) ...
3,825
1,470
import json from django.core.management.base import BaseCommand from 臺灣言語平臺.正規化團隊模型 import 正規化sheet表 from django.conf import settings class Command(BaseCommand): help = '加sheet的json' def add_arguments(self, parser): parser.add_argument( '服務帳戶json', type=str, hel...
907
426
""" Flask-GoogleLogin """ from base64 import (urlsafe_b64encode as b64encode, urlsafe_b64decode as b64decode) from urllib import urlencode from urlparse import parse_qsl from functools import wraps from flask import request, redirect, abort, current_app, url_for from flask_login import LoginManage...
6,851
2,009
import datajoint as dj import re import inspect from termcolor import colored class DJSearch: def __init__(self, db_prefixes=[''], context=None): db_prefixes = [db_prefixes] if isinstance(db_prefixes, str) else db_prefixes self.context = context or inspect.currentframe().f_back.f_locals s...
11,729
3,314
################################################################################ # # # Modules # # ...
1,838
333
# _ __ # | |/ /___ ___ _ __ ___ _ _ ® # | ' </ -_) -_) '_ \/ -_) '_| # |_|\_\___\___| .__/\___|_| # |_| # # Keeper Commander # Contact: ops@keepersecurity.com # import abc import datetime import json from typing import Optional, List, Tuple, Iterable, Type, Union, Dict, Any import itertools from .par...
16,002
4,685
import warnings import numpy as np import quaternionic import pytest def test_constants(): for const in ['one', 'x', 'y', 'z', 'i', 'j', 'k']: assert hasattr(quaternionic, const) c = getattr(quaternionic, const) with pytest.raises(ValueError): c *= 1.2 assert np.equal(quate...
773
310