text string | size int64 | token_count int64 |
|---|---|---|
from main import reverse, reverse1
def test1(benchmark):
assert benchmark(reverse, ["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]) == \
["!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"]
def test(benchmark):
assert benchmark(reverse1, ["I", "like", "big", "butts", "and", "I"... | 427 | 170 |
from instagram.client import InstagramAPI
from pprint import pprint
test_access_token = "1890268.7c3f1ab.e1c64ca8df38410099d98bff8a868bb6"
api = InstagramAPI(access_token=test_access_token)
pprint( api.user_recent_media())
| 226 | 104 |
""" Actor registry for rodario framework """
# local
from rodario import get_redis_connection
from rodario.exceptions import RegistrationException
# pylint: disable=C1001
class _RegistrySingleton(object):
""" Singleton for actor registry """
def __init__(self, prefix=None):
"""
Initialize t... | 2,356 | 695 |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | 1,851 | 588 |
import click
import logging
from . import logger, log_handler
from .organize import main, ORGANIZER_NAMES
from .storage.amazon_s3_storage import AWS_CLI_PARAMETERS
@click.group()
@click.option('--debug/--no-debug', default=False)
def organize(debug=False):
if debug:
logger.setLevel(logging.DEBUG)
... | 2,834 | 914 |
#!/usr/bin/env python3
# Copyright 2019, Alex Wiens <awiens@mail.upb.de>, Achim Lösch <achim.loesch@upb.de>
# SPDX-License-Identifier: BSD-2-Clause
# Reads ms task measurement results from CSV files.
#
# If the path to the results is not given it is read from the following environment variables:
# * SCHED_MSRESULTS
... | 5,798 | 2,432 |
import time
from prometheus_client import start_http_server, Gauge, Enum
from temper import Temper
def main():
port = 9204
t = Temper()
label_names = ['vendorid','productid','busnum','devnum']
temp_c = Gauge('temper_internal_temperature_celsius', 'Temperature in °C', label_names)
humid = Gauge('tem... | 931 | 304 |
''' Tests for MSSQL. '''
from util import exec_query, MSSQL
def test_connection():
''' Test connection to MSSQL Server. '''
result = exec_query(MSSQL, "SELECT 'It works!'")
assert result == 'It works!'
| 217 | 71 |
#!/usr/bin/env python
"""SPECFIT.PY - Generic stellar abundance determination software
"""
from __future__ import print_function
__authors__ = 'David Nidever <dnidever@montana.edu>'
__version__ = '20200711' # yyyymmdd
import os
import shutil
import contextlib, io, sys
import numpy as np
import warnings
from astro... | 61,597 | 22,030 |
# author: Kevin Shahnazari
# date: 2020-11-25
"""
This script Splits the raw cleaned data to train and test splits
based on the user input and saves them into two separate csv files
Usage: clean_data.py --input_file_path=<input_file_path> --saving_path_train=<saving_path_train> --saving_path_test=<saving_path_test>... | 2,832 | 883 |
import base64
import json
import os
import tempfile
import uuid
import zipfile
from io import BytesIO
import werkzeug
from flask import Blueprint, jsonify, request
from ..config import get_config
from ..dataset import convert_ndarray_to_image, import_csv_as_mdp_dataset
from ..models.dataset import Dataset, DatasetSch... | 3,607 | 1,106 |
# SPDX-FileCopyrightText: © 2021 Open Networking Foundation <support@opennetworking.org>
# SPDX-License-Identifier: Apache-2.0
from __future__ import absolute_import
from .e2 import E2Client, Subscription
from .sdl import SDLClient
| 234 | 81 |
"""
Update release numbers in various places, according to a release.ini file places at the project root
"""
import configparser
import logging
import sys
from configparser import ConfigParser
from pathlib import Path
from typing import Optional, Tuple
import click
from bump_release import helpers
from bump_release.h... | 11,936 | 3,655 |
import numpy as np
import matplotlib.pyplot as plt
class Fresnel0(object):
def __init__(self, e):
"""
calculate the Nadir Fresnel reflectivity
e.g. Ulaby (2014), eq. 10.36
Parameters
----------
e : complex
complex relative dielectric permitivity
... | 1,748 | 623 |
import numpy as np
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import matplotlib.pyplot as plt
import contractions # Expanding contractions
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.model_selection import tr... | 6,319 | 2,110 |
from django import template
import datetime
from applications.startupconfort.models import CartItem
#https://github.com/guinslym/mywadiyabi/blob/master/applications/wadiyabi/templatetags/registration.py
register = template.Library()
@register.filter
def replace_commas(string):
return string.replace(',', '_')
... | 796 | 264 |
from csv import reader , writer
from random import randrange
#These are lists of characters that program can use to generate password
smlLetters = ["a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" ,
"k" , "l" , "m" , "n" , "o" , "p" , "q" , "r" , "s" , "t" , "u" , "v" , "w" ,
"x" , "y" , "z"]
capLetters = [... | 4,069 | 1,330 |
from prefect import task, Flow, Parameter
from prefect.tasks.prefect import StartFlowRun
from prefect.storage import GitHub
with Flow("token-test") as flow:
StartFlowRun(project_name="testing", flow_name="flow_must_fail")()
flow.storage = GitHub(repo="kvnkho/demos", path="/prefect/token_test.py")
flow.register("t... | 328 | 104 |
#!/usr/bin/env python
from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(name='spacy-thrift',
version='0.5.0',
description='spaCy-as-a-service using Thrift',
long_description=long_description,
long_description_content_type="text/markdown",
ke... | 792 | 268 |
test_cases = int(input().strip())
def sum_sub_nums(idx, value):
global result
if value == K:
result += 1
return
if value > K or idx >= N:
return
sum_sub_nums(idx + 1, value)
sum_sub_nums(idx + 1, value + nums[idx])
for t in range(1, test_cases + 1):
N, K = map(int, i... | 471 | 182 |
from data_action.transformations import *
class Data_Loader:
def __init__(self, device, batch_size, dataset, mean, std, transform_type='pmda'):
self.device = device
self.batch_size = batch_size
self.transform_type = transform_type
self.dataset = dataset
self.kwargs = {'num_w... | 1,463 | 420 |
import base64
import dots
def get_auth_token():
if dots.client_id == None or dots.api_key == None:
raise AssertionError('api_key and/or client_id not set')
token = base64.b64encode(bytes(dots.client_id + ':' + dots.api_key, 'utf-8')).decode('utf-8')
return token
| 291 | 110 |
from setuptools import setup
#bring in __version__ from sourcecode
#per https://stackoverflow.com/a/17626524
#and https://stackoverflow.com/a/2073599
with open('lineman/version.py') as ver:
exec(ver.read())
setup(name='lineman',
version=__version__,
description='Lineman fixes data problems that will ... | 946 | 320 |
import png
import pyrealsense2 as rs
import logging
logging.basicConfig(level=logging.INFO)
import numpy as np
import cv2
import os
def make_directories():
if not os.path.exists("JPEGImages/"):
os.makedirs("JPEGImages/")
if not os.path.exists("depth/"):
os.makedirs("depth/")
if not os.path.... | 2,266 | 806 |
import torch
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
hparams_file, overrides = 'train.yaml',''
PATH = './results/4234/save/CKPT+2021-04-17+16-05-06+00/model.ckpt'
# 加载超参数文件
with open(hparams_file) as fin:
hparams = load_hyperpyyaml(fin, overrides)
# 加载模型
model=hparams["model"]
model=mode... | 1,711 | 776 |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 3,737 | 1,270 |
class VposConfigurationError(Exception):
pass
| 52 | 16 |
print('\033[36m='*12, '\033[32mAlistamento Militar', '\033[36m='*12)
from datetime import date
ano = int(input('Em que ano você nasceu? '))
atual = date.today().year
idade = atual - ano
print(f'Você tem \033[32m{idade} \033[36manos em \033[32m{atual}.')
if idade == 18:
print('\033[36mTa na hora de se alistar.')
eli... | 629 | 334 |
import numpy as np
from scipy import stats
import pandas as pd
from sklearn.cross_decomposition import PLSRegression
def standardize_vector(v, center=True, scale=False):
if center:
v = v - np.mean(v)
if scale:
if np.std(v) == 0:
return v
else:
return (v + 0.0)... | 2,548 | 833 |
"""Tests for AzWebAppHttp20Event plugin."""
import copy
import unittest
from cloudmarker.events import azwebapphttp20event
base_record = {
'ext': {
'record_type': 'web_app_config',
'cloud_type': 'azure',
'http20_enabled': True
},
'com': {
'cloud_type': 'azure'
}
}... | 2,247 | 721 |
{
'includes': ['common.gypi'],
'conditions': [
['OS == "win"', {
'variables': {
'application_platform%': 'Win32',
'renderers%': ['Direct3D11', 'GL4'],
'audio%': 'XAudio2',
'input_devices%': ['DirectInput'],
},
}],
['OS == "mac"', {
'variables': {
... | 31,270 | 11,237 |
from pythonforandroid.toolchain import CythonRecipe, shprint, ensure_dir, current_directory, ArchAndroid, IncludedFilesBehaviour
import sh
from os.path import exists, join
class AndroidRecipe(IncludedFilesBehaviour, CythonRecipe):
# name = 'android'
version = None
url = None
depends = ['pygame']
... | 368 | 114 |
from flask_restful import Resource
from flask import request, Blueprint, jsonify
from models import db, Post, Comment
from datetime import datetime
commentBp = Blueprint('commentBp', __name__)
class UserComments():
@commentBp.route("/addComment", methods=['POST'])
def addComment():
json_data = re... | 2,811 | 829 |
from .cache import CacheCommand
| 32 | 8 |
import random
from aalpy.automata import Dfa, DfaState, MdpState, Mdp, MealyMachine, MealyState, \
MooreMachine, MooreState, OnfsmState, Onfsm, MarkovChain, McState
from aalpy.utils.HelperFunctions import random_string_generator
def generate_random_mealy_machine(num_states, input_alphabet, output_alphabet, compu... | 6,660 | 2,047 |
import os
import sys
import os.path as osp
from contextlib import contextmanager
############################################################
# Setup path
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
curdir = osp.dirname(__file__)
lib_path = osp.join(curdir, '..', 'lib')
add_... | 4,104 | 1,552 |
#coding:utf-8
'''
filename:exchange_keys_and_values.py
chap:4
subject:10
conditions:a dict
solution:exchanged keys and values
'''
origin_dict = {'book':['python','djang','data'],'author':'laoqi','publisher':'phei'}
def ishashable(obj):
try:
hash(obj)
return True
exce... | 618 | 214 |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import sys
from datadog_checks.dev.subprocess import run_command
class TestRunCommand:
def test_output(self):
result = run_command(
'{} -c "import sys;print(sys.version)"'.form... | 760 | 255 |
from output.models.ms_data.datatypes.facets.any_uri.any_uri_b002_xsd.any_uri_b002 import (
Bar,
Ct,
Root,
St,
)
__all__ = [
"Bar",
"Ct",
"Root",
"St",
]
| 186 | 92 |
import pytest
from wolfbot.enums import Role, SwitchPriority
from wolfbot.statements import Statement
@pytest.fixture(scope="session")
def example_statement() -> Statement:
return Statement(
"test",
((2, frozenset({Role.ROBBER})), (0, frozenset({Role.SEER}))),
((SwitchPriority.ROBBER, 2, ... | 3,476 | 1,223 |
# Generated by Django 2.2.13 on 2020-11-28 23:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ranking', '0055_auto_20201009_0735'),
]
operations = [
migrations.AddIndex(
model_name='statistics',
index=models.I... | 419 | 162 |
import logging
import warnings
from boto3.resources.base import ServiceResource
logger = logging.getLogger(__name__)
class AIOBoto3ServiceResource(ServiceResource):
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.meta.client.__aexit__... | 489 | 146 |
# Copyright (c) 2021 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... | 11,728 | 4,162 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
def between_zero_and_one_hundred(value):
if value < 0 or value > 100:
... | 399 | 130 |
from flask import Blueprint, request
import json
import databaseutils as utils
tiposrefeicao = Blueprint("tiposrefeicao", __name__)
tiposrefeicaoColumns = ["cod_tiporefeicao", "designacao"]
@tiposrefeicao.route("/api/tiposrefeicao", methods=["GET"])
@tiposrefeicao.route("/api/tiposrefeicao/", methods=["GET"])
def g... | 1,709 | 687 |
#!/usr/bin/env /usr/local/opt/python@3.9/bin/python3.9
import sys
import psycopg2
from faker import Faker
from contextlib import closing
from random import randint
import time
if __name__ == "__main__":
total = 10
batch_size = 1000
if len(sys.argv) > 1:
total = int(sys.argv[1])
if len(sys.... | 1,464 | 475 |
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import cmasher as cmr
import astropy.units as u
import astropy.coordinates as coord
from astropy.io import ascii
from astropy.io import fits
from astropy.wcs import WCS
from functions import *
plt.rcParams['mathtext.fontset'] = 'cm'
plt.rcParams[... | 2,092 | 948 |
import re
def c(text, chars=" !?"):
rx = re.compile(f'{chars}')
text = rx.sub(r'-', text)
print(text)
a = 'dsf !?#'
c(a)
| 137 | 70 |
from typing import Dict, List, Tuple
from .confidence_cm import confidence_cm
from .matrices import ConfidenceMatrix
from .performance import timeit
@timeit()
def fill_confidence_matrix(
column_count: int,
subfam_counts: Dict[str, float],
subfams: List[str],
active_cells: Dict[int, List[int]],
al... | 2,859 | 1,023 |
from flask import Blueprint, render_template
from flask_login import login_required, current_user
articles = Blueprint(
"articles",
__name__,
)
@articles.route("/intro-fgr")
@login_required
def intro():
return render_template("article-intro-fgr.html", user=current_user)
@articles.route("/causes-fgr")
@... | 1,005 | 332 |
from flask import Flask, render_template, request, redirect, url_for
import tensorflow as tf
from keras.models import load_model
from keras.backend import set_session
from src.utils import image_preprocessing
from src.utils import overall_class_label
from src.utils import infinite_scraper
# sessions and default graphs... | 6,181 | 1,921 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Group'
db.create_table(u'circles_group', (
(u'id', self.gf('django.db.models.fie... | 2,777 | 883 |
# Faça um programa que leia o comprimento do cateto oposto e a do cateto adjacente de um triângulo retângulo.
# Calcule e mostre o comprimento da hipotenusa.
from math import hypot
catoposto = float(input('Cateto oposto: '))
catadjacente = float(input('Cateto adjacente: '))
print(hypot(catoposto, catadjacente))
'''
... | 512 | 190 |
from tkinter.commondialog import Dialog
ERROR = 'error'
INFO = 'info'
QUESTION = 'question'
WARNING = 'warning'
ABORTRETRYIGNORE = 'abortretryignore'
OK = 'ok'
OKCANCEL = 'okcancel'
RETRYCANCEL = 'retrycancel'
YESNO = 'yesno'
YESNOCANCEL = 'yesnocancel'
ABORT = 'abort'
RETRY = 'retry'
IGNORE = 'ignore'
OK = 'ok'
CANCEL... | 2,837 | 964 |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def configure(app):
db.init_app(app)
app.db = db
class Tree(db.Model):
__tablename__ = 'tree'
id = db.Column(db.Integer, primary_key=True)
code = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(25... | 550 | 205 |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
from six import string_types
import xbmcgui
from ..abstract_progress_dialog import ... | 1,159 | 378 |
import os
CRAIGSLIST_SITE = 'newjersey'
CRAIGSLIST_CATEGORY = 'apa'
MIN_FT2 = 900
MIN_PRICE = 1500
MAX_PRICE = 3000
MAX_TRANSIT_DISTANCE = 0.75
BOXES = {
"Hoboken": [40.734966101, -74.0439891815, 40.7529789172, -74.0192699432],
"The Heights": [40.7332100782, -74.0573787689, 40.7615609255, -74.0378093719],
... | 1,483 | 905 |
#!/usr/bin/python
import binascii
import sys
import glob, os
import pdb
file_no=0;
file_names=[];
RGB565=1;
out_string="";
def printrgb565(red, green, blue):
x1 = (red & 0xF8) | (green >> 5);
x2 = ((green & 0x1C) << 3) | (blue >> 3);
#pdb.set_trace()
this_string="0x" + str(binascii.hexlify(chr(x2))) + ",";
this_... | 1,729 | 773 |
class Input_data():
def __init__(self):
self.s=''
def getString(self):
self.s = input()
def printString(self):
print(self.s.upper())
strobj=Input_data()
strobj.getString()
strobj.printString() | 210 | 88 |
print("To jest pierwsza linia.")
print("To jest druga linia.")
print("To jest trzecia linia.")
| 95 | 32 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] ta... | 7,340 | 2,908 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import pickle
import numpy as np
from scipy.io import wavfile
import python_speech_features as fextract
audio_filename = sys.argv[1]
features_filename = sys.argv[2]
rate, sig = wavfile.read(audio_filename)
fbank_feat = fextract.logfbank(sig,samplerate=r... | 410 | 157 |
import numpy as np
import pymc as pm
import networkx as nx
from matplotlib import pyplot as plt
alpha = 0.5
beta = 0.1
L= 9.0
G0 = nx.Graph()
for i in range(1, 10):
for j in range(i + 1, 11):
G0.add_edge(i, j)
#G0.add_path(range(1, 11))
#G0.add_path(range(1, 11))
#G0.remove_edge(2, 3)... | 2,999 | 1,224 |
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from board.feeds import EventFeed
from board.views import IndexView, ServiceView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', IndexView.as_view(), name='index'),
url(r'^services/(?P<slug>[-\w]+)$', Serv... | 452 | 150 |
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
import asyncio
from io import BytesIO
from pathlib import Path
from datetime import datetime
from tempfile import TemporaryDirectory
from textwrap import dedent
# * Third Party Impo... | 20,715 | 6,589 |
# 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, overload
from .. import... | 75,810 | 19,232 |
import requests
from bs4 import BeautifulSoup as soup
import pandas as pd
# PJ chatlog archive
url_main = 'http://perverted-justice.com/?archive=byName'
# get list of chat URLs
req_main = requests.get(url_main)
main_soup = soup(req_main.text, "html.parser")
# list to store URLs
url_link = []
for link in main_soup.fin... | 694 | 245 |
"""
This module contains the basic logging setup for the project.
"""
import datetime
import logging
import os
def setup_logging(module):
"""Set up the logging."""
log_file = os.path.join('/astro/3/mutchler/mt/logs/', module,
module + '_' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M') + '.log')... | 496 | 170 |
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import os
import base64
# from .celery_test import test
# from clone_script import clone
def index(request):
return render(request, 'clone/index.html')
def results(request):
return render(request, 'clone/results.... | 795 | 284 |
###############################################################################
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this fi... | 1,777 | 475 |
from __future__ import (
annotations,
)
import logging
import warnings
from pathlib import (
Path,
)
from typing import (
TYPE_CHECKING,
Optional,
Type,
TypeVar,
Union,
)
from .object import (
Object,
)
if TYPE_CHECKING:
from .config import (
Config,
)
logger = loggin... | 3,406 | 989 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class Partner(models.Model):
_inherit = ['res.partner']
street_name = fields.Char(
'Street Name', compute='_comp... | 6,389 | 1,730 |
from optparse import OptionParser
import yaml
import cwrap_parser
import nn_parse
import native_parse
import preprocess_declarations
import function_wrapper
import dispatch_macros
import copy_wrapper
from code_template import CodeTemplate
parser = OptionParser()
parser.add_option('-s', '--source-path', help='path t... | 10,032 | 3,467 |
from modules.abstract_module import *
class MockModule(AbstractModule):
executed = False
name = "mock_module"
description = "Module for testing purposes."
arguments = [
ModuleArgumentDescription("Arg1", "Argument 1", True),
ModuleArgumentDescription("Arg2", "Argument 2",... | 458 | 119 |
from kornia.augmentation._3d.intensity.equalize import RandomEqualize3D
from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3D
| 149 | 56 |
from logging import getLogger
from typing import Dict, List, Optional
from tmtrader.entity.order import FilledBasicOrder
from tmtrader.entity.position import ClosedPosition, Position, Positions, \
PositionsRef
from tmtrader.exchange_for_backtest.usecase.order_to_share import from_order
logger = getLogger(__name__... | 3,270 | 893 |
import grpc
from concurrent import futures
import time
import sys
sys.path.insert(0, 'service/')
from service_spec import fake_news_pb2
from service_spec import fake_news_pb2_grpc
import json
import test
class fake_news_classificationServicer(fake_news_pb2_grpc.fake_news_classificationServicer):
def classify... | 850 | 299 |
from io import BytesIO
from PIL import Image
from django.contrib.auth.models import AbstractUser
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.mail import send_mail
from django.db import models
from resizeimage import resizeimage
from rest_framework.authtoken.models import Token
from ... | 3,807 | 1,195 |
#table join
#stefan safranek
import csv, os, sys, time
import pandas as pd
start_time = time.time() #start time
#File 1
IMPORT_FILE = "Burns_wO_LnLID.csv"
SAVE_FILE = IMPORT_FILE.replace('.csv','') + " MATCHED.csv"
df1 = pd.read_csv("Burns HD 58.csv", index_col=None, usecols=[0,1,2,4], parse_dates=True... | 646 | 305 |
import csv
from itertools import islice
import os
from glob import glob
import time
def demmeta(folder,mfile,errorlog):
metasource = [y for x in os.walk(folder) for y in glob(os.path.join(x[0], '*.txt'))]
with open(mfile,'wb') as csvfile:
writer=csv.DictWriter(csvfile,fieldnames=["id_no", "system:time_s... | 3,637 | 1,179 |
from django.urls import path
from . import views
app_name = 'bertpredict'
urlpatterns = [
path('bertpredict/', views.BertPredictView.as_view()),
] | 152 | 51 |
#!/usr/bin/env python3
# ROS packages required
import rospy
from eager_core.eager_env import BaseEagerEnv
from eager_core.objects import Object
from eager_core.wrappers.flatten import Flatten
from eager_bridge_webots.webots_engine import WebotsEngine # noqa: F401
from eager_bridge_pybullet.pybullet_engine import PyBu... | 3,493 | 1,170 |
# Configuration file for RefTest_t
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("FWCore.Framework.test.cmsExceptionsFatal_cff")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(2)
)
process.source = cms.Source("EmptySource")
process.WhatsItESProduce... | 11,190 | 4,019 |
from django.urls import path
from . import views
app_name = "keycards"
urlpatterns = [
path(f"", views.KeycardLoginFormView.as_view(), name="login"),
]
| 158 | 55 |
from drias2020.extract_drias2020 import extract_drias2020
from drias2020.convert_drias2020 import convert_drias2020
alls_models = [
('CNRM-CM5-LR', 'ALADIN63', 'historical'),
('CNRM-CM5-LR', 'ALADIN63', 'rcp2.6'),
('CNRM-CM5-LR', 'ALADIN63', 'rcp4.5'),
('CNRM-CM5-LR', 'ALADIN63', 'rcp8.5'),
('CNRM-... | 2,859 | 1,613 |
# Rewritten by @keinshin
import io
from userbot import CMD_LIST, ALIVE_NAME, bot as light
from userbot import CMD_HELP
from userbot.utils import lightning_cmd
import asyncio
from var import Var
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "Pls Go To Heroku Vars Then in `ALIVE_NAME`place You Telegram `Your Desire... | 2,118 | 699 |
import torch
import torch.nn as nn
from torchvision import models
import torch.nn.functional as F
def model_parser(model, sum_mode=False, dropout_rate=0.0, bayesian=False):
base_model = None
if model == 'Resnet':
base_model = models.resnet34(pretrained=True)
network = HourglassNet(base_model, ... | 4,593 | 1,805 |
r"""
Class to the python faces
"""
from typing import List, Tuple
import xml.etree.ElementTree as ET
import torch
import torch.utils.data as data
import cv2
import numpy as np
from PIL import Image
from torchvision.transforms import functional as F
class FacesDB(data.Dataset):
"""VOC Detection Dataset Object
... | 5,414 | 1,647 |
from typing import Any, Dict, List
from .utils import get_json
def fetch_markets(market_type: str) -> List[Dict[str, Any]]:
'''Fetch all trading markets from a crypto exchage.'''
if market_type == 'future':
return _fetch_future_markets()
elif market_type == 'option':
return _fetch_option_... | 1,473 | 528 |
from twisted.internet import defer, reactor
from twisted.protocols import basic
from twisted.internet.protocol import Protocol, ReconnectingClientFactory
from time import sleep
# local
import screen
import stevent
class NetMgr:
"""
new abstraction:
1) this module receives the latest screen from the server.
2)... | 3,218 | 1,182 |
"""MongoDB IO tasks."""
import logging
from typing import List, Optional, Sequence
from urllib.parse import urlparse
import attr
from icecream import ic # noqa pylint: disable=unused-import
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError
import voluptuous as vol
from dataplaybo... | 6,336 | 2,113 |
'''8. Faça um programa que receba o valor de um depósito e o valor da taxa de juros, calcule e
mostre o valor do rendimento e o valor total depois do rendimento de um mês.'''
#entrada
deposito = float(input('valor de deposito: '))
juros = float(input("Taxa de juros: "))
#processamento
rendimento = deposito * juros / ... | 422 | 144 |
import os
import unittest
from golly_maps.patterns import (
get_patterns,
get_pattern,
get_pattern_size,
get_grid_pattern,
pattern_union,
)
HERE = os.path.split(os.path.abspath(__file__))[0]
ALL_PATTERNS = [
"78p70",
"acorn",
"airforce",
"backrake2",
"bheptomino",
"block",... | 7,639 | 2,388 |
class Solution:
def minSessions(self, tasks: List[int], sessionTime: int) -> int:
n = len(tasks)
initial_state = int('0b'+'1'*n,2)
dp = {}
def find_dp(state):
if state in dp:
return dp[state]
if state == 0:
dp[state] = (1, 0)
... | 929 | 305 |
import argparse
import json
import numpy as np
import typing
from blockfs.directory import Directory
import logging
from precomputed_tif.blockfs_stack import BlockfsStack
from precomputed_tif.ngff_stack import NGFFStack
import os
import sys
from spimstitch.ngff import NGFFDirectory
from ..stitch import get_output_siz... | 8,350 | 2,693 |
#AGNET
# 該当のチャンネルのID
ID_CHANNEL_README = 771383900814573598
#たすきる
ID_ROLE_TSKL = 671354476044615680
#たすきる用ちゃんねるID(とつかんり)
ID_TSKILL = 624668843444273164
#とつ予定(とつかんり)
ID_totu = 739498595329376487
#とつ予定じゃり
ID_totu2 = 750321508219355227
#さーばーID
ID_SRV = 539773033724772362
#agnet
ID_agnet = 549971775828656168
ID_alist =... | 442 | 381 |
from haystack import indexes
from issues.models import Issue, Proposal
from haystack.fields import IntegerField, CharField, BooleanField, DateField, DateTimeField
from datetime import date, datetime, timedelta
class IssueIndex(indexes.ModelSearchIndex, indexes.Indexable):
community = IntegerField(model_attr='comm... | 1,821 | 530 |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import argparse
from typing import Optional
from data.sampler import arguments_sampler
from data.collate_fns import arguments_collate_fn
from options.utils import load_config_file
from data.datasets import argument... | 16,437 | 4,650 |
"""
Given a binary tree, find the root-to-leaf path with the maximum sum.
"""
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_paths(root):
res = []
cur_path = []
find_max(root, res, cur_path, 0)
return res
max_sum = ... | 1,012 | 412 |
# coding=utf-8
from django.shortcuts import render
from rest_framework import viewsets, generics, status
from .serializers import ClientSerializer, MessageSerializer, SearchSerializer, ManageSearchSerializer, PreferenceSerializer
from .models import Client, Message, Search, ManageSearch, Preference
from rest_framework... | 9,867 | 2,744 |