text string | size int64 | token_count int64 |
|---|---|---|
from chainer import backend
from chainer import function_node
from chainer.utils import argument
from chainer.utils import type_check
def _calc_axis_and_m(x_shape, batch_size, groups):
m = batch_size * groups
spatial_ndim = len(x_shape) - 2
spatial_axis = tuple(range(2, 2 + spatial_ndim))
for i in spa... | 10,440 | 3,596 |
#
# Example file for parsing and processing JSON
# (For Python 3.x, be sure to use the ExampleSnippets3.txt file)
def main():
# define a variable to hold the source URL
# In this case we'll use the free data feed from the USGS
# This feed lists all earthquakes for the last day larger than Mag 2.5
urlDat... | 439 | 155 |
import os
import unittest
import uuid
from env_flag import env_flag
class EnvironGetBoolTest(unittest.TestCase):
def test_that_env_flag_for_unset_returns_false(self):
env_var = str(uuid.uuid4())
self.assertIsNone(os.environ.get(env_var))
self.assertFalse(env_flag(env_var))
def test_tha... | 2,306 | 830 |
import os, sys
import subprocess
from pathlib import Path
import ml
from ml import (
cuda,
distributed as dist,
multiprocessing as mp,
random,
utils,
logging,)
def init_cuda(cfg):
if cfg.no_gpu:
# No use of GPU
cfg.gpu = []
os.environ['CUDA_VISIBLE_DEVICES'] = 'NoDe... | 5,857 | 1,936 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyvirtualdisplay import Display
import urllib3.exceptions
import traceback
import string
import time
import re
prin... | 2,497 | 816 |
"""remove enum from tile
Revision ID: 19e8e023f5fb
Revises: cf2e08638e84
Create Date: 2018-08-23 12:43:31.403270
"""
# revision identifiers, used by Alembic.
revision = '19e8e023f5fb'
down_revision = 'cf2e08638e84'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade()... | 769 | 308 |
#! /usr/bin/env python
# example of exec
exec "print 'Hello, world!'"
# another example
from math import sqrt
scope = {}
exec 'sqrt = 1' in scope
print "sqrt of 4:", sqrt(4)
print "scope:", scope['sqrt'], '\n', "length of scope:", len(scope)
# example of eval
eval(raw_input("Enter an arithmetic expression: ")) | 318 | 112 |
import os, sys
sys.path.append(os.getcwd())
import time
import numpy as np
import tensorflow as tf
import tflib as lib
import tflib.ops.linear
import tflib.ops.conv2d
import tflib.ops.batchnorm
import tflib.ops.deconv2d
import tflib.save_images
import tflib.cifar10
import tflib.inception_score
import tflib.plot
# D... | 15,510 | 6,553 |
"""===============================================================================
FILE: tests/test_wquantile.py
USAGE: (not intended to be directly executed)
DESCRIPTION:
OPTIONS: ---
REQUIREMENTS: ---
BUGS: ---
NOTES: ---
AUTHOR: Alex Leontiev (nailbiter@dtws-work.in)
ORG... | 2,224 | 732 |
text = "X-DSPAM-Confidence: 0.8475"
print(float(text[text.find(" "):].strip()))
| 83 | 38 |
import os
from selenium import webdriver
class TestGoogle:
def setup_method(self, method):
self.driver = webdriver.Chrome(executable_path=os.environ.get('CHROME_DRIVER_PATH'))
self.driver.get('http://www.google.com')
def teardown_method(self, method):
self.driver.close()
def tes... | 636 | 217 |
import uvicorn
from fastapi import FastAPI,Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import asyncio
from search_video_eporner import get_porn_div
origins = ["*"]
app = FastAPI()
... | 761 | 279 |
path = 'C:\\Users\\akash\\Pictures\\Sign-Language-Digits-Dataset-master\\Dataset\\'
import os
from PIL import Image
for i in range(3):
for filename in os.listdir(path + str(i)):
if filename != "":
image_obj = Image.open(path + str(i) + "\\" + filename).convert('L')
rotated_image = i... | 912 | 307 |
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
# pylint: disable=unused-variable
import pytest
from simcore_service_webserver.scicrunch.settings import SciCrunchSettings
@pytest.fixture
async def settings() -> SciCrunchSettings:
return SciCrunchSettings(SCICRUNCH_API_KEY="fake-secret-k... | 325 | 111 |
# -*- coding: utf-8 -*-
from .bundle import Day
def init(dtype='day', export='csv', path=None):
return Day(path=path, export=export).init()
def single(dtype='day', stock=None, path='history', export='csv'):
if stock is None:
raise Exception('stock code is None')
return Day(path=path, export=exp... | 677 | 225 |
from celery.decorators import periodic_task
from celery.schedules import crontab
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django_filters import rest_framework as ... | 4,409 | 1,276 |
#!/usr/bin/env python
"""
Author: Adam White, Mohammad M. Ajallooeian, Sina Ghiassian
Purpose: Code for the Gambler's problem environment from the Sutton and Barto
Reinforcement Learning: An Introduction Chapter 4.
For use in the Reinforcement Learning course, Fall 2017, University of Alberta
"""
from utils ... | 2,173 | 670 |
import my_functions
my_functions.foo() | 39 | 13 |
import os
import re
import zlib
from typing import List, Dict, Union, Optional, Generator, Iterable
from collections import defaultdict
import logging
import requests
from .data import Language
from .tools import write_file_or_remove
from .storage import (
BaseVersion,
Storage,
Patch,
PatchElement,
... | 23,272 | 6,659 |
import numpy as np
from numpy.testing import assert_allclose
import pandas as pd
from arch.bootstrap.base import optimal_block_length
def test_block_length():
rs = np.random.RandomState(0)
e = rs.standard_normal(10000 + 100)
y = e
for i in range(1, len(e)):
y[i] = 0.3 * y[i - 1] + e[i]
s ... | 935 | 405 |
from support import *
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import shap
GREY = '#444443'
n = 20_000
shap_test_size = 1000
X, y = load_bulldozer(n=50_000)
# Most recent timeseries data is more relevant so get big recent chunk
# then we can sample from that to get n
X = X.iloc[-50_00... | 2,836 | 1,179 |
#FLM: Font: Mark Composites (Typerig)
# VER : 1.0
# ----------------------------------------
# (C) Vassil Kateliev, 2019 (http://www.kateliev.com)
# (C) Karandash Type Foundry (http://www.karandash.eu)
#-----------------------------------------
# www.typerig.com
# No warranties. By using this you agree
# that you use ... | 640 | 245 |
import scenario1
import unittest
cost = scenario1.findCost
class Scenario1Test(unittest.TestCase):
def test_init(self):
pass
def test_ten(self):
routes = 'data/route-costs-10.txt'
# find longest route
assert cost(routes, '+449275049230') == '0.49'
assert cost(rout... | 1,246 | 499 |
import FWCore.ParameterSet.Config as cms
from FWCore.Services.InitRootHandlers_cfi import *
# Tell AdaptorConfig to suppress the statistics summary. We aren't actually using
# that service and it's summary interferes with the MessageLogger summary.
AdaptorConfig = cms.Service("AdaptorConfig",
stats = cms.untrack... | 337 | 106 |
import imgui
imgui.create_context()
io=imgui.get_io()
texWidth, texHeight, fontData = io.fonts.get_tex_data_as_rgba32()
io.display_size = imgui.Vec2(100,200)
imgui.new_frame()
imgui.render()
imgui.new_frame()
imgui.begin('Vulkan Example', None, imgui.WINDOW_ALWAYS_AUTO_RESIZE | imgui.WINDOW_NO_RESIZE| imgui.WINDOW_N... | 851 | 378 |
from congregation.dag.nodes import OpNode
class Dag:
def __init__(self, roots: set):
self.roots = roots
def __str__(self):
return "\n".join(str(node) for node in self.top_sort())
def involves_compute_party(self, pid: int):
"""
For a given PID, check if it owns any
... | 2,154 | 668 |
import sublime
import time
import functools
from .settings import run_on_main_thread
from .package_disabler import PackageDisabler
# How many packages to ignore and unignore in batch to fix the ignored packages bug error
PACKAGES_COUNT_TO_IGNORE_AHEAD = 8
# The minimum time between multiple calls setting the `igno... | 8,940 | 2,570 |
from .args import *
from .stats import *
from .utils import *
from .generators import *
from . import main
| 107 | 31 |
nome = str(input('Digite seu nome completo: ')).strip()
div_nome = nome.split()
print('Primeiro = {}\nÚltimo = {}'.format(div_nome[0], div_nome[len(div_nome)-1])) | 162 | 63 |
from dataclasses import asdict
from gallium import ICommand
from imagination import container
import yaml
from keymaster.server.model.user import DefaultRole
from keymaster.server.service.user_service import UserService
class CreateNewUser(ICommand):
"""Create a new user (run as a system user)"""
def ident... | 2,025 | 504 |
#!/usr/bin/env python3
#
# attr: concurrency 0
# attr: memory 128
# attr: timeout 60
# policy: AWSLambdaBasicExecutionRole
import base64
import boto3
import os
def decrypt(text):
return boto3.client('kms').decrypt(CiphertextBlob=base64.b64decode(bytes(text, 'utf-8')))['Plaintext'].decode('utf-8')
def main(event,... | 798 | 310 |
from .helpers import _as_bytes
from .helpers import b64_str
from .helpers import from_b64_str
from .helpers import _get_client
from .helpers import _prefix_alias
def encrypt_bytes(
plain_text: bytes
, alias: str
, region: str = None
, profile: str = None) -> bytes:
client = _get_cl... | 1,125 | 380 |
# --------------------------------
# Name: transit_svc_measure.py
# Purpose: Get count of intersection density per acre
#
#
# Author: Darren Conly
# Last Updated: <date>
# Updated by: <name>
# Copyright: (c) SACOG
# Python Version: 3.x
# --------------------------------
import gc
import sys
import arcpy
# import pp... | 3,275 | 1,142 |
from django.urls import path
from expenses.api.create import ExpenseCreateApi
from expenses.api.list import ExpenseListApi, periodicities_list_api
from expenses.api.update import ExpenseUpdateApi
from expenses.api.delete import ExpenseDeleteApi
urlpatterns = [
path('api', ExpenseListApi.as_view()),
path('api/p... | 530 | 166 |
import json,os,sys
filename = sys.argv[1]
file_path = "../build/contracts/"+filename
content = open(file_path, "r").read()
object = json.loads(content)
abi = json.dumps(object['abi'], indent=2)
bin = object['unlinked_binary'][2:]
open(filename+".abi","w").write(abi)
open(filename+".bin","w").write(bin)
| 308 | 117 |
import trinity.bonds as bonds
import trinity.returns as returns
def test_simulate_returns(expected_bond_returns):
"""Ensure simulated returns match published results."""
interest_rates = [(year['rate'], year['rate_long'])
for year in returns.read_shiller()]
simulated_returns = bonds... | 499 | 150 |
import discord
from discord.ext import commands
class KarutaKeqingAutoReact(commands.Cog):
"""
Reacts to karuta character lookup and collection for keqing bot.
"""
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
... | 705 | 232 |
"""
Copyright (c) 2015, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import absolute_import
import json
import os
import responses
import yaml
from tempfile import NamedTemporaryFile
from... | 4,035 | 1,497 |
#! /usr/bin/env python
# Copyright (c) 2022 Predibase, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 2,162 | 673 |
from io import BytesIO
import pytest
from megfile.interfaces import BasePath, Closable, Readable, URIPath, Writable
class Klass1(Closable):
pass
class Klass2(Closable):
def __init__(self):
self.outer_close_call_count = 0
def _close(self):
self.outer_close_call_count += 1
class Kla... | 3,735 | 1,387 |
from tools import LudiException
__author__ = 'maciek'
class Translation(object):
class Type(object):
NOUN = 'n'
VERB = 'v'
ADJECTIVE = 'adj'
ADVERB = 'adv'
PRONOUN = 'pn'
PREPOSITION = 'prep'
CONJUNCTION = 'conj'
def __init__(self, word):
self.... | 2,563 | 740 |
#!/usr/bin/env python
#coding:utf-8
from email.mime.text import MIMEText
from email.header import Header
import smtplib
sender='xxxxx@qq.com'
sender_pass='xxxxxxxxxxxxxx'
host='smtp.qq.com'
recivers=['xxxxxxxx@xxx.com']
def mail():
message=MIMEText('python 邮件发送111','plain','utf-8')
message['From']='{}'.format(sender... | 608 | 272 |
import functools
from dtpattern.alignment.alignment_list import align_global, finalize, format_alignment2
from dtpattern.unicode_translate.uc_models import FIX_SYMB
from pyjuhelpers.timer import timer
class Alignment(object):
def __init__(self, alpha, beta, translate=None, m=6, mm=-4, om=3, csetm=4,go=-10, ge... | 6,582 | 1,968 |
from datetime import date, datetime
import pytest
from proper_forms import Date, DateTime, Field, Integer
from proper_forms import validators as v
def test_confirmed_message():
validator = v.Confirmed()
assert validator.message == "Values doesn't match."
assert v.Confirmed(message="custom").message == "... | 6,056 | 2,563 |
#!/usr/bin/env python2
import rospy
import numpy as np
import threading
from timeit import default_timer as timer
import time
class FPS:
def __init__(self):
self.period_update = 0.2 # sec.
self.window_size = 25 # samples
self.max_cumulated_step = 100000
#
self.buffer_cumul... | 2,084 | 719 |
# Generated by Django 2.2.3 on 2019-07-05 08:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('video', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='videotype',
... | 631 | 208 |
import asyncio
import logging
import arrlio
import tasks
from arrlio import crypto
from arrlio.serializer.json import CryptoJson
logger = logging.getLogger("arrlio")
logger.setLevel("INFO")
BACKEND = "arrlio.backend.local"
async def main():
async def example_1():
producer = arrlio.Producer(arrlio.Pro... | 2,966 | 879 |
from enum import Enum
class FaceType(Enum):
WALL = (0, 'Walls', 'MOD_BUILD', ['M', 'W'], 'wall')
FLOOR = (1, 'Floors', 'TEXTURE', ['S', 'F'], 'floor')
ROOF = (2, 'Roofs', 'LINCURVE', ['T', 'R'], 'roof')
def get_id(self):
return self.value[0]
def get_name(self):
return self.value[... | 685 | 254 |
def tribonacci(n):
if n < 3:
return n
else:
return tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)
def tribonacciBottomUp(n):
last = 1
secondLast = 1
thirdLast = 1
for i in range(2,n):
new = last + secondLast + thirdLast
thirdLast = secondLast
secondL... | 496 | 189 |
from __future__ import annotations
import ast
import pytest
from flake8_pie import Flake8PieCheck
from flake8_pie.pie803_prefer_logging_interpolation import PIE803
from flake8_pie.tests.utils import Error, ex, to_errors
EXAMPLES = [
ex(
code=r"""
logger.info("Login error for %s" % user)
""",
... | 1,805 | 709 |
from test.data import bob, cheese, hates, likes, michel, pizza, tarek
from rdflib import Graph
class TestGraphSlice:
def test_slice(self):
"""
We pervert the slice object,
and use start, stop, step as subject, predicate, object
all operations return generators over full triples
... | 1,517 | 523 |
class ValidationException(Exception):
def __init__(self, message):
self.message = message
@classmethod
def export_in_progress(cls):
raise ValidationException("Export is still running")
class LimitExceededException(Exception):
def __init__(self, message):
self.message = message... | 821 | 238 |
import json
from typing import List, Union
from .Tag import Tag
from .audits.TagsAudits import TagsAudits
class Tags:
def __init__(self, _http):
self._http = _http
self.Audits = TagsAudits(_http)
def get(
self,
id: str = None,
page: int = None,
pageSize: int ... | 2,163 | 693 |
from collections import Counter, defaultdict
from typing import Dict, List
import config
def calculate_crab_pos_change_fuel(start: int, end: int) -> int:
"""Calculate the amount of fuel changed per position.
Args:
start (int): starting position
end (int): ending position
Returns:
... | 1,458 | 511 |
import datetime
from functools import reduce
from urllib.parse import urlsplit
from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import ugette... | 5,730 | 1,703 |
import json
import mock
from changes.config import db
from changes.testutils import APITestCase
class KickSyncRepoTest(APITestCase):
path = '/api/0/kick_sync_repo/'
def setUp(self):
self.repo = self.create_repo()
db.session.commit()
super(KickSyncRepoTest, self).setUp()
def test... | 1,010 | 319 |
# Generated by Django 2.1.2 on 2018-12-11 21:08
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('deployments', '0008_auto_20181211_1656'),
]
operations = [
migrations.AddField(
model_name='p... | 497 | 181 |
#!/usr/bin/python3
import smtplib
import ssl
import traceback
from email.message import EmailMessage
import csv
csv_name = input("Enter path to CSV: ")
with open(csv_name) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
for row in csv_reader:
title = row[0]
last_name = row[1]
... | 1,350 | 404 |
import grpc
def load_file(filepath):
with open(filepath, "rb") as f:
return f.read()
def get_grpc_channel_credentials(client_crt, client_key, ca_root):
"""Returns a ChannelCredentials object to use with the grpc channel
https://grpc.github.io/grpc/python/grpc.html#create-client-credentials
... | 609 | 205 |
# pylint: skip-file
import json
import subprocess
import sys
import api_extractor
try:
from semver import VersionInfo
except ImportError:
raise ImportError(
'semver must be installed for release. `pip install semver`'
)
try:
import koloro
except ImportError:
raise ImportError(
'koloro must be inst... | 2,020 | 738 |
'''
Exercício Python 081: Crie um programa que vai ler vários
números e colocar em uma lista. Depois disso, mostre:
A) Quantos números foram digitados.
B) A lista de valores, ordenada de forma decrescente.
C) Se o valor 5 foi digitado e está ou não na lista.
'''
lista = list()
while True:
lista.append(int(input(... | 674 | 249 |
#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./venus_messaging')
if args.REMOTE:
#p = remote('172.19.2.239',9080)
#port blocked? workaround: ssh -L 9080:localhost:9080 magellan@172.19.2.239
p = remote('localhost',9080)
libc = ELF('./libc.so.6')
# lame no ASLR
'''
# ldd /usr/bin/venu... | 1,327 | 680 |
# Generated by Django 3.2 on 2021-04-06 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('waterspout_api', '0013_modelarea_main_help_page_content'),
]
operations = [
migrations.AlterField(
model_name='calibratedparameter... | 4,565 | 1,290 |
"""**Configuration 변수들이 정의되는 module**
1. Constant는 대문자
----
"""
| 66 | 37 |
A = np.array([ [5, 4, 3, 2, 1], [1, 2, 3, 4, 5], [1.1, 2.2, 3.3, 4.4, 5.5] ])
print(A, "\n")
# set length(shape)
dims = A.shape
print(dims, "\n")
# slicing
print(A[-1, 2:], "\n")
print(A[1:3, 3:5], "\n")
# square
A2 = A * A
print(A2)
| 237 | 151 |
from django.conf import settings
from django.db import models
class RentInfo(models.Model):
class Meta:
db_table = "rentinfo"
houseID = models.CharField(primary_key=True, max_length=50)
updatedate = models.DateTimeField('updatedate')
decoration = models.CharField(max_length=50)
heating = ... | 752 | 247 |
#!/usr/bin/python3
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | 9,932 | 3,183 |
import base64
import random
import re
from django.conf import settings
from django.contrib import messages
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from ..decorators import prequal_completed
from ..models import Document, UserRespo... | 6,455 | 1,998 |
from django.contrib import admin
# Register your models here.
# 管理django后台的一个文件,我们要在后台中看到的数据库表都需要在这里注册,后续会详细说明
# 我们这里必须手动加上一句,从我的app里models 中导入所有类*
from MyApp.models import *
# 注册 刚刚的吐槽表:admin.site.register() 是注册用的函数,里面写类名,注意是类名,并不是类本身,所以不要加()
admin.site.register(DB_tucao)
admin.site.register(DB_home_href)
admin.site... | 633 | 319 |
#
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley.
#
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
# SEED Encryption Algorithm in CMS
#
# ASN.1 source from:
# https://www.rfc-editor.org/rfc/rfc4010.txt
#
from pyasn1.type import constraint
fro... | 796 | 351 |
class TooShortGPXException(ValueError):
"""GPX has less than 2 points, and so won't generate a heatmap cleanly."""
| 119 | 38 |
# coding: utf-8
# View a specific participant's assigned group details
# Created by James Raphael Tiovalen (2021)
import slack
import ast
import settings
import config
from slackers.hooks import commands
conv_db = config.conv_handler
@commands.on("viewgroupdeets")
def viewgroupdeets(payload):
return
| 311 | 100 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('isisdata', '0048_citationcollection_name'),
]
operations = [
migrations.AlterField(
model_name='authority',
... | 2,683 | 863 |
#!/usr/bin/env python
##############################################################################
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
################################... | 6,195 | 2,367 |
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(open("page.html"), "html.parser")
entries = soup.find_all("div", id=re.compile("dev.*"))
title_re = re.compile(".*\((.*)\)")
settings = []
for e in entries:
text = e.find("h2", class_="Name").text
m = title_re.match(text)
if m == None:
... | 404 | 143 |
class Node:
# Defining a Node
def __init__(self, key=None, value=None):
"""A Node Class
Keyword Arguments:
key {int} -- The unique key for a Node (default: {None})
value {int} -- The data for the the Node (default: {None})
"""
self.key = key
self.... | 4,604 | 1,264 |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label":_("Library"),
"icon": "octicon octicon-briefcase",
"items": [
{
"type": "doctype",
"name": "Article",
"label": _("Article"),
... | 1,148 | 290 |
import argparse
import os
import lightgbm as lgb
import joblib
parser = argparse.ArgumentParser()
parser.add_argument(
"--learning-rate",
type=float,
dest="learning_rate",
help="Learning date for LightGBM",
default=0.01,
)
parser.add_argument(
"--input-path",
type=str,
dest="input_path... | 1,213 | 431 |
# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate as django_authenticate
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
... | 12,365 | 3,362 |
from pyparsing import *
from string import printable, uppercase
from dateutil import parser as dateutil_parser
import yaml
class LogParser(object):
ACCESS_LOG_VARS = {
'request.first_line' : Word(uppercase)('request.method')+\
Literal(" ")+\
SkipTo(" ")('request.... | 6,446 | 1,726 |
# pylint: disable=missing-docstring
import unittest
import gzip
import tempfile
from biograph.vdb import vcf_to_parquet, anno_to_parquet
import biograph.vdb.parquet
import pyarrow as pa
import pandas as pd
class ParquetTestCases(unittest.TestCase):
def setUp(self):
# Make sure we test having multiple inp... | 12,196 | 3,889 |
import re
import asyncio
from html.parser import HTMLParser
import aiohttp
from discord.ext import commands
import config
def is_bot_author(id: int):
return id == 227473074616795137
async def t3_only(ctx):
return is_bot_author(ctx.author.id) or permission_check(ctx, 4)
async def mod_only(ctx):
return ... | 2,430 | 832 |
import glob
import ntpath
import pandas as pd
def build_timely_df(payments):
''' build the longitudinal dataset for figure 2b '''
timely_df = pd.DataFrame(columns=['Number of Payments',
'Value of Payments'])
for year in list(range(2009, 2018)):
timel... | 8,419 | 2,915 |
from .Anchor import Anchor
from Utils.config import *
class LoopAnchor(Anchor):
def __init__(self, elem):
if elem["type"] == "multiple_label":
super().__init__(elem["start"]+elem["inline-label"]+elem["separator"]+elem["inline-label"], LOOP)
self.start_regex = re.compile(elem["start"], flags=re.MULTILINE|re.IG... | 1,557 | 607 |
VALID_FILE_OPTIONS = [
"path",
"fileType",
"tags",
"includeFolder",
"name",
"limit",
"skip",
]
VALID_FILE_DETAIL_OPTIONS = ["fileID"]
VALID_UPLOAD_OPTIONS = [
"file",
"file_name",
"use_unique_file_name",
"tags",
"folder",
"is_private_file",
"custom_coordinates",... | 361 | 142 |
import os
import time
import csv
import pandas as pd
def formatdate(paymentDate):
months = dict(january='01', february='02', march='03', april='04', may='05', june='06', july='07', august='08', september='09', october='10', november='11', december='12')
paymentDateList = paymentDate.split()
if (len(payment... | 9,972 | 2,929 |
from minecraft.networking.packets import Packet
from minecraft.networking.types import (
String,
Byte,
VarInt,
Boolean,
UnsignedByte,
Enum,
BitFieldEnum,
AbsoluteHand,
)
class ClientSettingsPacket(Packet):
@staticmethod
def get_id(context):
return (
0x05
... | 1,929 | 653 |
import_error = None
try:
import ConfigSpace as cs
import ConfigSpace.hyperparameters as csh
from sspace.utils import sort_dict
cond_dispatch_leaves = {
'eq': cs.EqualsCondition,
'ne': cs.NotEqualsCondition,
'lt': cs.LessThanCondition,
'gt': cs.GreaterThanCondition,
... | 4,203 | 1,275 |
# 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... | 8,287 | 2,365 |
from transformers import RobertaPreTrainedModel
from transformers.models.roberta.modeling_roberta import RobertaEmbeddings, RobertaEncoder, RobertaPooler, RobertaLMHead, RobertaClassificationHead
from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions, MaskedLMOutput, SequenceClassifierOu... | 16,128 | 4,843 |
import functools
import math
import re
from dataclasses import dataclass
try:
# Python >=3.7
from re import Pattern
except ImportError:
# Python =3.6
from re import _pattern_type as Pattern
from typing import (
Callable,
Dict,
List,
Optional,
Union,
)
from RPA.PDF.keywords import (... | 14,847 | 4,045 |
import os
import pytest
from devtools_testutils import AzureRecordedTestCase
class KeysTestCase(AzureRecordedTestCase):
def _get_attestation_uri(self):
playback_uri = "https://fakeattestation.azurewebsites.net"
if self.is_live:
real_uri = os.environ.get("AZURE_KEYVAULT_ATTESTATION_URL... | 1,051 | 316 |
import sys
from PyQt5.QtWidgets import QVBoxLayout, QApplication, QMainWindow
import pandas as pd
from node_editor.node_content_widget import NodeContentWidget
from .dataframe_view import DataframeView
DEBUG = False
class DataTableContent(NodeContentWidget):
def __init__(self, node: 'Node', parent: 'QWidget' = N... | 1,918 | 569 |
"""Console script for ctimer."""
from ctimer import ctimer
import ctimer.ctimer_db as db
import sys
import argparse
from ctimer.visual import show_stats as ss
import logging
from ctimer import utils
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--debug",
help="Shorten cl... | 2,662 | 812 |
instructions = [sorted([int(num) for num in line.split("x")]) for line in open("input_2", "r").readlines()]
# Part 1
print("Part 1:", sum(3 * x * y + 2 * x * z + 2 * y * z for x, y, z in instructions))
# Part 1
print("Part 1:", sum(2 * x + 2 * y + x * y * z for x, y, z in instructions))
| 292 | 122 |
import importlib.metadata
try:
__author__ = """Muhammad Rafi"""
__version__ = importlib.metadata.version(__package__ or __name__)
except importlib.metadata.PackageNotFoundError:
__version__ = "0.6.5"
| 213 | 70 |
from abc import ABC
from typing import Awaitable, Callable, Type, Union
class EventBase(ABC):
pass
EventClass = Type[EventBase]
Handler = Callable[[EventBase], Union[None, Awaitable[None]]]
| 197 | 62 |
#This file was created by Wayne Dreyer
#It serves to create a zoomed/cropped image around the detected candidate
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from PIL import Image
import math
from ZoomObject import ZoomObject
#import DataObject as dataObject
#Takes in path to the ima... | 5,256 | 1,693 |
import pickle
import glob
import random
from tqdm import tqdm
import os
import collections
import urllib
import urllib.request
from urllib.request import Request, urlopen
import json
import shutil
class DatasetBuilder:
def __init__(self, name, data_type, classes, class_size):
self.name = name
self... | 2,032 | 676 |
from helpers import *
from flask import Flask, redirect, request, render_template, session
from flask_session import Session
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.route("/")
def index():
... | 391 | 137 |