text string | size int64 | token_count int64 |
|---|---|---|
import pytest
from herokuapp_internet.login_page import LoginPage
from herokuapp_internet.disappearing_elements_page import DisappearingElementsPage
import logging
logger = logging.getLogger(__name__)
def pytest_addoption(parser):
parser.addoption(
"--headless", action="store", default="false", help="Run... | 898 | 284 |
"""
doit docs: https://pydoit.org/cmd_run.html
"""
import pdoc
import os
import os.path
def generate_docs(docs_dir: str):
"""
python callable that creates docs like docs/textwalker.html, docs/patternparser.py
Args:
docs_dir: location to output docs to
"""
if not os.path.exists(docs_dir):
... | 2,286 | 783 |
'''
Module for basic averaging of system states across multiple trials.
Used in plotting.
@author: Joe Schaul <joe.schaul@gmail.com>
'''
class TrialState(object):
def __init__(self, trial_id, times, systemStates, uniqueStates, stateCounterForStateX):
self.trial_id = trial_id
self.times... | 2,329 | 719 |
import click
from lhotse.bin.modes import obtain, prepare
from lhotse.recipes import download_vctk, prepare_vctk
from lhotse.utils import Pathlike
__all__ = ['vctk']
@prepare.command()
@click.argument('corpus_dir', type=click.Path(exists=True, dir_okay=True))
@click.argument('output_dir', type=click.Path())
def vct... | 636 | 232 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
requirements = [
"xarray>=0.14",
"numpy>=1.11",
"scikit-learn>=0.22",
"fsspec>=0.6.2",
"pyyaml>=5.1.2",
"tensorflow>=2.2.0",
"tensorflow-addons>=0.11.2",
"typing_extension... | 1,627 | 595 |
# -*- coding: utf-8 -*-
"""Dupa
Set of tools handy during working, debuging and testing
the code."""
__version__ = '0.0.1'
__author__ = 'Kris Urbanski <kris@whereibend.space>'
import time
from functools import wraps
from dupa.fixturize import fixturize
def debug(func):
"""Print the function signature and retur... | 1,447 | 525 |
from django.contrib.sites.models import Site
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from htmlmin.decorators import not_minified_response
from dss import localsettings
from spa.forms import UserForm
__author__ = 'fergalm'
@not_minified_response
de... | 2,272 | 733 |
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from drf_yasg.utils import swagger_auto_schema
from service.serializers import PostSerializer, ImagePostSerializer
from .models import Author, Post
@swagger_auto_schema(method='get', operation_... | 1,207 | 327 |
# -*- coding:utf-8 -*-
import hashlib
import os
from datetime import datetime
from .error import *
from .utils import Utils
from .api import API
from .net import Net
class BasePixivAPI(Net, Utils):
def __init__(self, **requests_kwargs):
self.additional_headers = {}
self.client_id = 'MOBrBDS8blbauo... | 4,894 | 1,500 |
# %%
'''
Example implementations of HARK.ConsumptionSaving.ConsPortfolioModel
'''
from HARK.ConsumptionSaving.ConsPortfolioModel import PortfolioConsumerType, init_portfolio
from HARK.ConsumptionSaving.ConsIndShockModel import init_lifecycle
from HARK.utilities import plotFuncs
from copy import copy
from time import ti... | 10,057 | 3,471 |
import lobby
def test_book():
# Create a LOB object
lob = lobby.OrderBook()
########### Limit Orders #############
# Create some limit orders
someOrders = [{'type': 'limit',
'side': 'ask',
'qty': 5,
'price': 101,
'tid': 1... | 1,648 | 512 |
import os
import argparse
import numpy as np
import scipy
import imageio
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import graphkke.generate_graphs.graph_generation as graph_generation
import graphkke.generate_graphs.generate_SDE as generate_SDE
parser = argparse.ArgumentParser()
parser.add_... | 2,451 | 946 |
import sys
try:
import uos as os
except ImportError:
import os
if not hasattr(os, "unlink"):
print("SKIP")
sys.exit()
# cleanup in case testfile exists
try:
os.unlink("testfile")
except OSError:
pass
try:
f = open("testfile", "r+b")
print("Unexpectedly opened non-existing file")
excep... | 741 | 312 |
import json
import re
import datetime
import scrapy
import yaml
import munch
import pathlib
from appdirs import user_config_dir
config_path = list(pathlib.Path(__file__).parent.parent.parent.resolve().glob('config.yml'))[0]
class YtchSpider(scrapy.Spider):
name = "ytch"
start_urls = list(
munch.Munch... | 1,198 | 378 |
# -*- coding: utf-8 -*-
"""Pih2o pump / electro-valve management.
"""
import threading
from RPi import GPIO
from pih2o.utils import LOGGER
class Pump(object):
def __init__(self, pin):
self._running = threading.Event()
self.pin = pin
GPIO.setup(pin, GPIO.OUT)
GPIO.output(self.pi... | 1,031 | 346 |
"""
Responsible to return the abstract browser configs.
"""
from abc import ABC, abstractmethod
class BrowserConfigBase(ABC):
"""
Holds abstract methods to be implemented in Browser Config classes.
"""
@abstractmethod
def base_url(self):
"""
Return base_url.
"""
ra... | 1,193 | 328 |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_finance import candlestick_ohlc
# import matplotlib as mpl then mpl.use('TkAgg')
import pandas as pd
import numpy as np
from datetime import datetime
df = pd.read_csv('BitMEX-OHLCV-1d.csv')
df.columns = ['date', 'open', 'high', 'low', 'clo... | 939 | 394 |
# Copyright 2018 VMware, Inc.
# 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 a... | 6,006 | 1,884 |
#!/usr/bin/env python
# coding=utf-8
"""Complex Type Tests."""
import json
import mongoengine_goodjson as gj
import mongoengine as db
from ...fixtures.base import Dictable
from ....con_base import DBConBase
class FollowReferenceFieldLimitRecursionComlexTypeTest(DBConBase):
"""Follow reference field limit recu... | 1,829 | 540 |
# 现在单位成本价,现在数量
current_unit_cost = 78.1
current_amount = 1300
# 计算补仓后成本价
def calc_stock_new_cost(add_buy_amount,add_buy_unit_cost):
# 补仓买入成本
buy_stock_cost = add_buy_amount*add_buy_unit_cost
# 补仓后总投入股票成本 = 现数量 * 现成本单价 + 新数量 * 新成本单价
new_stock_cost = current_amount * current_unit_cost + buy_stock_cost
... | 995 | 693 |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module is for webkit-layout-tests-related operations."""
import re
from libs import test_name_util
from libs.test_results.base_test_results import B... | 16,112 | 4,944 |
import os
import zipfile
import hashlib
import logging
import json
from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import (AllowAny, IsAuthenticated, )
from .serializers import Test... | 3,477 | 1,503 |
from ff_client import FfClient, FfConfig, FfRequest
import unittest
import logging
class TestFfClientMutiPacket(unittest.TestCase):
def test_create_request_packets(self):
client = FfClient(FfConfig(ip_address='127.0.0.1',
port=8080,
log... | 4,309 | 1,502 |
# Copyright 2020 Google LLC
#
# 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, ... | 22,429 | 6,462 |
#!/usr/bin/env python
from __future__ import division, print_function
import numpy as np
import rospy
from rospkg.rospack import RosPack
from copy import deepcopy
from tf2_ros import TransformListener, Buffer
from bopt_grasp_quality.srv import bopt, boptResponse
from bayesian_optimization import Random_Explorer
from b... | 3,356 | 1,319 |
from typing import List, Optional
from utils.embedder import build_embed
from utils.utils import one
from database.channel_message import ChannelMessage
import discord
class ChannelMessageManager:
def __init__(self, host_channel: discord.TextChannel, emoji: str):
self.__host_channel = host_channel
self.__emoji =... | 2,356 | 851 |
#!/usr/bin/env python
from time import sleep
from rediscache import rediscache
import time, redis
@rediscache(1, 2)
def getTestValue():
return (5, 'toto')
if __name__ == '__main__':
myfunction()
| 208 | 74 |
# Generated by Django 3.0.5 on 2020-12-11 14:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0004_auto_20201211_1411'),
]
operations = [
migrations.CreateModel(
name='Education',
fields=[
... | 588 | 194 |
import os
import os.path as ops
import glob
import random
import tqdm
SOURCE_IMAGE_DIR = '/home/luk/datasets/carla/04-10-town02-ss/gt_images'
SOURCE_LABEL_DIR = '/home/luk/datasets/carla/04-10-town02-ss/gt_annotation'
DST_IMAGE_INDEX_FILE_OUTPUT_DIR = '.'
unique_ids = []
for dir_name in os.listdir(SOURCE_IMAGE_DIR)... | 1,246 | 480 |
import pandas as pd
chicago_df=pd.read_csv("Chicago_Crime_2015-2017.csv")
#print(chicago_df.head())
chicago_vc = chicago_df["Primary Type"].value_counts()
pd.DataFrame(chicago_vc).to_csv("crime_types_chicago_1.csv")
| 216 | 92 |
trees = []
with open("input.txt", "r") as f:
for line in f.readlines():
trees.append(line[:-1])
# curr pos
x, y = 0, 0
count = 0
while True:
x += 3
y += 1
if y >= len(trees):
break
if trees[y][x % len(trees[y])] == '#':
count += 1
print(count) | 293 | 144 |
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.test import TestCase
from .models import Event
UserModel = get_user_model()
class TestHappeningsGeneralViews(TestCase):
fixtures = ['events.json', 'users.json']
def setUp(self):
self.event = Even... | 3,193 | 974 |
import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Input
from tensorflow.keras.losses import binary_crossentropy, sparse_categorical_crossentropy
from bopflow.models.darknet import darknet_conv_upsampling, darknet_conv, darknet
from bopflow.models.utils im... | 12,618 | 4,500 |
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.9.3 on Wed Sep 11 13:50:00 2019
#
import wx
# begin wxGlade: dependencies
# end wxGlade
# begin wxGlade: extracode
# end wxGlade
class MyDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: MyDialog.__init__
kwds["style"] = kw... | 1,904 | 747 |
from gsi_handlers.sim_handlers import _get_sim_info_by_id
from sims4.gsi.dispatcher import GsiHandler
from sims4.gsi.schema import GsiGridSchema
familiar_schema = GsiGridSchema(label='Familiars', sim_specific=True)
familiar_schema.add_field('familiar_name', label='Name')
familiar_schema.add_field('familiar_type', label... | 1,227 | 382 |
#35011
#a3_p10.py
#Miruthula Ramesh
#mramesh@jacobs-university.de
n = int(input("Enter the width"))
w = int(input("Enter the length"))
c = input("Enter a character")
space=" "
def print_frame(n, w):
for i in range(n):
if i == 0 or i == n-1:
print(w*c)
else:
pr... | 368 | 163 |
# Copyright (C) 2012 Dr. Ralf Schlatterbeck Open Source Consulting.
# Reichergasse 131, A-3411 Weidling.
# Web: http://www.runtux.com Email: office@runtux.com
# All rights reserved
# ****************************************************************************
# This library is free software; you can redistribute it and... | 3,430 | 1,221 |
#!/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import numpy.linalg as nl
import scipy.linalg as sl
import scipy.stats as ss
import time
aca = np.ascontiguousarray
def nul(n):
return np.zeros((n, n))
def iuc(x, y):
"""
Checks if pair of generalized EVs x,y is inside the unit circle. Here for ... | 8,091 | 3,199 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 10:36:17 2019
@author: tuyenta
"""
s = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896... | 1,357 | 1,155 |
import json
import time
from datetime import datetime
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mod... | 6,649 | 2,182 |
import collections
import logging
from event_model import DocumentRouter, RunRouter
import numpy
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
import matplotlib
from qtpy.QtWidgets import ( # noqa
QLabel,
QWidget,
QVB... | 12,104 | 3,457 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .gamma_prior import GammaPrior
from .multivariate_normal_prior import MultivariateNormalPrior
from .normal_prior import NormalPrior
from .smoothed_box_prior import S... | 586 | 198 |
import time
from pageobjects.environments import Environments, Wizard, DeployChangesPopup
from pageobjects.header import TaskResultAlert
from pageobjects.nodes import Nodes, RolesPanel
from settings import OPENSTACK_CENTOS, OPENSTACK_RELEASE_CENTOS
from tests.base import BaseTestCase
class Environment:
@staticme... | 2,660 | 804 |
import base64
import datetime
import http.client
import json
import sys
from pyblake2 import blake2b
from flask import Flask, request
from flask import render_template
from util.config import host_config
app = Flask(__name__)
AUTH_SIZE = 16
API_KEY = 'aaeaa04350f3485eb3074dd3a2c4429a' # use the provided one
SECRE... | 3,080 | 1,114 |
import os
import json
from fair_research_login import NativeClient
CLIENT_ID = 'e54de045-d346-42ef-9fbc-5d466f4a00c6'
APP_NAME = 'My App'
SCOPES = 'openid email profile urn:globus:auth:scope:transfer.api.globus.org:all urn:globus:auth:scope:search.api.globus.org:all'
CONFIG_FILE = 'tokens-data.json'
tokens = None
# ... | 937 | 331 |
import requests
import os.path, json
import time
from store_order import *
from load_config import *
def get_last_coin():
"""
Scrapes new listings page for and returns new Symbol when appropriate
"""
latest_announcement = requests.get("https://www.binance.com/bapi/composite/v1/public/cms/article/cata... | 1,996 | 621 |
# -*- coding: utf8 -*-
from distutils.core import setup
setup(
name='pyfixwidth',
packages=['fixwidth'],
version='0.1.1',
description="Read fixed width data files",
author='Chris Poliquin',
author_email='chrispoliquin@gmail.com',
url='https://github.com/poliquin/pyfixwidth',
keywords=[... | 797 | 231 |
# Libraries
import ast
import collections
import pandas as pd
# -----------------
# Methods
# -----------------
def invert(d):
if isinstance(d, dict):
return {v: k for k, v in d.items()}
return d
def str2eval(x):
if pd.isnull(x):
return None
return ast.literal_eval(x)
def sortkeys(... | 1,274 | 444 |
import argparse
import twitter
import os
import json
from likes import Likes
import sys
import time
class Downloader:
def __init__(self):
self._current_path = os.path.dirname(os.path.realpath(__file__))
def downloadLikes(self, api, screen_name, force_redownload):
liked_tweets = Likes(
... | 3,424 | 942 |
import gym
import numpy as np
env = gym.make('FrozenLake-v0')
#env = env.unwrapped
print(env.observation_space)
print(env.action_space)
def play_policy(env, policy, render=True):
total_reward = 0
observation = env.reset()
while True:
if render:
env.render()
action = np.random.c... | 701 | 252 |
import json
import pathlib
import platform
import dask
import distributed
import pytest
import scheduler_profilers
pytest_plugins = ["docker_compose"]
def core_test(client: distributed.Client, tmp_path: pathlib.Path) -> None:
df = dask.datasets.timeseries().persist()
scheduler_prof_path = tmp_path / "prof... | 1,616 | 529 |
#!/usr/bin/env python
from pydgutils_bootstrap import use_pydgutils
use_pydgutils()
import pydgutils
from setuptools import setup, find_packages
try:
from pip.req import parse_requirements
except:
from pip._internal.req import parse_requirements
package_name = 'ncstyler'
# Convert source to v2... | 1,889 | 587 |
import csv
import cv2
import numpy as np
import copy
from sklearn.utils import shuffle
"""
Data generator and augmentation methods. The generator called
get_flipped_copies and get_color_inverted_copies, if augmentation mode
is activated.
The usage of color inverted copies is done to make the algorithm also work on st... | 7,521 | 2,239 |
import sys
import math
from collections import defaultdict, deque
sys.setrecursionlimit(10 ** 6)
stdin = sys.stdin
INF = float('inf')
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().strip()
N, X = na()
S = ns()
up = 0
tmp_S = ""
for c in S[::-1]:
if c =... | 689 | 283 |
import pytest
import math
import torch
from detector.fcos.map import Mapper
from test.fcos.level_map_fixtures import (
image_size,
strides,
sample,
targets,
expected_level_map_sizes,
expected_joint_map_8x8
)
@pytest.fixture
def expected_level_thresholds(expected_level_map_sizes, image_size):
pixel_sizes = ... | 1,580 | 640 |
import sqlalchemy
from sqlalchemy.ext.compiler import compiles
import sys
from src.container import create_container
from src.models.base import Base
from src.models import *
@compiles(sqlalchemy.LargeBinary, 'mysql')
def compile_binary_mysql(element, compiler, **kw):
if isinstance(element.length, int) and eleme... | 770 | 258 |
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is
# located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... | 4,586 | 1,295 |
# -*- coding: utf-8 -*-
"""
audit api module.
"""
import pyrin.audit.services as audit_services
from pyrin.api.router.decorators import api
audit_config = audit_services.get_audit_configurations()
audit_config.update(no_cache=True)
is_enabled = audit_config.pop('enabled', False)
if is_enabled is True:
@api(**a... | 3,696 | 746 |
a = int(input())
sum = 0
while True:
if ( a == 0):
print (int(sum))
break
if ( a <= 2):
print (-1)
break
if (a%5 != 0):
a = a - 3
sum = sum + 1
else:
sum = sum + int(a/5)
a = 0
| 222 | 109 |
# Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from numpy.testing import assert_almost_equal
from mmpose.models import build_loss
from mmpose.models.utils.geometry import batch_rodrigues
def test_mesh_loss():
"""test mesh loss."""
loss_cfg = dict(
type='MeshLoss',
... | 5,793 | 2,430 |
"""IntegerHeap.py
Priority queues of integer keys based on van Emde Boas trees.
Only the keys are stored; caller is responsible for keeping
track of any data associated with the keys in a separate dictionary.
We use a version of vEB trees in which all accesses to subtrees
are performed indirectly through a hash table... | 6,932 | 2,017 |
# Copyright 2021 Fedlearn 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 applicable law or agreed to in writi... | 3,238 | 901 |
from __future__ import print_function
#
# cfg file to pack (DigiToRaw) a GT DAQ record, unpack (RawToDigi) it back
# and compare the two set of digis
#
# V M Ghete 2009-04-06
import FWCore.ParameterSet.Config as cms
# process
process = cms.Process('TestGtPackUnpackAnalyzer')
###################### user choices #####... | 9,369 | 4,259 |
from operator import is_
from ._helper import _UnhashableFriendlyDict, _LinkedList, _is_iterable_non_string, Rangelike
from .Range import Range
from .RangeSet import RangeSet
from typing import Iterable, Union, Any, TypeVar, List, Tuple, Dict, Tuple
T = TypeVar('T', bound=Any)
V = TypeVar('V', bound=Any)
class Range... | 39,103 | 10,412 |
from django.urls import path
from cases.api.get_visuals_data import UpdateVisualsData
from cases.api.kenyan_cases import KenyanCaseList
from cases.api.visuals import VisualList
urlpatterns = [
path('kenyan/all', KenyanCaseList.as_view(), name='Historical data'),
path('history/', VisualList.as_view(), name='Hi... | 428 | 131 |
from typing import List
import pytest
from cfn_lint_ax.rules import (
CloudfrontDistributionComment,
CloudfrontDistributionLogging,
)
from tests.utils import BAD_TEMPLATE_FIXTURES_PATH, ExpectedError, assert_all_matches
@pytest.mark.parametrize(
"filename,expected_errors",
[
(
"c... | 1,198 | 316 |
'''
records.py: base record class for holding data
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2018 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more... | 3,661 | 990 |
#!/usr/bin/env python
##############################################################
# preparation of srtm data for use in gamma
# module of software pyroSAR
# John Truckenbrodt 2014-18
##############################################################
"""
The following tasks are performed by executing this script:
-readi... | 12,080 | 4,101 |
import unittest
from my_test_api import TestAPI
class TestCreateIssue(TestAPI):
def test_create_issue(self):
params = {
'project': 'API',
'summary': 'test issue by robots',
'description': 'You are mine ! ',
}
response = self.put('/issue/', params)
... | 631 | 195 |
from model.contact import Contact
from model.group import Group
import random
def test_add_contact_to_group(app, db):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname="contact", lastname="forGroup", address="UA, Kyiv, KPI", homephone="0123456789", email="test@mail.com"))
if len... | 1,422 | 489 |
from .model import ResUnetPlusPlus
| 35 | 11 |
import csv
from collections import Counter
from collections import defaultdict
from datetime import datetime
# Make dictionary with district as key
# Create the CSV file: csvfile
csvfile = open('crime_sampler.csv', 'r')
# Create a dictionary that defaults to a list: crimes_by_district
crimes_by_district = defaultdic... | 1,416 | 409 |
#!/usr/bin/env python
# Break up idstr file into separate measid/objectid lists per exposure on /data0
import os
import sys
import numpy as np
import time
from dlnpyutils import utils as dln, db
from astropy.io import fits
import sqlite3
import socket
from argparse import ArgumentParser
def breakup_idstr(dbfile):
... | 4,016 | 1,343 |
#!/usr/bin/python
__author__ = "Bassim Aly"
__EMAIL__ = "basim.alyy@gmail.com"
from fabric.api import *
env.hosts = [
'10.10.10.140', # ubuntu machine
'10.10.10.193', # CentOS machine
]
env.user = "root"
env.password = "access123"
def run_ops():
output = run("hostname")
def get_ops():
try:
... | 721 | 281 |
import os
from Model.Model import *
from Handlers.AddGuest import AddGuest
from Handlers.QueryGuest import QueryGuest
from Handlers.EventsCreation import EventsCreation
from Handlers.EventRemoval import EventRemoval
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoade... | 1,882 | 590 |
import unittest
from year import is_leap_year
class YearTest(unittest.TestCase):
def test_leap_year(self):
self.assertTrue(is_leap_year(1996))
def test_non_leap_year(self):
self.assertFalse(is_leap_year(1997))
def test_non_leap_even_year(self):
self.assertFalse(is_leap_year(1998... | 530 | 210 |
# Licensed under an MIT open source license - see LICENSE
'''
Runs data_reduc on all data cubes in the file.
Creates a folder for each data cube and its products
Run from folder containing data cubes
'''
from turbustat.data_reduction import *
from astropy.io.fits import getdata
import os
import sys
import errno
im... | 1,934 | 758 |
import copy
import random
import torch
import unittest
from torch_geometric.datasets import TUDataset, Planetoid
from copy import deepcopy
from deepsnap.graph import Graph
from deepsnap.hetero_graph import HeteroGraph
from deepsnap.dataset import GraphDataset, Generator, EnsembleGenerator
from tests.utils import (
... | 44,549 | 14,262 |
import aiohttp
import asyncio
import os
import string
import random
import argparse
async def upload_follow(session, addr, user_0, user_1):
payload = {'user_name': 'username_' + user_0,
'followee_name': 'username_' + user_1}
async with session.post(addr + '/wrk2-api/user/follow', data=payload) as res... | 5,425 | 1,893 |
from . import TestReader
from reader.models import WikiArticle
class TestWikiArticle(TestReader):
def test_get_wiki_article(self):
wiki = WikiArticle(search="M. Antonius Imperator Ad Se Ipsum", article="Meditations")
wiki.save()
wiki2 = WikiArticle(search="M. Antonius Imperato... | 1,152 | 338 |
# -*- coding: utf-8 -*-
import unittest
import unittest.mock as mock
import requests
import json
from io import BytesIO
from fastapi.testclient import TestClient
from projects.api.main import app
from projects.database import session_scope
import tests.util as util
app.dependency_overrides[session_scope] = util.ove... | 7,399 | 2,291 |
def add_num(x, y):
return x + y
def sub_num(x, y):
return x - y
class MathFunctions(object):
pass
| 114 | 48 |
import boto3
import json
import datetime
import logging
import os
import ipaddress
import requests
log = logging.getLogger()
log.setLevel(logging.INFO)
QUEUE_URL = os.environ['SQS_QUEUE_CLOUD_SNIPER']
DYNAMO_TABLE = os.environ['DYNAMO_TABLE_CLOUD_SNIPER']
WEBHOOK_URL = os.environ['WEBHOOK_URL_CLOUD_SNIPER']
HUB_ACCOU... | 37,344 | 11,470 |
from __future__ import absolute_import
import unittest
import sys
from testutils import ADMIN_CLIENT
from testutils import harbor_server
from library.project import Project
from library.user import User
from library.repository import Repository
from library.repository import push_image_to_project
from li... | 17,311 | 5,512 |
import requests
import logging
import os
import diffhtml
from django.conf import settings
from django.shortcuts import render
from django.core.mail import EmailMessage
from django.template import loader
from django.contrib.auth.models import User
from django_q.tasks import async_chain, result_group
from hackmds.mode... | 3,728 | 1,224 |
import logging
from frozendict import frozendict
def log_with_context(message, context=frozendict({}), log_level='info', **kwargs):
log_function = __get_log_function(log_level)
log_context_prefix = __get_log_context_prefix(context)
if log_context_prefix:
log_function(f"{log_context_prefix} {mess... | 814 | 263 |
if __name__ == '__main__':
N = int(input())
main_list=[]
for iterate in range(N):
entered_string=input().split()
if entered_string[0] == 'insert':
main_list.insert(int(entered_string[1]),int(entered_string[2]))
elif entered_string[0] == 'print':
print(main_lis... | 734 | 229 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-07-04 00:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0054_assessment_licence_activity_type'),
]
operations = [
... | 742 | 223 |
with open('input.txt', 'r') as file:
input = file.readlines()
input = [ step.split() for step in input ]
input = [ {step[0]: int(step[1])} for step in input ]
def part1():
x = 0
y = 0
for step in input:
x += step.get('forward', 0)
y += step.get('down', 0)
y -= step.get('up', 0)... | 677 | 274 |
__author__ = "Ryan Faulkner"
__date__ = "July 27th, 2012"
__license__ = "GPL (version 2 or later)"
from os import getpid
from collections import namedtuple
import user_metric as um
from user_metrics.metrics import query_mod
from user_metrics.metrics.users import UMP_MAP
from user_metrics.utils import multiprocessing_... | 4,307 | 1,329 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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, overload
from .. import _utilities
from... | 7,210 | 2,055 |
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from .models... | 8,224 | 2,510 |
def f(x):
if x:
x = 1
else:
x = 'zero'
y = x
return y
f(1)
| 101 | 52 |
""" Library to perform sequences of electronic structure calculations
along a molecular coordinate and save the resulting information to
SCAN or CSAN layers of the save filesystem.
"""
import numpy
import automol
import autofile
import elstruct
from phydat import phycon
from mechlib import filesys
from mechli... | 23,950 | 7,690 |
"""
Designed to be used in conjunction with xtream1101/humblebundle-downloader.
Takes the download directory of that script, then copies all file types of
each non-comic book to a chosen directory.
Each folder in the target directory will be one book, containing the
different file formats available for the boo... | 3,296 | 982 |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 requ... | 2,276 | 790 |
class Pattern_Twenty_Six:
'''Pattern twenty_six
***
* *
*
* ***
* *
* *
***
'''
def __init__(self, strings='*'):
if not isinstance(strings, str):
strings = str(strings)
for i in range(7):
if i i... | 633 | 204 |
import numpy as np
A = np.asarray([[-5, -5, -1, 0, 0, 0, 500, 500, 100],
[0, 0, 0, -5, -5, -1, 500, 500, 100],
[-150, -5, -1, 0, 0, 0, 30000, 1000, 200],
[0, 0, 0, -150, -5, -1, 12000, 400, 80],
[-150, -150, -1, 0,... | 1,069 | 623 |
from rest_framework import serializers
from ..models import Faculties, Departaments, StudyGroups, Auditories, Disciplines
class FacultiesSerializers(serializers.ModelSerializer):
"""Faculties API"""
class Meta:
fields = '__all__'
model = Faculties
class DepartamentsSerializers(serializers.M... | 911 | 261 |
"""
info_routes.py - Handle the routes for basic information pages.
This module provides the views for the following routes:
/about
/privacy
/terms_and_conditions
Copyright (c) 2019 by Thomas J. Daley. All Rights Reserved.
"""
from flask import Blueprint, render_template
info_routes = Blueprint("info_routes", __na... | 713 | 226 |