text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python3
import pandas as pd
import json
df = pd.read_excel("OPIMD Calc_checked_03Feb21AL.xlsx", sheet_name=None)
obj = {}
dz = df["OPIMD15ACCESSDATAZONERANK"]
dz = dz.dropna(subset=["datazone"])
dz.datazone = dz.datazone.astype(int)
dz.index = dz.datazone
obj["dz"] = dz.OPIMDAccPopRank_AL.to_dict()
... | 1,185 | 501 |
import requests
import urllib
def ForvoRequest(QUERY, LANG, apikey, ACT='word-pronunciations', FORMAT='mp3', free= True):
# action, default is 'word-pronunciations', query, language, apikey, TRUE if free api(default), FALSE if commercial
# Return a list of link to mp3 pronunciations for the word QUERY in L... | 1,806 | 525 |
def fib(x):
if not isinstance(x, int):
print "argument must be an integer"
return
if x == 0:
return 0
a, b = 0, 1
for i in range(x-1):
a, b = b, a + b
return b
def fib_rec(x):
if not isinstance(x, int):
raise ValueError("argument must be an integer") # an... | 422 | 154 |
import re
__all__ = ['register_table_name', 'sql_query']
batch_table_name_map = dict()
stream_table_name_map = dict()
def register_table_name(op, name: str, op_type: str):
if op_type == "batch":
batch_table_name_map[name] = op
elif op_type == "stream":
stream_table_name_map[name] = op
el... | 1,336 | 462 |
"""
Functions for working with the codepage on Windows systems
"""
import logging
from contextlib import contextmanager
from salt.exceptions import CodePageError
log = logging.getLogger(__name__)
try:
import pywintypes
import win32console
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# A... | 3,790 | 1,107 |
from flask import Flask, render_template
from application.settings import STATIC
from application.storage import storage
app = Flask(__name__, static_url_path=STATIC)
@app.route('/')
def hello_world():
storage_dataset = storage.load_data()
labels = []
datasets = {}
for label, dataset in storage_dat... | 827 | 234 |
"""Fun section of CLI command."""
import json
import logging
import time
from pprint import pformat, pprint
import click
from fabric.colors import red
@click.group()
def cli():
"""My fun program!"""
pass
@cli.command()
def progress():
"""Sample progress bar."""
i = range(0, 200)
logging.debug('... | 1,857 | 642 |
import unittest
import unittest.mock as mock
import pytest
from smqtk.algorithms.descriptor_generator import DescriptorGenerator
from smqtk.algorithms.descriptor_generator.colordescriptor.colordescriptor \
import ColorDescriptor_Image_csift # arbitrary leaf class
from smqtk.utils.configuration import configurati... | 1,851 | 545 |
# Generated by Django 2.1.7 on 2019-04-18 09:15
from django.db import migrations, models
import django.db.models.deletion
import django_fsm
class Migration(migrations.Migration):
dependencies = [
('conservation', '0019_auto_20190410_1329'),
]
operations = [
migrations.RenameModel(
... | 557 | 199 |
# Generated by Django 3.1.5 on 2021-04-28 16:22
import ckeditor.fields
from django.db import migrations, models
import django_minio_backend.models
class Migration(migrations.Migration):
dependencies = [
('news', '0004_profile_info'),
]
operations = [
migrations.AddField(
mod... | 1,141 | 339 |
import socket
from threading import Thread, Timer
class Invokeable:
def __init__(self, signal, *args, **kwargs):
self._signal = signal
self._args = args
self._kwargs = kwargs
@property
def signal(self):
return self._signal
@property
def kwargs(self):
retur... | 1,433 | 463 |
from . import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(UserMixin, db.Model):
__tabl... | 5,206 | 1,994 |
# coding=utf-8
# Copyright 2021-present, the Recognai S.L. team.
#
# 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 ... | 2,139 | 697 |
import unittest
from solution.rotated_array_search import RotatedArraySearch
class TestCasesRotatedArraySearch(unittest.TestCase):
def input_list_is_none_return_minus_one(self: object) -> None:
# Arrange
rotated_array_search: RotatedArraySearch = RotatedArraySearch()
input_list: list = Non... | 5,838 | 1,879 |
###############################################################
# pytest -v --capture=no tests/test_keygroup.py
# pytest -v tests/test_keygroup.py
###############################################################
#import pytest
import os
from cloudmesh.common.variables import Variables
from cloudmesh.common.Benchmark i... | 3,637 | 1,103 |
import pytest
import pandas as pd
import numpy as np
from blinpy import models
data = pd.DataFrame(
{'x': np.array(
[0.0, 1.0, 1.0, 2.0, 1.8, 3.0, 4.0, 5.2, 6.5, 8.0, 10.0]),
'y': np.array([5.0, 5.0, 5.1, 5.3, 5.5, 5.7, 6.0, 6.3, 6.7, 7.1, 7.5])}
)
def test_linear_model():
# 1) ... | 2,344 | 1,053 |
import pprint
import time
import json
from gtmcore.dispatcher import Dispatcher, jobs
from lmsrvlabbook.tests.fixtures import fixture_working_dir
class TestLabBookServiceQueries(object):
def test_query_finished_task(self, fixture_working_dir):
"""Test listing labbooks"""
d = Dispatcher()
... | 3,226 | 871 |
import re
def verify(phn_no):
design = "[789]\d{9}$"
if re.match(design,phn_no):
return "yes"
else:
return "No"
n = int(input())
for i in range(n):
print(verify(input())) | 204 | 81 |
from MAPLEAF.Motion import ForceMomentSystem, Inertia, Vector
from MAPLEAF.Rocket import RocketComponent
__all__ = [ "SampleStatefulComponent" ]
class SampleStatefulComponent(RocketComponent):
def __init__(self, componentDictReader, rocket, stage):
self.rocket = rocket
self.stage = stage
s... | 1,632 | 494 |
from Utils.Array import input_array
ZERO, ONE, TWO = 0, 1, 2
# Time -> O(n)
# Space -> O(1) inplace
def sort_by_counting(A):
cnt_0 = cnt_1 = cnt_2 = 0
# Count the number of 0s, 1s and 2s in the array
for num in A:
if num == ZERO:
cnt_0 += 1
elif num == ONE:
cnt_... | 866 | 416 |
#!/usr/bin/python -t
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it... | 8,601 | 2,566 |
#!/usr/bin/env python3
import rospy
from miradar_node.msg import PPI, PPIData
from visualization_msgs.msg import MarkerArray, Marker
from geometry_msgs.msg import Point
import dynamic_reconfigure.client
class PPIVisualizer:
def __init__(self):
self.pub = rospy.Publisher("/miradar/markers", MarkerArray, qu... | 1,911 | 632 |
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import psycopg2
import json
import pandas as pd
import time
app = dash.Dash(__name__)
#app.css.config.serve_locally=False
#app.css.append_css(
# {'external_url': 'https://codepen.io/amyosh... | 3,561 | 1,150 |
import pymongo
from .config import DB_PASSWORD, DB_USER, CLUSTER_NAME, SUBDOMAIN, DB_NAME
from .exceptions import CharacterNotFound, PoemAuthorNotFound
class DatabaseService:
def __init__(self):
client = pymongo.MongoClient(
f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{CLUSTER_NAME}.{SUBDOMAIN}.m... | 1,291 | 396 |
# imports
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as pyplot
# pycsep imports
import csep
from csep.utils import stats, plots
# experiment imports
from experiment_utilities import (
load_zechar_catalog,
plot_consistency_test_comparison,
read_zechar_csv_t... | 4,525 | 1,509 |
import os
import re
import sys
import time
import puzzles
from csp import *
from search import *
from utils import *
class Kakuro(CSP):
def __init__(self, puzzle):
self.puzzle = puzzle
self.rows_size = len(puzzle)
self.cols_size = len(puzzle[0])
self.variables = self.get_variables(... | 10,284 | 2,999 |
C, N = map(int, input().split(' '))
print(C % N)
| 49 | 23 |
import csv
import os
import sys
import matplotlib.pyplot as plt
from metrics.index import metrics
from plot_package.helpers import ascendence_label, descendence_label, with_sign
if len(sys.argv) != 2:
print(f"{__file__} sample_name.csv")
sys.exit(1)
sample_name = sys.argv[1]
# set size
plt.figure(figsize=(... | 2,682 | 998 |
#!/user/bin/env python
# -*- coding:utf-8 -*-
# 作者:zm6
# 创建:2021-03-19
# 更新:2021-03-19
# 用意:打印N以内的质数
import time # 比较代码运行时间
def list_prime(n):
num = 0
for i in range(2, n + 1):
is_prime = 1 #预设质数为是
for j in range(2, i - 1):
if i % j == 0:
is_prime = 0 #设置质数为否
... | 662 | 333 |
import glob
import os
from pkg_resources import resource_filename
import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
FF_DIR = resource_filename('foyer', 'forcefields')
FORCEFIELDS = glob.glob(os.path.join(FF_DIR, '*.xml'))
def test_load_files()... | 2,246 | 896 |
from ns_portal.database.meta import (
Main_Db_Base
)
from sqlalchemy import (
Column,
Integer,
String
)
class TRoles(Main_Db_Base):
__tablename__ = 'TRoles'
TRol_PK_ID = Column(
Integer,
primary_key=True
)
TRol_Label = Column(
String(250),
nullable=Fals... | 407 | 145 |
""" Form validators for authorization """
import re
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, ValidationError, Email, EqualTo
from cloudcourseproject.src.model import User
def password_validator(password):
""" Va... | 2,869 | 734 |
import pathlib
from mara_pipelines.commands.sql import ExecuteSQL, Copy
from mara_pipelines.pipelines import Pipeline, Task
from mara_pipelines import config
pipeline = Pipeline(
id="load_marketing_data",
description="Jobs related with loading marketing leads data from the backend database",
max_number_of... | 1,418 | 410 |
from django.urls import path,include
from .views import menu, image, weixinFile
urlpatterns = [
path('menu/list', menu.get_menu),
path('menu/user', menu.UserMenu.as_view()),
path('image', image.ImageView.as_view()),
path('saveWX', weixinFile.saveWX),
path('getRecentWX', weixinFile.getRecentWX),
] | 320 | 117 |
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from navigation import Link
from .permissions import (
permission_key_delete, permission_key_receive, permission_key_view,
permission_keyserver_query
)
link_private_keys = Link(
icon='fa fa-key', permissions=... | 1,178 | 395 |
"""
Problem : RNA Splicing
URL : http://rosalind.info/problems/splc/
Author : David P. Perkins
"""
import fasta
def getCodingRegion(DNAString, introns):
#print("DNA String", DNAString, "introns", introns)
codingString = list()
workingString = DNAString
while workingString:
for curI... | 1,489 | 499 |
import os
def encode(s):
if isinstance(s, bytes):
return s.decode('utf-8', 'ignore')
else:
return str(s)
path_joiner = os.path.join
path_basename = os.path.basename | 191 | 70 |
"""Interrupt field tests."""
from copy import deepcopy
from unittest import TestCase
from ..testbench import RegisterFileTestbench
class TestInterruptFields(TestCase):
"""Interrupt field tests"""
def test_fields(self):
"""test interrupt fields"""
fields = []
types = {
typ:... | 6,448 | 2,055 |
import tornado.ioloop
import tornado.web
import tornado.options
from tornado.log import gen_log
'''
Alert Manager Documentation: https://prometheus.io/docs/alerting/configuration/
Sample alertmanager message:
{
"version": "4",
"groupKey": <string>, // key identifying the group of alerts (e.g. to deduplicate)... | 1,745 | 591 |
from rest_framework import serializers
from backend.models import TodoItem, Note
from django.contrib.auth import authenticate, get_user_model
class TodoItemSerializer(serializers.ModelSerializer):
class Meta:
model = TodoItem
fields = ('id', 'created', 'updated', 'due', 'title', 'description', 'pr... | 1,848 | 520 |
from rstem.led_matrix import FrameBuffer
from rstem.mcpi import minecraft, control
import time
control.show()
mc = minecraft.Minecraft.create()
SCALE = 25
fb = FrameBuffer()
count = 0
FLASH_COUNT = 3
flash_lit = True
while True:
pos = mc.player.getTilePos()
x = round(pos.x/SCALE + (fb.width-1)/2)
x_out_of_bound... | 695 | 322 |
import os
from os.path import join as osp
import numpy as np
from tqdm import tqdm
import wandb
import torch
import torch.nn as nn
import torch.optim as optim
from torch.cuda import amp
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch import autograd
from torch... | 10,833 | 3,928 |
from backend.common.consts.notification_type import NotificationType
from backend.common.models.notifications.verification import (
VerificationNotification,
)
def test_str():
notification = VerificationNotification("https://thebluealliance.com/", "password")
assert "{'verification_key': " in str(notifica... | 889 | 232 |
class Generator(object):
def __init__(self):
self.tables = []
self.alters = []
self.triggers = []
def write_to_file(self, output_file):
with open(output_file, 'w') as sql_file:
sql_file.write('{0}{1}'.format('\n'.join(table for table in self.tables), '\n'))
... | 4,043 | 1,302 |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... | 1,967 | 571 |
import os
import ConfigParser
mu0 = 1.25663706e-6
class SACConfig(object):
def __init__(self, cfg_file=os.path.dirname(__file__) + '/sac_config.cfg'):
self.cfg_file = cfg_file
self.cfg = ConfigParser.SafeConfigParser()
self.cfg.read(self.cfg_file)
def _get_value(self, section, optio... | 7,847 | 2,342 |
from django.contrib.gis.db import models
from django.db.models import Q
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
# Create your models here.
class Location (models.Model):
name = models.CharField(
max_length=100,
verbose_name='Name of... | 1,606 | 465 |
"""Module configures project's main logger."""
import logging
from loguru import logger
def disable_usp_logging() -> None:
"""Disable logging of ultimate-sitemap-parser (usp) library.
Usp package initializes default logging.Logger() each time it
imports something from its core submodules.
Therefor... | 842 | 252 |
from __future__ import annotations
import warnings
from typing import Any, List, Callable, Tuple, Union, Collection, FrozenSet, Optional, Iterable, Set
from .base import DependencyBase, dataclass
from .tag import Tag
ExtractorFunc = Callable[[Any], Optional[dict]]
class Scopes:
""" Generate dependencies that ... | 14,213 | 3,503 |
import logging
import requests
import requests_cache
from django.conf import settings
from django.http import HttpResponse, HttpRequest
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
from .api import usergroups
from .models import DataportenUser
# Cach... | 812 | 240 |
# -*-coding:utf-8-*-
import base64
import copy
from .func import xor, rotl, get_uint32_be, put_uint32_be, bytes_to_list, list_to_bytes, padding, un_padding
BOXES_TABLE = [
0xd6,
0x90,
0xe9,
0xfe,
0xcc,
0xe1,
0x3d,
0xb7,
0x16,
0xb6,
0x14,
0xc2,
0x28,
0xfb,
0x2c,
0x05,
0x2b,
0x67,
0x9a,
0x76,
0x2a,... | 7,326 | 4,963 |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了74.47% 的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了7.95% 的用户
解题思路:
只能向右或向下前进。
则当前格的路径数等于左侧格的路径数+上侧格的路径数
dp[i][j] = dp[i-1][j] + dp[i][j-1]
例子:
1 1 1 1 1 1
1 2 3 4 5 6
1 3 6 10 15 21
... | 617 | 358 |
import sys
import structlog
from osrest import Tcpml
import services_component
def build_os(dataset_path, model_path, logger):
logger.info(f"Loading OS dataset from \"{dataset_path}\".")
dataset = Tcpml.load_dataset(dataset_path)
logger.info(f"Building OS model.")
model = Tcpml.build_model(dataset)
... | 1,207 | 428 |
version https://git-lfs.github.com/spec/v1
oid sha256:b28da294230f24c172729139b1988b8008f6fb2c259b1c3425772b2c80cfb9dd
size 2688
| 129 | 93 |
#!/usr/bin/env python3
import sys
import xml.etree.ElementTree as ET
def parse_value(element):
if element.tag == "string":
return element.text
elif element.tag == "dict":
return parse_dict(element)
elif element.tag == "array":
return parse_array(element)
else:
exception = "Unknown tag `" + element.tag + "`... | 4,049 | 1,459 |
"""panamsquad URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | 1,768 | 591 |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='sphinx-git-lowdown',
version='0.0.1',
url='https://github.com/yamahigashi/sphinx-git-lowdown',
# download_url='http://pypi.python.org/pypi/sphinx-git-lowdown',
license='Apache',
author='yamahigashi',
author_email='yamahigas... | 1,015 | 340 |
from .device import Device
class ValueDevice(Device):
pass | 63 | 17 |
from rfim2d import param_dict
key_dict = {
'A': ['Sigma', 'a', 'b'],
'dMdh': ['hMax', 'eta', 'a', 'b', 'c'],
'joint': ['rScale', 'rc', 'sScale', 'etaScale', 'df',
'lambdaH', 'B', 'C', 'F'],
'Sigma': ['rScale', 'rc', 'sScale', 'df', 'B', 'C'],
'eta': ['rScale', 'rc', 'etaScale', 'lambd... | 1,756 | 690 |
print('hi all')
print('hii')
print('hello world')
print('hi')
print('hello')
| 80 | 32 |
#!/usr/bin/python
# Copyright (c) 2015 Aaron Soto
# Released under the MIT license
# Incorporates libraries from AdaFruit, also released under the MIT license
# TODO functions:
# display_progress(percentage,[title]) - display a progress bar (0-1,1-100) / check for float
# display_error(message,[ti... | 2,250 | 839 |
# Upper-lower splitter for the exercise list
import sys
import exercise_populator_config as conf
print('Enter the file name: ')
filename = sys.stdin.readline()
filename = filename[0:len(filename)-1]
f = open(filename, 'r')
upper = conf.CONST_MUSCLES['upper']
lower = conf.CONST_MUSCLES['lower']
uex = []
lex = []
fo... | 753 | 291 |
#!/usr/bin/env/python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import asyncio
import logging
import os
import pathlib
import shutil
from typing import Dict, List
from fbpmp.pcf impo... | 4,893 | 1,459 |
import matplotlib.font_manager as font_manager
import matplotlib.pyplot as plt
import pandas as pd
import os
# Read the data
path = os.path.join(os.getcwd(), "results")
df = pd.read_csv(os.path.join(path, "tracker_AND_cookies.csv"))
x = df["day"]
y1 = df["total_tracker"]
y2 = df["tracker_distinct"]
y3 = df["is_sessio... | 2,168 | 793 |
import asyncio
async def long_task(writer):
total = 100
for i in range(1, total+1):
writer.write(type='progress', value=i, total=total)
print(i)
await asyncio.sleep(0.05)
class Writer:
def write(self, **kwargs):
print(kwargs)
coroutine = long_task(Writer())
asyncio.ensu... | 379 | 142 |
# -*- coding: utf-8 -*-
Group_Key_To_Dimension = dict(
c_ip = 'ip',
uid = 'user',
page = 'page',
did = 'did',
# c_ipc = 'ipc',
)
Avail_Dimensions = tuple(Group_Key_To_Dimension.values())
# dimension : variable_name(获取点击量的变量名)
Click_Variable_Names = dict(
ip='ip__visit__dynamic_count__1h__slot'... | 2,636 | 1,118 |
from pyhdf.SD import SD, SDC
from pathlib import Path
import numpy as np
import a301
m5_file = a301.data_dir / Path('myd05_l2_10_7.hdf')
the_file = SD(str(m5_file), SDC.READ)
wv_nearir_data = the_file.select('Water_Vapor_Near_Infrared').get()
the_file.end
positive = wv_nearir_data > 0.
print(f'found {np.sum(positive.f... | 346 | 155 |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from course_grader.dao import current_datetime, display_datetime
from course_grader.dao.term import (
next_gradable_term, previous_gradable_term, submission_deadline_warning,
is_grading_period_open)
from persistent_message.m... | 2,649 | 877 |
"""File reading/writing helpers."""
__all__ = ["topnet2ts", "gdf_to_shapefile"]
import geopandas
import pandas as pd
from swn.logger import get_logger, logging
def topnet2ts(nc_path, varname, mult=None, log_level=logging.INFO):
"""Read TopNet data from a netCDF file into a pandas.DataFrame timeseries.
Use... | 4,541 | 1,477 |
#!/usr/bin/env python3
"""
data clean for books (clean_documents.py)
note - this is the same as in assignment 1 for the most part
"""
import re
from ast import literal_eval
from os.path import basename, splitext, exists
from typing import Optional, List
from utils import get_glob, file_path_relative
from variables im... | 5,752 | 1,690 |
from django.shortcuts import render
from rest_framework.generics import RetrieveAPIView,CreateAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST,HTTP_201_CREATED
from rest_framework.views import APIView... | 6,041 | 1,763 |
# Copyright (c) 2014 Evalf
#
# 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, distribute, s... | 9,378 | 3,547 |
"""
This script analyses optimal alphas for each class and draws them in a box and whisker plot
"""
import pandas as pd
import argparse
import seaborn as sns
import matplotlib.pyplot as plt
import itertools
def shorten_uri(class_uri, base="http://dbpedia.org/ontology/", pref="dbo:"):
return class_uri.replace(base... | 6,336 | 2,177 |
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
ans = []
def helper(path: List[int], target: int, start: int) -> None:
if target < 0:
return
if target == 0:
... | 1,009 | 349 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... | 12,197 | 3,391 |
#!/usr/bin/python3
import pytest
from hypothesis import settings
# derandomizing prevents flaky test outcomes
# we are testing hypothesis itself, not testing with hypothesis
settings.register_profile("derandomize", derandomize=True)
@pytest.fixture
def SMTestBase(devnetwork):
settings.load_profile("derandomize"... | 486 | 139 |
from logging import getLevelName
import numpy as np
import os
import tensorflow as tf
import pathlib
import pandas as pd
import re
import matplotlib.pyplot as plt
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers im... | 7,706 | 2,658 |
import datetime
from django.db import models
from django.utils import timezone
# from .backends import update_data
class Member(models.Model):
github_username = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = self.github_username
super(Member, self... | 1,377 | 434 |
from django.db import models
from django.utils import timezone
from gentry.utils import make_absolute_uri
class Project(models.Model):
slug = models.SlugField()
name = models.CharField(max_length=128)
date_added = models.DateTimeField(default=timezone.now, editable=False)
def __str__(self):
... | 546 | 174 |
import os
from datetime import datetime, timedelta
from behave import given, when, then
from hamcrest import (
assert_that, equal_to, has_item, is_, is_not, greater_than, less_than
)
from StringIO import StringIO
from pptx import packaging
from pptx import Presentation
from pptx.constants import MSO_AUTO_SHAPE_T... | 17,167 | 6,222 |
"""
[2016-08-18] Challenge #279 [Intermediate] Text Reflow
https://www.reddit.com/r/dailyprogrammer/comments/4ybbcz/20160818_challenge_279_intermediate_text_reflow/
#Description:
Text reflow means to break up lines of text so that they fit within a certain width. It is useful in e.g. mobile
browsers. When you zoom in... | 2,604 | 754 |
from time import time, sleep
from math import floor
import argparse
import csv
import datetime
# Constants
TIME_WORK = 25
TIME_REST = 5
TIME_REST_LONG = 30
ONE_MINUTE = 60
SESSIONS_WORK_MAX = 4
LOOP_LIMIT = 9999
# Console
parser = argparse.ArgumentParser(description='===== Pomodoro timer CLI =====')
parser.add_argume... | 3,177 | 1,023 |
#!/usr/bin/env python
import signal
import click
from .client import Client
from .utils import Utils
utils = Utils()
signal.signal(signal.SIGINT, utils.signal_handler)
class Config(object):
def __init__(self):
self.loglevel = None
pass_config = click.make_pass_decorator(Config, ensure=True)
@click.... | 2,454 | 798 |
from itertools import count
from string import ascii_lowercase
plain_text = 'july'
results_file = open('results.txt', 'w')
letters_to_numbers = dict(zip(ascii_lowercase, count(0)))
numbers_to_letters = dict(zip(count(0), ascii_lowercase))
plain_text_numbers = [letters_to_numbers[letter] for letter in plain_text]
for i... | 998 | 329 |
import os, pickle
import numpy as np
import tensorflow as tf
def read_pickle(file_name):
with (open(file_name, "rb")) as openfile:
while True:
try:
objects = pickle.load(openfile)
except EOFError:
break
return objects
class Generator(tf.keras.uti... | 2,663 | 835 |
from mlb.models.game_detail import GameDetail
import time
import board
import displayio
from adafruit_display_text import label
from adafruit_display_shapes.roundrect import RoundRect
import fonts.fonts as FONTS
from mlb.schedule.schedule_view_model import ScheduleViewModel
from time_utils import day_of_week, month_nam... | 5,096 | 1,829 |
# Strings are used in Python to record text information, such as names.
# Strings in Python are actually a sequence, which basically means Python keeps track
# of every element in the string as a sequence.
# For example, Python understands the string "hello' to be a sequence of letters in a specific order.
# This me... | 1,307 | 400 |
# This code finds the Fourier Tranform of a signal and the Nyquist frequency
import matplotlib.pyplot as plt
import numpy as np
import librosa
import librosa as lr
from scipy import signal
from scipy.fft import fft, ifft
import math
import matplotlib.pyplot as plt
if __name__ == "__main__":
# Read the audio ... | 1,138 | 454 |
#!/usr/bin/env python
import rospy
import actionlib
from control_msgs.msg import *
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
PI = 3.14159265359
class TiltMotorController:
def __init__(self):
self.leftMotor_publisher = rospy.Publisher('/left_motor_tilt/command', Float64, queue_size =... | 2,106 | 899 |
from ast import Lambda
from enum import IntEnum
from typing import Any
from Ast import Stmt
from Ast import Expr
from Token import Token, TokenType
from Utils import Assert
from Ast import AstType, ArrayExpr, BoolExpr, ExprStmt, FunctionCallExpr, FunctionStmt, GroupExpr, IdentifierExpr, IfStmt, IndexExpr, InfixExpr, ... | 14,888 | 4,726 |
# COLORS
black = "\033[30m"
red = "\033[31m"
green = "\033[32m"
yellow = "\033[33m"
blue = "\033[34m"
magenta = "\033[35m"
cyan = "\033[36m"
white = "\033[37m"
nc = "\n"
# COLOR TESTING
def test():
print(red + "test")
print(blue + "test2")
print(green + "test3" + "\n" + cyan + "test4" + white)
| 302 | 165 |
from django.urls import path
from . import views
app_name = 'database'
urlpatterns = [
path('update/', views.update),
path('update2/', views.update2),
path('update3/', views.update3),
path('upload-user/', views.create_user_dataset)
]
| 253 | 86 |
from datetime import datetime
def unlucky_days(year):
return sum(datetime(year, month, 13).weekday() == 4 for month in range(1,13)) | 135 | 47 |
from werkzeug.exceptions import HTTPException
class InternalServerError(HTTPException):
pass
class SchemaValidationError(HTTPException):
pass
class UserNotFoundError(HTTPException):
pass
class EmailAlreadyExistError(HTTPException):
pass
errors = {
"InternalServerError": {
"message": "Oops someth... | 714 | 206 |
from raincoat.radarFunctions import getVarTimeRange, getRadarVar
import pandas as pd
data = getRadarVar('../samplefiles/radar/181202_000000_P09_ZEN_compact.nc',
'2001.01.01. 00:00:00',
'Ze')
start = pd.to_datetime('2018-12-02 00:00:00', format='%Y-%m-%d %H:%M:%S')
stop = pd.to_datetime... | 421 | 210 |
""" Gecko REQRM/RMREQ handlers """
import logging
import struct
from .packet import GeckoPacketProtocolHandler
REQRM_VERB = b"REQRM"
RMREQ_VERB = b"RMREQ"
_LOGGER = logging.getLogger(__name__)
class GeckoRemindersProtocolHandler(GeckoPacketProtocolHandler):
@staticmethod
def request(seq, **kwargs):
... | 1,527 | 582 |
# Generated by Django 2.2.13 on 2021-02-09 12:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('apps', '0004_auto_20210209_1243'),
]
operations = [
migrations.RenameField(
model_name='appinstance',
old_name='lab_session... | 376 | 140 |
# encoding: utf-8
__version__ = "1.0.1"
try:
import pygame
from pygame import mixer
except ImportError:
raise ImportError("\n<pygame> library is missing on your system."
"\nTry: \n C:\\pip install pygame on a window command prompt.")
from time import time
class SoundObje... | 30,714 | 9,077 |
#!/usr/bin/env python
import os
import sys
import getopt
TESTNAME = "extmethods"
class extmethodcls(object):
def commit(self, *args, **kwargs):
return "COMMIT_CALLED"
def presave(self, *args, **kwargs):
return "PRESAVE_CALLED"
def postsave(self, *args, **kwargs):
return "POSTSAVE_CALLED"
def ... | 2,931 | 1,045 |
# https://rosalind.info/problems/tran/
file = "data/tran.txt"
def read_fasta(file: str):
"""
Args
file: path of fasta file
"""
with open(file) as f:
fa = f.read().splitlines()
prev = True
header = []
seq = []
for f in fa:
if ">" in f:
header.append(f[1:... | 790 | 290 |