text string | size int64 | token_count int64 |
|---|---|---|
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [os.environ['ALLOWED_HOSTS']]
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#... | 624 | 219 |
import tempfile
from pathlib import Path
import pytest
from norby.utils import get_readable_elapsed_time
from mmvae_hub.celeba.CelebaTrainer import CelebaTrainer
from mmvae_hub.evaluation.eval_metrics.coherence import test_generation
from mmvae_hub.mimic.MimicTrainer import MimicTrainer
from mmvae_hub.mnistsvhntext.m... | 7,159 | 2,142 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... | 41,339 | 15,448 |
# 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 2.3.3... | 17,804 | 4,889 |
"""
This package contains functions to computing a variety of image-based features
that quantify the appearance and/or morphology of an objects/regions in the
image. These are needed for classifying objects (e.g. nuclei) and
regions (e.g. tissues) found in histopathology images.
"""
# make functions available at the p... | 1,284 | 354 |
from Tkinter import *
import tkMessageBox
def callback():
print 'called the callback!'
def setStatus():
myBar.set("%s", 'STATUS BAR INFO')
def exitNow():
exit()
def confirmExit():
if tkMessageBox.askyesno('Exit dialog', 'Really exit?'):
exitNow()
root = Tk()
# create a menu
menu = Menu... | 1,532 | 551 |
'''
Analyze PHiP-seq read counts matrix to generate enrichment-over-beads-only scores.
Algorithm sketch:
[I] For each bead-only sample:
[1] Bin the read counts across clones into some number of bins (default 50).
[2] For each set of clones c associated with each bin:
For each other sample s:
... | 8,000 | 2,482 |
from passlib.context import CryptContext
#importing cryptcontext from passlib
pwd_context = CryptContext(
schemes=["pbkdf2_sha256"],
default="pbkdf2_sha256",
pbkdf2_sha256__default_rounds=30000
)
#A round is a part of the algorithm that runs many times in order to reduce "crackability".
def ... | 619 | 205 |
SERVICE = "00001523-1212-efde-1523-785feabcd124"
PWR_CHARACTERISTIC = "00001525-1212-EFDE-1523-785FEABCD124"
IDENTIFY_CHARACTERISTIC = "00008421-1212-EFDE-1523-785FEABCD124"
PWR_ON = b"\x01"
PWR_STANDBY = b"\x00"
NAME_SUFFIX = "LHB-" | 233 | 165 |
from cloudmesh.common.Shell import Shell
import subprocess
import asyncio
import sys
from subprocess import PIPE, Popen
import threading
from queue import Queue, Empty
import time
import os
import shlex
host = "r-003"
port = 9010
command = f'ssh juliet "ssh {host} ./ENV3/bin/jupyter-lab --ip localhost --port {port}"'
... | 2,264 | 742 |
from flask import *
app = Flask(__name__)
@app.route('/<X>')
def message(X):
return render_template('index.html', Y = X)
if __name__ == '__main__':
app.run()
| 171 | 67 |
import os
import config
def walk():
"""
遍历源文件目录
:return: Generator
"""
for root in config.Source.include:
for path, _, files in os.walk(root):
if path not in config.Source.exclude:
for file in files:
yield (path, file)
| 297 | 93 |
from string import ascii_lowercase
from itertools import product
# the letter z is not found in gogen puzzles
lowercase_letters = ascii_lowercase[:-1]
def get_connections(word_list):
"""Returns a dictionary of each letter in the alphabet, where the value is
a set of all the letters that are linked to it based on a... | 888 | 330 |
#! /usr/local/python-2.7.6/bin/python
#
# Copyright (C) 2015 by Howard Hughes Medical Institute.
#
# Purpose: given a segmentation stack,
# produce a directory of RGB files
import os, sys, re, h5py
import tifffile as tiff
import numpy
from skimage.morphology import label
from scipy.ndimage import measurements
from sk... | 2,728 | 998 |
#!/bin/bash
# Copyright (c) 2020, NVIDIA CORPORATION. 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,371 | 1,597 |
# -*- coding: utf-8 -*-
import unittest
from telebot.storage import EphemeralStorage
class TestEphemeralSession(unittest.TestCase):
def setUp(self):
from telebot.logger import init_root_logger
init_root_logger()
def test_session_storage_singleton(self):
session1 = EphemeralStorage()... | 811 | 295 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import logging
class Logger(object):
def __init__(self,logger,**kw):
'''
creat a logger class,port from default loggin module
Description:
对于不传入**kw参数的调用,为旧式调用,用于一些旧式程序
对于传输**kw的掉用,则支持如下功能
... | 1,856 | 671 |
import numpy as np
class AccuracyChecker:
def __init__(self, n_labels):
self.confusion = np.zeros((n_labels, n_labels))
# batch_accuracies = np.zeros((n_batches, max_epoch))
def update(self, real, predicted):
if predicted.ndim == 2 and real.ndim == 2:
predicted = np.argmax... | 965 | 317 |
#!/usr/bin/env python
from config_manager.eucalyptus import Eucalyptus
from config_manager.eucalyptus.enterprise import Enterprise
from config_manager.eucalyptus.topology import Topology
from config_manager.eucalyptus.topology.cluster import Cluster
from config_manager.eucalyptus.topology.cluster.nodecontroller import ... | 1,287 | 459 |
#!/usr/bin/env python
from __future__ import print_function
from cosmosis.postprocessing.postprocess import postprocessor_for_sampler
from cosmosis.postprocessing.inputs import read_input
from cosmosis.postprocessing.plots import Tweaks
from cosmosis.runtime.utils import mkdir
import sys
import argparse
import os
par... | 6,581 | 2,032 |
#!/usr/bin/env python3
# -*- coding^ utf-8 -*-
def t():
r = 1
while 1:
ch = int(input())
if not ch: break
r *= ch
print(r)
return (r)
if __name__ == '__main__':
print(t())
| 224 | 93 |
#!/usr/bin/python
from scapy.all import *
import sys
import signal
import os
#Function to handle Crtl+C
def signal_handler(signal, frame):
print('\n=================')
print('Execution aborted')
print('=================')
os.system("kill -9 " + str(os.getpid()))
sys.exit(1)
def signal_exit(signal, frame):
prin... | 2,592 | 1,224 |
"""
PyAnime4Up
~~~~~~~~~
:Copyright: (c) 2021 By Amine Soukara <https://github.com/AmineSoukara>.
:License: MIT, See LICENSE For More Details.
:Description: A Selenium-less Python Anime4Up Library
"""
from setuptools import find_packages, setup
AUTHOR = "AmineSoukara"
EMAIL = "AmineSoukara@gmail.com"
URL = "https://g... | 1,715 | 586 |
import time
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapi_apollo_middleware.middleware import (
FastAPIApolloMiddleware,
startup_apollo_cycle_task,
)
@pytest.fixture(name="test_middleware")
def test_middleware():
def _test_middleware(**profiler_kwargs)... | 1,032 | 316 |
from typing import Optional
from .sql_common import SQLAlchemyConfig, SQLAlchemySource
class BigQueryConfig(SQLAlchemyConfig):
scheme = "bigquery"
project_id: Optional[str]
def get_sql_alchemy_url(self):
return f"{self.scheme}://{self.project_id}"
class BigQuerySource(SQLAlchemySource):
de... | 545 | 178 |
import pandas
'''
根據文本資料,建構 term document matrix 矩陣,
存放在指定的位置。
'''
information = pandas.read_csv("csv/information.csv")
import text
vocabulary = text.vocabulary()
vocabulary.build(content = information['abstract'], title=information['title_e'])
matrix = pandas.DataFrame(vocabulary.frequency, dtype='int')
matrix.i... | 655 | 265 |
""" File Handling
=============
Pyfai strictly differentiates between virtual paths in the target system
(:any:`TargetPath`) and physical paths in the installer system
(:any:`InstallerPath`). While the former are always rooted in the target
system's filesystem root, only the latter can be resolved ... | 5,039 | 1,504 |
import info
class subinfo(info.infoclass):
def setTargets(self):
for ver in ['2.4.28', '2.4.33', '2.4.36', '2.4.45']:
self.targets[ver] = ('ftp://ftp.openldap.org/pub/OpenLDAP/'
'openldap-release/openldap-' + ver + '.tgz')
self.targetInstSrc[ver] = ... | 1,595 | 693 |
"""
Description: Old fun module. Will be rewritten
Version: 0620/prototype
Author: useless_vevo
"""
# Standard library
import os
import hashlib
import requests
from io import BytesIO
# Discord
import discord
from discord.ext import commands
# Pillow/PIL
from PIL import Image
from PIL import ImageFont
from PIL import... | 4,610 | 1,420 |
"Test that the PARANOIA setting works --fpm"
import gnosis.xml.pickle as xml_pickle
from gnosis.xml.pickle.util import \
setParanoia, getParanoia, add_class_to_store
import funcs
funcs.set_parser()
ud_xml = """<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="UserDict" class="Us... | 2,271 | 869 |
import math
import triangle
import numpy
pointBoundary = [ (-1, -1),
(-1, 1.0),
( 0, 1.0),
( 0, -1),
( 1, 1),
( 1, -3)]
points = pointBoundary
segs = [(0, 1),(1, 2),(2, 3),(3, 0), (2, 4), (4, 5), (5, 3)]
# these are ph... | 1,079 | 423 |
import colormaps as cmaps
cmap = cmaps._inferno_data;
for i,r in enumerate(cmap):
if i % 2 == 0:
print "{%s}," % ",\t".join(str(int(round(v * 255))) for v in r);
| 183 | 84 |
import argparse
import json
import pprint
import Logger
from executors.EndLoopExecutor import EndLoopExecutor
from executors.ExecutorFactory import ExecutorFactory
from DictUtils import DictUtils
class Tester:
__LOGGER = Logger.getLogger('Tester')
def __init__(self, configFilePath):
Tester.... | 4,703 | 1,376 |
"""
Functions bundled in this module make various announcements about the current game state to the standard output
"""
import math
def introduce_battle(attacker, defender):
print()
print("********* BATTLE *********")
print("Two brave warriors came to fight today:")
print(str(attacker))
print(str... | 6,448 | 2,203 |
from . import structure, applications, error
__version__ = '1.0.0'
| 68 | 23 |
"""
This module provides tests for @as_json_p() decorator.
"""
import sys
import pytest
from werkzeug.exceptions import BadRequest
from flask import Response, json
from flask_json import json_response, _json_p_handler, as_json_p
@pytest.fixture
def theapp(app):
# Disable pretty print to have smaller result string... | 9,912 | 3,038 |
from functools import partial
from typing import List
import time
import torch
from apex.transformer import parallel_state
from apex.transformer.tensor_parallel import model_parallel_cuda_manual_seed
from apex.transformer.pipeline_parallel.utils import setup_microbatch_calculator
from apex.transformer.pipeli... | 7,504 | 2,522 |
import siproll
import sys
siproll.do_call("sip:"+ sys.argv[1] + "@voip.eventphone.de", 60)
| 92 | 43 |
# Load libraries
import pandas
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from sklearn import model_selection # 模型比较和选择包
from sklearn.naive_bayes import GaussianNB
class Bayes_Test():
# 读取样本 数据集
def load_dataset(self):
url = 'Iris.csv'
names = ['sepal-lengt... | 8,143 | 4,021 |
data = {
"recent_sales": [
{
"id": 1,
"item": 'shirt',
"size": 'large',
"color": 'blue',
"price": '13.99'
},
{
"id": 2,
"item": 'shirt',
"size": 'large',
"color": 'orange',
"price": '15.99'
},
{
"i... | 2,175 | 859 |
import pytest
from data_structure_implementation.binary_tree import BinaryTree, BinaryTreeNode
class TestBinaryTree:
@pytest.fixture
def gen_tree(self) -> BinaryTree[int]:
root = BinaryTreeNode(
25,
BinaryTreeNode(
15,
BinaryTreeNode(10, Binary... | 1,695 | 687 |
#coding:utf-8
import sys
import traceback
import time
import datetime
import pytz
import base64
import binascii
import hashlib
# 第三方库
from flask import Flask, request, redirect, jsonify, session, abort, render_template, Response
from decouple import config
# 自己的库
from mybase.mylog3 import log
from mybase.myencrypt2 im... | 16,851 | 6,047 |
from pprint import pprint as pp
from flask import Flask, render_template, request
from module.weather import query_api
app = Flask(__name__)
@app.route('/')
def index():
return render_template(
'weather.html',
data=[{'name': 'Toronto'}, {'name': 'Montreal'}, {'name': 'Calgary'},
{'n... | 935 | 307 |
# Generated by Django 3.2.6 on 2021-08-15 04:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('challengenews', '0004_articles_slug'),
]
operations = [
migrations.AlterField(
model_name='articles',
name='slug',
... | 426 | 146 |
# WARNING: Do not edit by hand, this file was generated by Crank:
#
# https://github.com/gocardless/crank
#
from . import base_service
from .. import resources
from ..paginator import Paginator
from .. import errors
class CustomerBankAccountsService(base_service.BaseService):
"""Service class that provides acce... | 5,094 | 1,271 |
from .builder import build_iou_calculator
from .iou2d_calculator import BboxOverlaps2D, bbox_overlaps
from .dis_calculator import Dis, bbox_dis
from .riou_calculator import RboxOverlaps2D
__all__ = ['build_iou_calculator', 'BboxOverlaps2D', 'bbox_overlaps', 'Dis', 'bbox_dis', 'RboxOverlaps2D']
| 295 | 111 |
# Copyright (c) 2022 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 appli... | 1,256 | 415 |
# -*- coding: utf-8 -*-
# Author: XuMing <xuming624@qq.com>
# Brief: This example demonstrates the use of fasttext for text classification
# Bi-gram : 0.9056 test accuracy after 5 epochs.
import os
import keras
import numpy as np
from keras.layers import Dense
from keras.layers import Embedding
from keras.layers impor... | 6,091 | 2,271 |
import requests
import json
import torch
import numpy as np
x_new = np.zeros((1,1,28,28))
# Convert the array to a serializable list in a JSON document
input_json = json.dumps({"data": x_new.tolist()})
# Set the content type
headers = { 'Content-Type':'application/json' }
predictions = requests.post("http://127.0.0.... | 529 | 185 |
import datetime
import os
import uuid
from urllib.parse import urlparse
import slack
from flask import (
Flask,
jsonify,
render_template,
request,
send_from_directory,
)
from flask.cli import load_dotenv
from pymongo import MongoClient
from pytz import timezone
app = Flask(__name__)
load_dotenv()
... | 3,943 | 1,544 |
import requests
import tempfile
from celery.task import task
from django.core import files
from celery.utils.log import get_task_logger
from .models import Bag
logger = get_task_logger(__name__)
@task(
name="save_goods_to_db"
)
def save_goods_to_db(items_list):
for item in items_list:
bag = Bag(
... | 961 | 289 |
# Generated by Django 2.1.5 on 2019-02-09 18:55
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("core", "0001_initial")]
operations = [
migrations.CreateModel(
name="FoodWeight",
fields=[
... | 1,408 | 375 |
from click.testing import CliRunner
from pytest import fixture, mark
from unittest.mock import Mock, AsyncMock, patch, create_autospec
pytestmark = [mark.cli,mark.unit]
@fixture
def runner():
runner = CliRunner()
yield runner | 236 | 74 |
''' Present an interactive function explorer with slider widgets.
Scrub the sliders to change the properties of the ``hrf`` curve, or
type into the title text box to update the title of the plot.
Use the ``bokeh serve`` command to run the example by executing:
bokeh serve sliders.py
at your command prompt. Then nav... | 2,835 | 1,062 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding=utf-8
"""
814. 二叉树剪枝
"""
from laozhang import TreeNode
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
def helper(root: TreeNode) -> TreeNode:
if root:
helper(root.left)
helper(root.right)... | 682 | 216 |
import os
import shutil
import sys
import erfa # noqa
import pytest
import astropy # noqa
if len(sys.argv) == 3 and sys.argv[1] == '--astropy-root':
ROOT = sys.argv[2]
else:
# Make sure we don't allow any arguments to be passed - some tests call
# sys.executable which becomes this script when producing... | 4,816 | 1,486 |
# Generated by Django 3.0.8 on 2020-07-27 15:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('encrypt_decrypt_app', '0018_ciphergame_solved'),
]
operations = [
migrations.AlterField(
model_name='ciphergame',
na... | 425 | 146 |
# Generated by Django 3.2 on 2021-04-26 10:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('analyzer', '0005_auto_20210425_2245'),
]
operations = [
migrations.RemoveField(
model_name='attachment',
name='added_by',
... | 333 | 125 |
import sqlite3
from DataManagements.BackendAPIStaticList import singleton
from DataManagements.BackendAPIStaticList import cate_map
@singleton
class UserCatesManager:
def __init__(self):
pass
def dbconnect(self):
"""
connect to the database
:return: None
"""
sel... | 5,109 | 1,400 |
import random
import re
# Third-party modules:
# Local modules:
# Function WAI:
def roll_3d6():
"""Rolls 3d6"""
total = 0
for i in range(3):
roll = random.randint(1, 6)
# print(f"Rolling 1d6: {roll}")
total += roll
return total
# Function WAI:
def roll_4d6d():
"""Rolls 4d6... | 2,255 | 726 |
import asyncio
import random
from asyncio import Event
from typing import List, Any
import pytest
from swaplink import defaults
from tests.utils import setup_network_by_relative_loads
# for speeding up tests
defaults.HBEAT_SEND_FREQUENCY *= 0.3
defaults.HBEAT_CHECK_FREQUENCY *= 0.3
defaults.RPC_TIMEOUT *= 0.3
@pyt... | 3,088 | 1,103 |
n = int(input("Digite um número: "))
print("O anecessor do número é {} e o sucessor é {} ".format(n-1, n+1))
| 110 | 45 |
import pygame
import time
class Intro():
"""
A class that represent opening window of the game
and this window hold the play button, music button,
game sound button
"""
def __init__(self,screen):
self.screen = screen
def show_open_window(self):
# load the i... | 846 | 256 |
"""Handles input args for training deep-learning models."""
import numpy
from gewittergefahr.gg_utils import soundings
from gewittergefahr.deep_learning import cnn
from gewittergefahr.deep_learning import deep_learning_utils as dl_utils
TIME_FORMAT = '%Y-%m-%d-%H%M%S'
SOUNDING_HEIGHTS_M_AGL = soundings.DEFAULT_HEIGHT... | 13,741 | 5,249 |
"""Set up main entity."""
# pylint: disable=duplicate-code
import logging
from dataclasses import dataclass
from homeassistant.config_entries import ConfigEntry
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassis... | 1,859 | 592 |
"""Writer for generating a DiffX file from DOM objects."""
from __future__ import unicode_literals
import six
from pydiffx.writer import DiffXWriter
from pydiffx.sections import CONTENT_SECTIONS
class DiffXDOMWriter(object):
"""A writer for generating a DiffX file from DOM objects.
This will write a :py:c... | 4,238 | 1,142 |
import numpy as np
# Subway ridership for 5 stations on 10 different days
ridership = np.array([
[0, 0, 2, 5, 0],
[1478, 3877, 3674, 2328, 2539],
[1613, 4088, 3991, 6461, 2691],
[1560, 3392, 3826, 4787, 2613],
[1608, 4802, 3932, 4477, 2705],
[1576, 3933, 3909, 4979, 2685],
[95, 229, 255, 49... | 1,540 | 721 |
from typing import Any
from rx import Observable, pipe
from rx.operators import do_action, filter, map, ignore_elements
from redux import (
Epic,
Reducer,
ReduxFeatureModule,
combine_epics,
create_action,
create_feature_module,
handle_actions,
of_init_feature,
of_type,
select_ac... | 1,158 | 394 |
import random
def randomMAC():
return [ 0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
def MACprettyprint(mac):
return ':'.join(map(lambda x: "%02x" % x, mac))
def randomize():
return MACprettyprint(randomMAC()... | 323 | 138 |
from django.conf.urls import url
from . import views
app_name = 'lms_app'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^authentication$', views.auth, name='authentication'),
url(r'^registration$', views.registration, name='registration'),
url(r'^my_profile$', views.my_profile_request,... | 1,698 | 705 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""backend URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.schemas import get_schema_view
from rest_framework.documentation import include_docs_urls
from todoist import views
API_TITLE = 'Todoist API'... | 909 | 309 |
#!/bin/env python
import numpy
#import pylab
#import stats
from VMCHelp import *
import random
import numpy
from PIMC5 import *
numParticles=2
numTimeSlices=10
tau=0.1
lam=0.5
Path=PathClass(numParticles,numTimeSlices,tau,lam)
Path.SetCouplingConstant(1.0)
Path.SetPotential(HarmonicOscillator)
print PIMC(10000,Path,... | 342 | 141 |
import os
def FlagsForFile(filename, **kwargs):
return {
'flags': [
'-x', 'c11',
'-Wall', '-Wpointer-arith',
],
}
| 139 | 55 |
from zingkd.models.meta import Base
from sqlalchemy import Column, func
from sqlalchemy.types import Unicode, Integer, DateTime, Boolean, UnicodeText
from sqlalchemy.orm import relationship, backref
class Note(Base):
__tablename__ = 'notes'
__table_args__ = {'schema': 'zingk'}
note_id = Column(Integer,... | 731 | 230 |
import math
def secs_to_time(seconds):
if seconds < 60:
return "{seconds} secondi".format(
seconds = seconds
)
else:
if int(seconds / 60 / 60 / 24) > 0:
days = seconds / 60 / 60 / 24
return "{days} giorni, {hours} ore, {minutes} minuti, {seconds} secondi".... | 1,192 | 415 |
# Generated by Django 2.2.4 on 2019-08-19 20:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20190819_1441'),
]
operations = [
migrations.AlterField(
model_name='account',
n... | 425 | 160 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata('apscheduler') | 140 | 54 |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from .models import Job, Prediction
from .serializers import JobSerializer, PredictionSerializer
CREATE_JOB_URL = reverse('jobs... | 2,042 | 628 |
#program to convert an array to an array of machine values and return the bytes representation.
import array
import binascii
a = array.array('i', [1,2,3,4,5,6])
print("Original array:")
print('A1:', a)
bytes_array = a.tobytes()
print('Array of bytes:', binascii.hexlify(bytes_array)) | 283 | 95 |
from collections import defaultdict
import copy
from enum import Enum
import hashlib
import json
# From UD v2: https://universaldependencies.org/u/pos/
class Pos(Enum):
UNKNOWN = 0
# Open class
ADJ = 1
ADV = 2
INTJ = 3
NOUN = 4
PROPN = 5
VERB = 6
# Closed class
ADP = 7
AUX = 8
CCONJ = 9
DET =... | 22,949 | 7,890 |
import torch
import torch.nn as nn
from src.gumbel_social_transformer.gumbel_social_transformer import GumbelSocialTransformer
from src.gumbel_social_transformer.temporal_convolution_net import TemporalConvolutionNet
def offset_error_square_full_partial(x_pred, x_target, loss_mask_ped, loss_mask_pred_seq):
assert... | 7,239 | 2,575 |
# -*- coding: utf-8 -*-
# @Author: IBNBlank
# @Date: 2018-07-22 19:56:30
# @Last Modified by: IBNBlank
# @Last Modified time: 2018-07-28 22:19:12
import pygame
from os import path
##### Color Define #####
COLOR = {
"BLACK": (0,0,0),
"WHITE": (255,255,255),
"RED": (255,0,0),
"YELLOW": (255,255,0),
... | 7,598 | 3,250 |
import unittest
from mpf.core.segment_mappings import TextToSegmentMapper, BCD_SEGMENTS
class TestSegmentDisplay(unittest.TestCase):
def test_text_to_mapping(self):
mapping = TextToSegmentMapper.map_text_to_segments("1337.23", 10, BCD_SEGMENTS, embed_dots=True)
self.assertEqual(
[BCD... | 922 | 376 |
# Copyright 2019 Crowdin
#
# 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... | 1,845 | 693 |
import discord
import helper
from helper import *
client=discord.Client()
@client.event
async def on_ready():
print('logged in as')
print(client.user.name)
print(client.user.id)
print('-----')
@client.event
async def on_guild_join(guild):
name = "**<:Png:590089990780878848> Christian Westo... | 6,928 | 2,350 |
# 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
# distributed under t... | 4,095 | 1,164 |
# =============================================================================================
# QtVSCodeStyle.
#
# Copyright (c) 2015- Microsoft Corporation
# Copyright (c) 2021- Yunosuke Ohsugi
#
# Distributed under the terms of the MIT License.
# See https://github.com/microsoft/vscode/blob/main/LICENSE.txt
#
#... | 6,433 | 1,828 |
class MetaCommand:
def __init__(self, commands):
self.commands = commands
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
| 181 | 56 |
from shapely.geometry import Polygon
import cv2
image = cv2.imread("a.png")
window_name = 'Image'
# Center coordinates
center_coordinates = (120, 50)
# Radius of circle
radius = 20
# Blue color in BGR
color = (255, 0, 0)
# Line thickness of 2 px
thickness = 2
# Using cv2.circle() method
# Draw a circle with blue l... | 495 | 186 |
from polinomios.polinomios import p_de_A
import numpy as np
def test_p_de_A():
A = np.array([[-1, 4], [2, 1]])
p = [1, 0, -9]
assert np.allclose(p_de_A(p, A), np.zeros((2,2)))
def test_q_de_A():
A = np.array([[-1, 4], [2, 1]])
q = [2, 3]
assert np.allclose(p_de_A(q, A), np.array([[1, 8], [4, 5... | 326 | 171 |
#wirte a program to read number from keyboard and print it in reverse
number=input("Enter the number")
reverse=0
for i in range(len(number)):
reminder = int(number) % 10
reverse = (reverse * 10) + reminder
number = int(number) / 10
print(reverse)
#********************************using slice************... | 1,045 | 298 |
"""tests non-gui related Cart3d class/interface"""
from __future__ import print_function
import os
import unittest
from numpy import array_equal, allclose
import pyNastran
from pyNastran.converters.cart3d.cart3d import read_cart3d
from pyNastran.converters.cart3d.cart3d_to_nastran import cart3d_to_nastran_filename, ca... | 8,247 | 3,272 |
#! /usr/bin/python3
x = ("Hello")
y = "day 1 python"
z= "good going"
print(y)
print (z)
print(x)
print (x,y,z)
| 118 | 64 |
import ndspy
import ndspy.rom
import code
import io
import os
import os.path
from os import path
import json
import copy
def set_global_vars():
global ROM_NAME, NARC_FORMAT, POKEDEX, METHODS, ITEMS, MOVES
with open(f'session_settings.json', "r") as outfile:
settings = json.load(outfile)
ROM_NAME = setting... | 2,260 | 1,027 |
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
N = len(graph) - 1
mappings = {}
for i, nodes in enumerate(graph):
mappings[i] = nodes
result = []
queue = deque([[0]])
while queue:
path = queu... | 609 | 168 |
from tool.runners.python import SubmissionPy
class DivSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
# Your code goes here
positions = [int(x) for x in s.split(",")]
min_pos, max_pos = min(position... | 661 | 222 |
import os
import pytest
import sys
import traceback
enable_gpu = bool(os.environ.get("CORENRN_ENABLE_GPU", ""))
from neuron import h, gui
pc = h.ParallelContext()
def model():
pc.gid_clear()
for s in h.allsec():
h.delete_section(sec=s)
s = h.Section()
s.L = 10
s.diam = 10
s.insert("... | 1,698 | 719 |
#!/user/bin/python
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app import app as application
| 138 | 47 |
from django.db import models
class UserProfile(models.Model):
title = models.CharField(max_length=25, default='NULL USER')
img = models.ImageField(upload_to="images/", default='null.jpg')
def __str__(self):
return self.title | 247 | 76 |
import subprocess
import glob
import os
# Convert the tutorials
for fn in glob.glob("../examples/*.ipynb"):
name = os.path.splitext(os.path.split(fn)[1])[0]
outfn = os.path.join("tutorials", name + ".rst")
print("Building {0}...".format(name))
subprocess.check_call(
"jupyter nbconvert --templat... | 431 | 149 |