text
string
size
int64
token_count
int64
from django.conf import settings settings.NOTIFY_EMAIL = 'root@localhost' settings.DEBUG = True def before_all(context): context.users = {} context.members = {}
172
54
import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator from h2o.utils.model_utils import reset_model_threshold def test_reset_threshold(): """ Test the model threshold can be reset. Performance metric should be recalc...
2,546
854
#!/usr/bin/python import argparse import csv import sys ''' This script takes a CSV file with a mandatory header and a sql tablename and converts the data in the csv file into an SQL INSERT statement. ''' def parse_arguments(): # initialize argumentparser and arguments parser = argparse.ArgumentParser(descri...
2,324
645
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/index') def index(): return render_template('index.html') @app.route('/contact') def contact(): return render_template('contact.html') @a...
1,043
336
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,913
518
from django.db import models from django_countries.fields import CountryField from django.db.models.deletion import CASCADE class Author(models.Model): name = models.CharField(max_length=60) nationality = CountryField() class Book(models.Model): name = models.CharField(max_length=60) description = m...
448
139
import os os.environ["CUDA_VISIBLE_DEVICES"] = "4" import json import argparse import numpy as np import tensorflow as tf import midi_encoder as me from train_generative import build_generative_model from train_classifier import preprocess_sentence GENERATED_DIR = './generated' def override_neurons(model, layer_idx...
4,805
1,596
from ..utils import pad_left, try_parse_int from datetime import timedelta from typing import Dict, List TIME_PARTS: List[str] = [ "D", "H", "M", "S" ] FIXED_INTERVALS: Dict[str, timedelta] = { "WEEK": timedelta(weeks=1), "DAY": timedelta(days=1), "HOUR": timedelta(hours=1) } def parse_interval(value: str...
1,616
578
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.ai.PiratesMagicWordManager from direct.showbase.ShowBaseGlobal import * from direct.distributed import DistributedObject from di...
80,245
19,795
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def deps(): excludes = native.existing_rules().keys() if "bazel_installer" not in excludes: http_file( name = "bazel_installer", downloaded_file_path = "bazel-installer.sh", sha256 = "bd7a3a583a18640f...
634
272
import os import sqlite3 class TaskDatabase: def __init__(self, db_filename): self.filename = db_filename self.connection = None def get_connection(self): """ Return a connection to the database, creating one if it doesn't exist """ if self.connection is None: self...
4,318
1,180
#!/usr/bin/python def test_vars(): """test variables in python""" int_var = 5 string_var = "hah" assert int_var == 5 assert string_var == 'hah' print("test vars is done") if __name__ == "__main__": test_vars()
243
92
""" Up to now we have held all data in memory. This is of course impossible with large datasets. In this file we explore the use of TFRecords (binary files quickly loading data from disk) and Queues to store asynchronously loading data. In this example we the TinyImageNet-200 dataset which has 100,000 64x64 images fo...
7,199
2,117
import serial import serial.tools.list_ports from PyQt5.QtCore import QObject import relialok.Logger class SerialPort(QObject): @relialok.Logger.function_log def __init__(self, port, parent = None): self.port = port self.resource_free = True self.connection_active = True self.po...
2,906
761
import os import datetime def exit(): os._exit(0) def GetTimeString(m = -1): if m==0: s1 = datetime.datetime.now().strftime("%Y%m%d%H%M%S") else: s1 = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") return s1 def MakeDir(directory): if not os.path.exists(directory): os....
339
133
""" __| |_____________________________________________________________________________________| |__ (__ _____________________________________________________________________________________ __) | | | | | | ...
4,301
1,431
import datetime from django.utils import timezone from django.test import TestCase from sport.models import Sport, Competition, Venue from compete.models import CompetitionRound from compete.motorsport.models import Race from datasource.models import DataSource from datasource.mylaps.scoreboard import ScoreboardHand...
1,763
577
#* #* Copyright (C) 2017-2019 Alibaba Group Holding Limited #* #* 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 ...
1,697
592
import pytest import sqlalchemy as sa class ThreeLevelDeepOneToOne(object): @pytest.fixture def Catalog(self, Base, Category): class Catalog(Base): __tablename__ = 'catalog' id = sa.Column('_id', sa.Integer, primary_key=True) category = sa.orm.relationship( ...
6,610
1,776
# 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, software # d...
6,041
1,675
'''Robot sim with a nicer display.''' from sim_framework import * from math import radians import tkinter BACKGROUND_COLOR = 'grey60' ENTITY_COLOR = 'RoyalBlue1' OBSTACLE_COLOR = 'black' ENTITY_TAG = 'entity' class TKWorld(World): '''A world that will display via tkinter instead of ascii.''' def __init__(self...
3,916
1,391
#!/usr/bin/env python # # test_doctests.py - test runner for COT doctests # # July 2016, Glenn F. Matthews # Copyright (c) 2016-2017 the COT project developers. # See the COPYRIGHT.txt file at the top-level directory of this distribution # and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt. # # This ...
1,224
397
import logging import subprocess import sys import stardog.cluster.utils as utils def run_program(cmd, tries): def pgm_func(): try: p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) o, e = p.communicate() logging.debug("STDOUT: %s", ...
1,045
328
""" Here all the blog's urls routes will be mapped """ from django.urls import path from django.conf.urls import include, url from . import views app_name = 'core' urlpatterns = [ # path('', views.home, name='home-page'), url(r'^api/', include('apps.core.api.urls', namespace='api')), ]
297
97
"""Utilities for functional tests.""" import datetime import json import re import pymongo import pytest import api RATE_LIMIT_BYPASS = "test_bypass" TESTING_DB_NAME = 'ctf_test' db = None def decode_response(res): """Parse a WebSuccess or WebError response.""" decoded_dict = json.loads(res.data.decode('u...
24,270
8,421
exec "123"
11
8
import MySQLdb from queue import Queue import socket import json from time import sleep import threading import os queue = Queue() # 全局判题列表 myjsonfile = open("./setting.json", 'r') judgerjson = json.loads(myjsonfile.read()) if os.environ.get("DB_USER"): judgerjson["db_ip"] = os.environ.get(...
1,308
536
class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if not self.language == language: return f"{self.name} does not know {language}"...
909
257
from env import MsnDiscrete, MaplessNaviEnv from robot_utils import * from robot_utils.log import msn_debug from robot_utils.scene import * from env import * from collections import Counter MAX_FORCE = 10. TARGET_VELOCITY = 5. MULTIPLY = 2.0 def keyboard_control(): global MAX_FORCE global TARGET_VELOCITY ...
1,557
602
import bb import oe.path import glob import hashlib import os.path import shutil import string import subprocess VARIABLES = ( 'IMAGE_ROOTFS', 'OSTREE_BRANCHNAME', 'OSTREE_COMMIT_SUBJECT', 'OSTREE_REPO', 'OSTREE_GPGDIR', 'OSTREE_GPGID', 'OSTREE_OS', 'OSTREE_REMOTE', 'OSTREE_BARE', ...
12,358
4,029
#returns the value to the variable # x = 900 print(x) #print will take the argument x as the value in the variable #
123
42
from glob import glob from flask import flash, Flask, Markup, render_template, redirect, request, send_from_directory from form import MapForm from process_new_map import create_map_from_form app = Flask(__name__) with open("secret.txt", "r") as secret_f: app.config["SECRET_KEY"] = secret_f.read() @app.route(...
1,453
490
# Copyright 2021 MONAI Consortium # 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, s...
4,121
1,105
#!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-1728-Cat-and-Mouse-II.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-05-10 ==================================...
11,698
3,731
import click from random import randrange from tictac import Tictac @click.group() def tictac(): pass @tictac.command(name="games", help="Returns all started games, order by when they were created") def view_games(): tictac_class = Tictac() click.echo(tictac_class.view_games()) @tictac.command(name="...
2,193
703
import numpy as np import pandas as pd import riotConstant import time import requests def wait( tik ): tik = int(tik) tik += 2 while( tik > 0 ): print("API Rate Limit exceeded, wait for " + str(tik) + " second(s)", end = ' \r') tik -= 1 time.sleep(1) print(" ...
4,230
1,252
from django.urls import path from . import views urlpatterns = [ path('checkout/', views.checkout), path('orders/', views.OrdersList.as_view()), ]
158
53
from z3c.saconfig.scopedsession import Session, named_scoped_session from z3c.saconfig.utility import ( GloballyScopedSession, SiteScopedSession, EngineFactory) __all__ = [ 'Session', 'named_scoped_session', 'GloballyScopedSession', 'SiteScopedSession', 'EngineFactory', ]
299
101
from triage.experiments import ExperimentBase class SingleThreadedExperiment(ExperimentBase): def process_query_tasks(self, query_tasks): self.feature_generator.process_table_tasks(query_tasks) def process_matrix_build_tasks(self, matrix_build_tasks): self.matrix_builder.build_all_matrices(ma...
557
173
import re import os class tag_obj: def __init__(self): self.pos = 0 self.name = "" self.class_name = "" self.content = '' self.children ='' self.pairpos = -1 self.pair="" self.tag_label = "" class spider: def __init__(self, txt): self....
11,374
3,337
# # Copyright (c) 2019 Erwin Schotman # # Licensed under MIT License (MIT) # # 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 right...
4,909
1,366
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import json import os import random import time import uuid import pyrax from pyrax.autoscale import AutoScaleClient from pyrax.autoscale import AutoScalePolicy from pyrax.autoscale import AutoScaleWebhook from pyrax.autoscale import Sca...
30,434
9,900
#!/usr/bin/env python """ 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 License, Version 2.0 (the "License")...
2,869
890
#!/usr/bin/env python # Copyright 2017 The Kubernetes Authors. # # 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 appli...
3,589
1,135
from typing import Iterable import pytest from click.testing import CliRunner, Result from mock import Mock, patch from mock.mock import create_autospec from tickit.cli import main from tickit.core.components.component import ComponentConfig from tickit.core.management.schedulers.master import MasterScheduler from ti...
2,631
877
from typing import Any from pydantic import BaseSettings from .utils import singleton_cache class Settings(BaseSettings): TESTING: bool = False SQLALCHEMY_DATABASE_URI: str = 'sqlite:///db.sqlite3' FIRST_SUPERUSER: str = 'admin' FIRST_SUPERUSER_PASSWORD: str = 'admin' FIRST_SUPERUSER_ROLE: str...
565
208
from typing import ChainMap import yaml from pathlib import Path from jinja2 import Template from weasyprint import HTML, CSS # from xhtml2pdf import pisa class Story(): def __init__(self, story_path, story_name, template_path, *args, **kwargs): self.template_path = template_path self.story_path =...
2,158
654
from homework.models.answer import Answer from homework.models.answer_access_log_entry import AnswerAccessLogEntry from homework.models.answer_cross_check import AnswerCrossCheck from homework.models.question import Question __all__ = [ 'Answer', 'AnswerAccessLogEntry', 'AnswerCrossCheck', 'Question', ...
322
92
def add(tree, x): if not tree: tree.extend([x, None, None]) print('DONE') return key = tree[0] if x == key: print('ALREADY') elif x < key: left = tree[1] if left == None: tree[1] = [x, None, None] print('DONE') else: ...
1,650
540
import json from typing import TextIO from functools import partial import click import numpy as np from scipy.stats import sem import pandas as pd from fewshot.bootstrap import bootstrap from fewshot.bootstrap import ci from fewshot.challenges.utils import get_gold_dataset from . import score_utils as su def statist...
5,502
1,877
batch_size, num_samples, sample_rate = 32, 32000, 16000.0 # A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1]. pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32) # A 1024-point STFT with frames of 64 ms and 75% overlap. stfts = tf.signal.stft(pcm, frame_length=1024, frame_ste...
1,196
516
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-08-12 18:49 from __future__ import unicode_literals from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('user', '0016_post_likes'), ] operations = [ migrations.Alter...
458
164
from pydub import AudioSegment, effects import glob import os from tqdm import tqdm import argparse class AudioNormalization: def __init__(self, wav_file): self.wav_file = wav_file def loudness_normalization(self, target_dBFS=-15): audio_file = AudioSegment.from_file(self.wav_file, format='wav...
1,834
595
# 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 License, Version 2.0 # (the "License"); you may not use ...
12,308
3,552
from PIL import Image, ImageEnhance import pytesseract import os #image = Image.open('f_test.jpg') #enhance = ImageEnhance.Contrast(image) #new_image = enhance.enhance(1.5) #new_image.save('f_test__c_2.jpg') for x in range(0,3): os.system('./textcleaner -g -s 2 -a 1 ./Images/test_crop_'+str(x)+'.jpg ./Images/test_cr...
533
224
#! /usr/bin/env python3 ## Copyright 2018 Eugenio Gianniti <eugenio.gianniti@polimi.it> ## Copyright 2016 Giorgio Pea <giorgio.pea@mail.polimi.it> ## ## 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 Li...
2,090
677
"""Top-level package for mynlp.""" __author__ = """Suneel Dondapati""" __email__ = 'dsuneel1@gmail.com' __version__ = '0.1.0'
127
56
import unittest from geometry.point import Point class TestPoint(unittest.TestCase): def get_points(self): return [ Point(0, 0), Point(1, 1), Point(0, 1), Point(-1, 1), Point(-1, 0), Point(-1, -1), Point(1, -1) ]...
788
285
import yaml import os, errno import json def load_config(path): config = None with open(path, 'r') as config_file: config = yaml.load(config_file) return config def createSensorConfigs(topicSensors): sensors = [] count = 0 for i in range(topicSensors['nb']): config = {} ...
2,183
691
import collections class Solution(object): def fourSum(self, nums, target): nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): for j in xrange(i+1, len(nums)): lookup[nums[i]+nums[j]].append([i,j]) for i in ...
879
277
from .backend import Backend from .circuitbyqiskit import CircuitByQiskit from .circuitbyprojectq import CircuitByProjectq from .circuitbycirq import CircuitByCirq from .circuitbyqulacs import CircuitByQulacs # from .circuitbytket import CircuitByTket from .circuitbytensor import CircuitByTensor from .circuitbyq...
573
210
""" User Get Key Value Input Dictionary Start """ dic = { "google": "google is provide job and internship.", "amezon": "amezon is e-commerce store and cloud computing provider.", "zoom": "zoom is provide video call system to connecting meeating.", "microsoft": "microsoft is owner of windows and office ...
766
232
from statistics import mean from collections import defaultdict from cloudpredictionframework.anomaly_detection.algorithms.base_algorithm import BaseAlgorithm class HybridAlgorithm(BaseAlgorithm): def __init__(self, filters: [BaseAlgorithm], min_confidence=0.8): super().__init__() self._filters...
2,811
812
__all__ = ['Defer'] from contextlib import contextmanager, ExitStack @contextmanager def Defer(): with ExitStack() as stack: yield stack.callback
159
45
# vim:ts=4 sw=4 expandtab softtabstop=4 from jsonmerge.exceptions import HeadInstanceError, \ BaseInstanceError, \ SchemaError import jsonschema import re class Strategy(object): """Base class for merge strategies. """ def merge(self, walk,...
9,798
2,600
""" Reconcile and posting versions at 10.0 TODO:WIP """ import arcpy, os, sys, string #Populate parent and child versions in the following manner('Parent':'Child', etc). DO NOT LIST DEFAULT vTree = {'SDE.Parent':'SDE.Child','SDE.QA':'SDE.Edit'} #Reconcile and post child versions with parent def RecPostNonDefault(wo...
3,100
1,025
#!/usr/bin/env python import numpy as np import os,sys from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt import argparse ap=argparse.ArgumentParser() ap.add_argument('-vis') # 1 plot cropped point cloud ap.add_argument('-refine') # 1 refine mesh ap.add_argument('-clean') # 1 remove tmp...
4,626
2,326
import numpy from torch.utils.data import DataLoader import os import pickle import random from ..datasets import Dataset def generate_data_loaders_from_distributed_dataset(distributed_dataset, batch_size): """ Generate data loaders from a distributed dataset. :param distributed_dataset: Distributed data...
2,850
901
# -*- coding: utf-8 -*- __version__ = '$Id: 024580a7ff506aa3cbda6d46122b84b1603a6c05 $' from pywikibot import family # Omegawiki, the Ultimate online dictionary class Family(family.Family): def __init__(self): family.Family.__init__(self) self.name = 'omegawiki' self.langs['omegawiki']...
794
291
import os import sys import shutil import glob import time import multiprocessing as mp if len(sys.argv)!=4: print("Usage: ") print("python extract_features_WORLD.py <path_to_wav_dir> <path_to_feat_dir> <sampling rate>") sys.exit(1) # top currently directory current_dir = os.getcwd() # input audio direct...
4,781
1,813
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex from cctbx import adptbx from mmtbx import bulk_solvent from cctbx.array_family import flex from cctbx import adptbx import mmtbx from libtbx import group_args import mmtbx.arrays import mmtbx.bulk_solvent.scaler from l...
19,261
7,575
from session.abstract_class import PysparkPro class DslAdaptor(object): pysparkpro = PysparkPro() select = 'SELECT' insert = 'INSERT' delete = 'DELETE' update = 'UPDATE' alert = 'ALERT' create_table = 'CREATETABLE' drop_table = 'DROPTABLE' create_index = 'CREATEINDEX' drop_inde...
4,704
1,581
import socket def connect(server, port): # open a connection to vulnserver s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s.connect ((server, port)) return s def read_until(s, delim=b':'): buf = b'' while not buf.endswith(delim): buf += s.recv(1) return buf def overflo...
821
288
""" Runs all tests in the intended order. Each test script (in the `tests` folder) contains a group of tests. These scripts must be run in separate processes as most of them start and stop the Java virtual machine, which can only be done once per process. This is why simply calling pyTest (with `python -m pytes...
3,384
983
#!/usr/bin/env python """html in standard nbconvert format """ from ipypublish.html.create_tpl import create_tpl from ipypublish.html.standard import content from ipypublish.html.standard import content_tagging from ipypublish.html.standard import document from ipypublish.html.standard import inout_prompt from ipypubl...
592
202
# from flask import render_template, request, make_response, jsonify # from src.app_pkg.routes.common import validate_helper # from src.app_pkg import app, db # from src.app_pkg.forms import MessageForm # # ################################################ # # Show All Messages / User Profile # # ###########...
1,320
392
# Copyright 2016 Dave Kludt # # 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, s...
18,681
6,841
""" fork THIS excellent downloader https://www.kaggle.com/maroberti/transformers-model-downloader-pytorch-tf2-0 """ from typing import Union from pathlib import Path import os import transformers from transformers import AutoConfig, AutoTokenizer, TFAutoModel def transformers_model_dowloader(pretrained_model_name: ...
2,150
733
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from utils import read_log, plot_hist, update_fontsize, autolabel, read_p100_log from plot_sth import Bar import os import plot_sth as Color import math OUTPUT_PATH = '/media/sf_Shared_Data/tmp/icdcs2019' INPUT_PATH = '/media/sf_S...
28,128
12,098
from logging import raiseExceptions from typing import List from fastapi import APIRouter,Depends,HTTPException, Response,status from sqlalchemy.orm.session import Session from .. database import get_db from .. import models,schemas ,oauth2 router=APIRouter( prefix='/posts', tags=['Post'] ) @router.get('/'...
2,188
766
import torch.nn as nn import cv2 import torch from copy import deepcopy import numpy as np from torch.autograd import Variable from torch.autograd import Function as F from numpy.polynomial import Polynomial as P try: from parameters import Parameters except: from src.parameters import Parameters import math...
8,766
3,436
import nose.tools import unittest import os import json import pandas as pd import numpy as np import mia from mia.io_tools import * from ..test_utils import get_file_path class IOTests(unittest.TestCase): @classmethod def setupClass(cls): cls._output_files = [] @classmethod def teardownCla...
3,322
1,124
# Generated by Django 2.2.4 on 2019-09-29 13:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0006_recipe_tags'), ] operations = [ migrations.RemoveField( model_name='profile', name='rated_recipes', ), ...
326
116
from .assembly import HRCAssembly from .element import HRCElement from .artist import AssemblyArtist from .utilities import *
126
35
from unittest.mock import patch import pytest from pytest import mark from integrations.mailchimp import SubscriptionResult from newsletters.models import Subscription def test_subscribe_to_newsletter(graphql_client): email = "me@example.it" variables = {"email": email} query = """ mutation($em...
3,674
1,070
#----------------------------------------------------- # Mimas: conference submission and review system # (c) Allan Kelly 2016-2020 http://www.allankelly.net # Licensed under MIT License, see LICENSE file # ----------------------------------------------------- # System imports # Google imports from google.appengine.e...
3,077
931
################################# ##### jExam Argument Parser ##### ################################# import argparse def get_parser(): """ Creates and returns the argument parser for jExam Returns: ``argparse.ArgumentParser``: the argument parser for jExam """ parser = argparse.Argum...
891
254
class Element: dependencies = [] def __init__(self, name): self.name = name def add_dependencies(self, *elements): for element in elements: if not self.dependencies.__contains__(element): self.dependencies.append(element) def remove_dependencies(self, *elem...
474
119
from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stack = models.IntegerField() image_url = models.CharField(2083)
236
74
import numpy as np import xpart as xp import xobjects as xo #context = xo.ContextPyopencl() context = xo.ContextCpu() ctx2np = context.nparray_from_context_array particles = xp.Particles(_context=context, p0c=26e9, delta=[1,2,3]) assert ctx2np(particles.delta[2]) == 3 assert np.isclose(ctx2np(particles.rvv[2]), 1.00...
758
327
from typing import Union import gym import numpy as np import pytest import torch as th import torch.nn as nn from stable_baselines3.common.preprocessing import get_flattened_obs_dim from stable_baselines3.common.torch_layers import BaseFeaturesExtractor from sb3_contrib import QRDQN, TQC, MaskablePPO from sb3_contri...
9,628
3,315
from requests import post from random import randrange from uuid import uuid4 import base64 import json PORT = 6789 MAX_SIZE_UDP = 65535 HEADER_SIZE = 12 NUM_TRANSACTIONS = 10 SERVER = 'http://localhost:1234/add' def main(): for i in range(NUM_TRANSACTIONS): # Psuedo-random transaction ID trans...
880
298
from experiments.common.definitions import remat_data_dir import numpy as np import pandas as pd import glob import re # compute aggregated tables of max and geomean lp approximation ratios exp_name_re = re.compile(r"^(?P<platform>.+?)_(?P<model_name>.+?)_(?P<batch_size>[0-9]+?)_(?P<input_shape>None|.+?)$") dfs = [] ...
2,414
959
# known contracts from protocol CONTRACTS = [ # NFT - Meteor Dust "terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7", # NFT - Eggs "terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg", # NFT - Dragons "terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6", # NFT - Loot "terra14gfnxnwl0yz6njzet4n33erq5n70w...
431
231
# Generated by Django 3.1.2 on 2020-10-03 12:39 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('github', '0006_repository_open_issues_count'), ] operations = [ migrations.RenameField( model_name=...
2,268
600
''' A unit test for databearDB.py Runs manually at this point... ''' import unittest from databear.databearDB import DataBearDB #Tests class testDataBearDB(unittest.TestCase): def setUp(self): ''' Hmm ''' pass
254
82
version = "0.21.0"
19
12
# # See https://github.com/dials/dials/wiki/pytest for documentation on how to # write and run pytest tests, and an overview of the available features. # from __future__ import absolute_import, division, print_function import os import pytest @pytest.fixture(scope="session") def dials_regression(): '''Return the ...
1,161
355
# Copyright The IETF Trust 2019-2020, All Rights Reserved # -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2019-11-15 20:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('review', '0019_auto_20191023_0829'), ] operations = [ m...
978
313
def isPalindrome(string, i = 0): j = len(string) - 1 -i return True if i > j else string[i] == string[j] and isPalindrome(string, i+1) def isPalindrome(string): return string == string[::-1] def isPalindromeUsingIndexes(string): lIx = 0 rIdx = len(string) -1 while lIx < rIdx: if(string...
442
168