text string | size int64 | token_count int64 |
|---|---|---|
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 3,591 | 982 |
#!/usr/bin/env python
"""
Copyright (c) 2018 Robert Bosch GmbH
All rights reserved.
This source code is licensed under the BSD-3-Clause license found in the
LICENSE file in the root directory of this source tree.
@author: Jan Behrens
"""
from geometry_msgs.msg import TransformStamped
from roadmap_planner_tools.plann... | 5,631 | 3,036 |
# coding=utf-8
"""Print unique rows in table.
Trie data structure Python solution.
"""
from Trie import Trie
def print_unique(table):
t = Trie()
for row in table:
if not t.in_tree(row):
print(row)
t.add_key(row)
if __name__ == "__main__":
table = [
"semir",
... | 415 | 149 |
#!/usr/bin/env python
# Standard python libs
import os,sys
sys.path.append("./src/genpy")
import ast, pprint
import pdb
import yaml, json
import telemetry_pb2
from mdt_grpc_dialin import mdt_grpc_dialin_pb2
from mdt_grpc_dialin import mdt_grpc_dialin_pb2_grpc
import json_format
import grpc
#
# Get the GRPC Server ... | 2,179 | 771 |
'''
This code is a simple example how to define custom exception class in Python
'''
# custom exception class
class CustomError(Exception):
def __init__(self,message):
self.message = message
super().__init__(self.message)
# use it whenever you need in your code as follows:
try:
...
... | 436 | 124 |
#!/usr/bin/env python3
from pathlib import Path
slope = 3, 1
class Map:
def __init__(self, rows):
self.w = len(rows[0])
self.rows = rows
def tree(self, x, y):
return '#' == self.rows[y][x % self.w]
def main():
m = Map(Path('input', '3').read_text().splitlines())
xy = [0, 0]... | 545 | 204 |
import numpy as np
import csv
import matplotlib.pyplot as pyplot
from gBarGraph import *
# Conditional Debugging
debug = False
# Inputs
scaleFac = 10**6 # scaling factor
adList = [[128,128], [64,64], [32,32], [16,16], [8,8]] #list of systolic array dimensions
dfList = ["os", "ws", "is"]
nnList = ["AlphaGoZero", "De... | 2,092 | 905 |
from functools import wraps
DEFAULT_CODE = -1
class APIError(ValueError):
pass
def normalize_network_error(func):
from requests import exceptions as exc
@wraps(func)
def decorated(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc.RequestException as e:
... | 374 | 113 |
import re
def find_key(keyString):
k = PyKeyboard()
key_to_press = None
highest = 0
for each in dir(k):
if each.endswith("_key"):
if similar(keyString + "_key" ,each) > highest:
highest = similar(keyString + "_key" ,each)
key_to_press = getattr(k,each)... | 2,446 | 791 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import json
import csv
import time
from datetime import date
import requests
class CrawlerController(object):
'''Split targets into several Crawler, avoid request url too long'''
def __init__(self, targets, max_stock_per_crawler=50):
... | 3,095 | 1,086 |
import datetime
from fp17 import treatments
def annotate(bcds1):
bcds1.patient.surname = "BEDWORTH"
bcds1.patient.forename = "TOBY"
bcds1.patient.address = ["5 HIGH STREET"]
bcds1.patient.sex = 'M'
bcds1.patient.date_of_birth = datetime.date(1938, 4, 11)
bcds1.date_of_acceptance = datetime.d... | 694 | 324 |
"""
The MIT License (MIT)
Copyright (c) 2021 Cong Vo
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... | 1,643 | 601 |
#!/usr/bin/python3
# File: fizz_buzz.py
# Author: Jonathan Belden
# Description: Fizz-Buzz Coding Challenge
# Reference: https://edabit.com/challenge/WXqH9qvvGkmx4dMvp
def evaluate(inputValue):
result = None
if inputValue % 3 == 0 and inputValue % 5 == 0:
result = "FizzBuzz"
elif inputValue % 3 ... | 465 | 174 |
# Exercícios Numpy-27
# *******************
import numpy as np
Z=np.arange((10),dtype=int)
print(Z**Z)
print(Z)
print(2<<Z>>2)
print()
print(Z <- Z)
print()
print(1j*Z)
print()
print(Z/1/1)
print()
#print(Z<Z>Z) | 213 | 106 |
import copy
from .coco import CocoDataset
def build_dataset(cfg, mode):
dataset_cfg = copy.deepcopy(cfg)
if dataset_cfg['name'] == 'coco':
dataset_cfg.pop('name')
return CocoDataset(mode=mode, **dataset_cfg)
| 234 | 80 |
#!/bin/python
"""
straintables' main pipeline script;
"""
import os
import argparse
import shutil
import straintables
import subprocess
from Bio.Align.Applications import ClustalOmegaCommandline
from straintables.logo import logo
from straintables.Executable import primerFinder, detectMutations,\
compareHea... | 5,387 | 1,582 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... | 1,881 | 515 |
# -*- coding: utf-8 -*-
# coding=utf-8
import json
import random
import requests
import argparse
import time
# 请求内容转json
def getval():
values = {"province": "北京", "city": "北京市", "addressType": "整租房", "temperature": "36.7", "dayNum": "", "contactHbPerplr": "无接触", "toWh": "未去过/路过武汉", "familySymptom": "无症状", "rem... | 1,634 | 688 |
# -*- coding: utf-8 -*-
# @Time : 2019-08-02 18:31
# @Author : Wen Liu
# @Email : liuwen@shanghaitech.edu.cn
import os
import cv2
import glob
import shutil
from multiprocessing import Pool
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from tqdm import tqdm
import numpy as np
im... | 7,848 | 3,117 |
"""
Podcats is a podcast feed generator and a server.
It generates RSS feeds for podcast episodes from local audio files and,
optionally, exposes the feed and as well as the episode file via
a built-in web server so that they can be imported into iTunes
or another podcast client.
"""
import os
import re
import time
i... | 10,346 | 3,140 |
class Solution:
"""
@param A:
@return: nothing
"""
def numFactoredBinaryTrees(self, A):
A.sort()
MOD = 10 ** 9 + 7
dp = {}
for j in range(len(A)):
dp[A[j]] = 1
for i in range(j):
if A[j] % A[i] == 0:
num = A... | 477 | 182 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
from statsmodels.tsa.arima_model import ARMA
from scipy.stats.distributions import chi2
import statsmodels.tsa.stattools as sts
# ------------------------
# load data
# ----------
raw_csv_data = pd.rea... | 3,254 | 1,254 |
# Copyright (c) 2021 Valerii Sukhorukov. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | 2,861 | 926 |
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from snownlp import SnowNLP
# Create your views here.
@csrf_exempt
def index(request):
message = {}
print request.method
if request.method == 'GET':
message = construct_message... | 948 | 335 |
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# 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.
# THIS SOFTWARE IS PROVIDED "AS I... | 10,677 | 2,984 |
# doxygen.py
#
# Doxygen Management
from utils import *
import glob
##############################################################################
# Doxygen Management #
##############################################################################
"""
Called ... | 7,559 | 2,112 |
#!/usr/bin/env python
# Standard imports
import pandas as pd
import numpy as np
# Pytorch
import torch
from torch import nn
# Using sklearn's LASSO implementation
from sklearn.linear_model import Lasso
# Local Files
from models.model_interface import CryptoModel
class LASSO(CryptoModel):
"""Wrapper around the ... | 3,074 | 945 |
from Beat_Detector import BeatDetector
from SignalChoice import *
update_time_seconds = 20
update_time_easy = 2 # means enough data for 2 seconds.
array_easy = [0, 2, 5, 10, 5, 2, 0, 2, 5, 10, 5]
def test_get_num_beats():
beat_detector = BeatDetector(update_time_seconds, SignalChoice.both)
assert 2 == beat_... | 719 | 289 |
#!/usr/bin/env python
# encoding: utf-8
import urllib, urllib2
import tempfile
import base64
from PIL import Image
import os
# 全局变量
API_URL = 'http://apis.baidu.com/apistore/idlocr/ocr'
API_KEY = "0c69d1b8ec1c96561cb9ca3c037d7225"
def get_image_text(img_url=None):
headers = {}
# download image
opener = u... | 1,806 | 728 |
import torch
class AttentionBasedImportance:
def __init__(self, inputs, tokenizer, attentions):
if type(inputs["input_ids"]) == torch.Tensor:
if inputs["input_ids"].device != torch.device(type='cpu'):
self.input_ids = inputs["input_ids"].cpu()
else:
... | 2,381 | 736 |
# vi: set shiftwidth=4 tabstop=4 expandtab:
import datetime
import itertools
import collections
RUN_LONG_TESTS = False
def string_to_seat_layout(string):
return {
(i, j): s
for i, line in enumerate(string.splitlines())
for j, s in enumerate(line)
}
def seat_layout_to_string(seats):
... | 3,704 | 1,488 |
from django import forms
from apps.app_gestor_usuarios.models import db_usuarios, db_manage_contacts
class signupForm(forms.ModelForm):
class Meta:
model = db_usuarios
fields = [
'name',
'last',
'email',
'password',
]
labels = {
... | 3,356 | 973 |
from spanserver import (
SpanRoute,
Request,
Response,
MimeType,
RecordType,
DocInfo,
DocRespInfo,
)
from isleservice_objects import models, errors, schemas
from service.api import api
class SchemaCache:
ENEMY_FULL = schemas.EnemySchema()
ENEMY_POST = schemas.EnemySchema(exclude=[... | 1,613 | 535 |
from .item import Item
from .entry import Entry
from copy import copy
class Record(object):
"""
A Record, the tuple of an entry and it's item
Records are useful for representing the latest entry for a
field value.
Records are serialised as the merged entry and item
"""
def __init__(self,... | 948 | 251 |
"""
pyexcel_matplotlib
~~~~~~~~~~~~~~~~~~~
chart drawing plugin for pyexcel
:copyright: (c) 2016-2017 by Onni Software Ltd.
:license: New BSD License, see LICENSE for further details
"""
from pyexcel.plugins import PyexcelPluginChain
PyexcelPluginChain(__name__).add_a_renderer(
relative_plug... | 385 | 132 |
#py.test --cov-report=term --cov=. --cov-config=coverage.rc --cov-fail-under=100
from impl import PhysicalInfo
import pytest
import hypothesis.strategies as st
from hypothesis import given, assume
| 199 | 63 |
from django.http import Http404, JsonResponse
from django.shortcuts import render
from chatbot.chatbot import create_chatbot
import threading
import pickle
import collections
from io import BytesIO
import numpy as np
import urllib.request
import json
import wave
import librosa
import pandas as pd
from homepage.models i... | 7,025 | 2,469 |
"""
Django settings for petstore project.
Generated by 'django-admin startproject' using Django 2.2.10.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
... | 5,749 | 2,055 |
from tool.runners.python import SubmissionPy
class JonSubmission(SubmissionPy):
def run(self, s):
l = [int(x) for x in s.strip().split()]
n = len(l)
for i in range(n):
for j in range(i):
if l[i] + l[j] > 2020:
continue
for k... | 440 | 158 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# From /opt/recon-ng/recon/mixins/threads.py
from Queue import Queue, Empty
import threading
import time
import logging
logging.basicConfig(level=logging.INFO, format="[+] %(message)s")
logger = logging.getLogger("mutilthreads")
class ThreadingMixin(object):
def _... | 1,919 | 596 |
from BusquedasSem import *
import seaborn as sns
def main():
df = pd.read_csv('./client0-sort.csv')
df_abstract = df['Abstract']
l = df_abstract.size
abstracts = df_abstract.values
PCA_score = np.zeros((l, l))
abstracts_aux = preprocessing_abstracts_PCA(abstracts)
for i in range(l):
... | 2,184 | 786 |
import os
import sys
import time
import hashlib
target_hash = input("Input a target hash: ")
numbers = '1234567890'
uptext = 'qwertyuiopasdfghjklzxcvbnm'
lotext = 'QWERTYUIOPASDFGHJKLZXCVBNM'
steach = uptext + lotext
lash_ash = open('log', 'w')
found_hash = open('saved', 'w')
def animate():
print(f"[{gen_text_has... | 864 | 378 |
import pandas as pd
from sklearn.metrics import classification_report, confusion_matrix
from argparse import ArgumentParser
from read_data import read_csv
def create_toxic_result(path, expected, out, toxic_category, test=False):
if not test:
df_true = read_csv(expected, names=['comment_id', 'toxic', 'enga... | 11,100 | 3,720 |
def multiplo(a, b):
if a % b == 0:
return True
else:
return False
print(multiplo(2, 1))
print(multiplo(9, 5))
print(multiplo(81, 9))
| 157 | 66 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import parsifal.apps.reviews.models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('library', '0013_auto_20150710_1614'),
('reviews', '0019_study_co... | 1,165 | 374 |
#!/usr/bin/env python
"""
Copyright 2012-2013 The MASTIFF Project, All Rights Reserved.
This software, having been partly or wholly developed and/or
sponsored by KoreLogic, Inc., is hereby released under the terms
and conditions set forth in the project's "README.LICENSE" file.
For a list of all contributors... | 6,518 | 1,952 |
import torch.nn as nn
from torchvision.models import resnet
class SceneRecognitionCNN(nn.Module):
"""
Generate Model Architecture
"""
def __init__(self, arch, scene_classes=1055):
super(SceneRecognitionCNN, self).__init__()
# --------------------------------#
# Base ... | 2,874 | 876 |
from time import sleep
class AWSEC2(object):
def __init__(self, target):
self.conn = target.get_ec2_conn()
def get_instance_state(self, instance_id):
instance = self.conn.get_only_instances(instance_id)[0]
return instance.state
def stop_instance(self, instance_id):
self.co... | 1,309 | 408 |
import rv.api
class Command(object):
args = ()
processed = False
def __init__(self, *args, **kw):
self._apply_args(*args, **kw)
def __repr__(self):
attrs = ' '.join(
'{}={!r}'.format(
arg,
getattr(self, arg),
)
for ... | 3,786 | 1,144 |
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from scipy.spatial.distance import squareform, pdist
from rfcc.data_ops import ordinal_encode
import pandas as pd
import numpy as np
from typing import Union, Optional
from scipy.cluster.hierarchy import linkage, fcluster
from rfcc.path_o... | 22,527 | 6,481 |
from pathlib import Path
from typing import Any, Generator, Optional, Tuple
from cv2 import CAP_PROP_BUFFERSIZE, VideoCapture
from numpy import ndarray
from zoloto.marker_type import MarkerType
from .base import BaseCamera
from .mixins import IterableCameraMixin, VideoCaptureMixin, ViewableCameraMixin
from .utils im... | 4,632 | 1,391 |
import vim
from datetime import datetime
from os import path
from subprocess import run, DEVNULL
def include_screenshot():
directory = path.dirname(vim.current.buffer.name)
timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
filename = f"screenshot-{timestamp}.png"
with open(path.join(directory, f... | 448 | 145 |
from cement.ext.ext_plugin import CementPluginHandler
# module tests
class TestCementPluginHandler(object):
def test_subclassing(self):
class MyPluginHandler(CementPluginHandler):
class Meta:
label = 'my_plugin_handler'
h = MyPluginHandler()
assert h._meta.in... | 433 | 120 |
"""
Represents an ideal lens.
"""
from syned.beamline.optical_elements.ideal_elements.screen import Screen
from wofry.beamline.decorators import OpticalElementDecorator
class WOScreen(Screen, OpticalElementDecorator):
def __init__(self, name="Undefined"):
Screen.__init__(self, name=name)
def applyOpti... | 655 | 200 |
import os
from tqdm import tqdm
from pathlib import Path
import random
from mycv.paths import IMAGENET_DIR
from mycv.datasets.imagenet import WNIDS, WNID_TO_IDX
def main():
sample(200, 600, 50)
def sample(num_cls=200, num_train=600, num_val=50):
assert IMAGENET_DIR.is_dir()
train_root = IMAGENET_DIR /... | 1,799 | 644 |
# test utilities
import unittest
from decimal import Decimal
# tested module
import madseq
class Test_Document(unittest.TestCase):
def test_parse_line(self):
parse = madseq.Document.parse_line
Element = madseq.Element
self.assertEqual(list(parse(' \t ')),
['']... | 702 | 221 |
from abc import ABC, abstractmethod, ABCMeta
class Visitor(ABC):
@abstractmethod
def visitProgram(self, ast, param):
pass
@abstractmethod
def visitVarDecl(self, ast, param):
pass
@abstractmethod
def visitConstDecl(self, ast, param):
pass
@abstractmethod
def visi... | 5,307 | 1,529 |
from prefixdate import parse_parts
from opensanctions import helpers as h
from opensanctions.util import remove_namespace
def parse_address(context, el):
country = el.get("countryDescription")
if country == "UNKNOWN":
country = None
# context.log.info("Addrr", el=el)
return h.make_address(
... | 4,917 | 1,441 |
# -*- coding: utf-8 -*-
"""
处理各种语言的库,主要是实现分段落、句子、词的功能
"""
from __future__ import unicode_literals
from .nlp_zh import NlpZh
class Nlp(object):
def __init__(self, config):
self.config = config
if self.config.language == 'zh':
self.nlp = NlpZh(config)
else:
raise Va... | 1,031 | 470 |
# coding: utf-8
import matplotlib.pyplot as plt
from scr_class_stats import init_rain, cl_frac_in_case, frac_in_case_hist
def proc_frac(cases, lcl, frac=True):
"""fraction or sum of process occurrences per case"""
cl_sum = cases.case.apply(lambda x: 0)
for cl in lcl:
cl_sum += cases.case.apply(la... | 730 | 307 |
"""
Since the size of real robot data is huge, we first go though all data then save loss array,
then sort loss array. Finally we use the indexes to find the corresponding graphs
"""
import time
from rllab.core.serializable import Serializable
from numpy.linalg import norm
from numpy import mean
from numpy import std
i... | 3,784 | 1,569 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Wei Wu
@license: Apache Licence
@file: prepare_training_data.py
@time: 2019/12/19
@contact: wu.wei@pku.edu.cn
将conll的v4_gold_conll文件格式转成模型训练所需的jsonlines数据格式
"""
import argparse
import json
import logging
import os
import re
import sys
from collections import d... | 12,225 | 3,938 |
"""
Utilities for making plots
"""
from warnings import warn
import matplotlib.pyplot as plt
from matplotlib.projections import register_projection
from matplotlib.animation import ArtistAnimation
from .parse import Delay, Pulse, PulseSeq
def subplots(*args, **kwargs):
"""
Wrapper around matplotlib.pyplot.s... | 8,611 | 2,760 |
from genlisp.immutables import _ImmutableMap as ImmutableMap
import random
test_dicts = [{1: 2},
{1: 3},
{1: 2, 3: 4},
dict(a=1, b=2, c=3, d=4, e=5),
dict(a=3, b=1, c=3, d=4, e=5),
{ii: random.randint(0, 10000) for ii in range(20000)},
... | 1,835 | 702 |
class Quadrado:
def __init__(self, lado):
self.tamanho_lado = lado
def mudar_valor_lado(self, novo_lado):
lado = novo_lado
self.tamanho_lado = novo_lado
def retornar_valor_lado(self, retorno):
self.tamanho_lado = retorno
print(retorno)
def calcular_area(self, a... | 740 | 285 |
# Generated with FileFormatCode
#
from enum import Enum
from enum import auto
class FileFormatCode(Enum):
""""""
BINARY_OUTPUT_ONLY = auto()
ASCII_OUTPUT_ONLY = auto()
NO_ADDITIONAL_OUTPUT = auto()
ASCII_OUTPUT = auto()
BINARY_OUTPUT = auto()
def label(self):
if self == FileFormat... | 772 | 250 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import itertools
import logging
from asyncio import CancelledError
from wolframclient.evaluation.base import WolframAsyncEvaluator
from wolframclient.evaluation.kernel.asyncsession import (
WolframLanguageAsyncSessio... | 13,075 | 3,360 |
import os.path as osp
import subprocess
dna_datasets = [
"CTCF",
"EP300",
"JUND",
"RAD21",
"SIN3A",
"Pbde",
"EP300_47848",
"KAT2B",
"TP53",
"ZZZ3",
"Mcf7",
"Hek29",
"NR2C2",
"ZBTB33",
]
prot_datasets = [
"1.1",
"1.34",
"2.1",
"2.19",
"2.31",
... | 1,237 | 557 |
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class CartPage:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def del_from_cart_butto... | 1,911 | 596 |
from ._utils import _tag_class
from ._utils._paths import PATH_ENTITIES, S3_PATH_ENTITIES
def available_deep_model():
"""
List available deep learning entities models, ['concat', 'bahdanau', 'luong']
"""
return ['concat', 'bahdanau', 'luong']
def available_bert_model():
"""
List available be... | 2,945 | 845 |
from django.test import TestCase
from core.tests.factories import SaleFactory, InvoiceFactory
from invoices.models import Invoice
class InvoiceModelTestCase(TestCase):
def test_sales_pending_without_invoice(self):
""" Should return this sale if not have Invoice to cover"""
sale = SaleFactory(tota... | 1,451 | 492 |
valores = []
quant = int(input())
for c in range(0, quant):
x, y = input().split(' ')
x = int(x)
y = int(y)
maior = menor = soma = 0
if x > y:
maior = x
menor = y
else:
maior = y
menor = x
if maior == menor+1 or maior == menor:
valores.append(0)
e... | 523 | 183 |
# Regional volume and density management
# Author: David Young, 2018, 2019
"""Measure volumes and densities by regions.
Intended to be higher-level, relatively atlas-agnostic measurements.
"""
from enum import Enum
from time import time
import numpy as np
import pandas as pd
from scipy.spatial.distance import cdist
... | 53,932 | 15,639 |
import time,pyb
uart = pyb. UART(3,9600, bits=8, parity=None, stop=1)
while(True):
time.sleep_ms(100)
size = uart.any()
if (size > 0):
string = uart.read(size)
data = int(string[-1])
print('Data: %3d' % (data))
| 251 | 111 |
# Adds session chairs to the existing (static) program.html file.
# Source: https://docs.google.com/spreadsheets/d/1aoUGr44xmU6bnJ_S61WTJkwarOcKzI_u1BgK4H99Yt4/edit?usp=sharing
# Please download and save the spreadsheet in CSV format.
PATH_TO_CSV = "/tmp/sessions.csv"
#PATH_TO_HTML = "../conference-program/main/progra... | 2,089 | 764 |
from faker import Faker
import random
import parameters
from utils import chance_choose, chance
from uri_generator import gen_path, uri_extensions, gen_uri_useable
# TODO: Continue to expand this list with the proper formats for other application
# layer protocols (e.g. FTP, SSH, SMTP...)
protocols = ['HTTP/1.0', 'H... | 2,084 | 651 |
from pathlib import PosixPath, Path
from typing import Optional
import nbformat as nbf
from ktx_parser.abs_format import AbsFormat
from ktx_parser.abs_getter import AbsGetter
from ktx_parser.decorations import keys_to_decorations
class FormatJupyter(AbsFormat):
def __init__(self, getter: AbsGetter):
sel... | 2,570 | 820 |
def binary_search(collection, lhs, rhs, value):
if rhs > lhs:
mid = lhs + (rhs - lhs) // 2
if collection[mid] == value:
return mid
if collection[mid] > value:
return binary_search(collection, lhs, mid-1, value)
return binary_search(collection, mid+1, rhs, v... | 787 | 329 |
#! /usr/bin/env python
from datetime import datetime, timedelta
from threading import Thread
import logging
import os
from time import sleep
logging.basicConfig(level = logging.DEBUG)
"""# define various handy options
usage = "usage: %prog [options] [+]hours:minutes"
parser = OptionParser(usage=usage)
parser.add_op... | 4,831 | 1,512 |
"""
Check that the output from irrational functions is accurate for
high-precision input, from 5 to 200 digits. The reference values were
verified with Mathematica.
"""
import time
from mpmath import *
precs = [5, 15, 28, 35, 57, 80, 100, 150, 200]
# sqrt(3) + pi/2
a = \
"3.302847134363773912758768033145623809041389... | 10,442 | 8,036 |
"""Commandline interface."""
# TODO: After scripting works.
| 61 | 18 |
#!/usr/bin/env python
from __future__ import print_function
import uproot
import argparse
from prettytable import PrettyTable
from collections import defaultdict
parser = argparse.ArgumentParser(description="Shows Indices table in a DQMIO file. Last column (ME count) is computed like this: lastIndex - firstIndex + 1... | 1,396 | 487 |
#Exercício Python 9: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.
n = int(input("Digite um número: "))
i = 0
print("--------------")
while i < 10:
i += 1
print("{:2} x {:2} = {:2}".format(n, i, n*i))
print("--------------") | 272 | 107 |
print
print('This is Naveen')
:q
| 52 | 35 |
"""Test evaluation functionality."""
from moda.evaluators import f_beta
from moda.evaluators.metrics import calculate_metrics_with_shift, _join_metrics
def test_f_beta1():
precision = 0.6
recall = 1.0
beta = 1
f = f_beta(precision, recall, beta)
assert (f > 0.74) and (f < 0.76)
def test_f_beta3(... | 4,988 | 2,197 |
from contextlib import contextmanager
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from .config_server import SERVER_DATABASE
engine = create_engine(SERVER_DATABASE)
Base = declarative_base(metadat... | 9,070 | 2,937 |
from queue import Queue
from threading import Thread
from glouton.commands.download.downloadCommandParams import DownloadCommandParams
from glouton.commands.download.archiveDownloadCommand import ArchiveDownloadCommand
from glouton.commands.module.endModuleCommand import EndModuleCommand
from glouton.commands.module.en... | 3,064 | 805 |
# Generated by Django 2.2.6 on 2019-10-25 19:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('file_deletion', '0004_maxlength_etag'),
]
operations = [
migrations.AlterField(
model_name='deletedfile',
name='file... | 418 | 145 |
click(Pattern("Bameumbrace.png").similar(0.80))
sleep(1)
click("3abnb.png")
exit(0)
| 84 | 39 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 The Procyon 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
#
# Un... | 1,459 | 474 |
from django.db import models,transaction
from contact.models import Customer
from product.models import Stock
from django.urls import reverse
from django.db.models import Sum
# Create your models here.
class Approval(models.Model):
created_at = models.DateTimeField(auto_now_add = True,
editable = F... | 5,053 | 1,504 |
from pdf2image import convert_from_path, convert_from_bytes
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
images = convert_from_path('.\git_cheat_sheet.pdf')
| 221 | 70 |
from googleapiclient.discovery import build
from uuid import uuid4
from google.auth.transport.requests import Request
from pathlib import Path
from google_auth_oauthlib.flow import InstalledAppFlow
from typing import Dict, List
from pickle import load, dump
class CreateMeet:
def __init__(self, attendees: Dict[str,... | 3,097 | 890 |
class Rover:
def __init__(self,photo,name,date):
self.photo = photo
self.name = name
self.date = date
class Articles:
def __init__(self,author,title,description,url,poster,time):
self.author = author
self.title = title
self.description = description
... | 392 | 112 |
from django.urls import path
from . import views
urlpatterns = [
path('panel/', views.panel, name='panel-noslug'),
path('panel/<slug:conslug>/', views.panel, name='panel'),
path('panelreview/',
views.PendingPanelList.as_view(), name='pending-panel-list-noslug'),
path('panelreview/<slug:conslug... | 782 | 262 |
import librosa
import numpy as np
import audio
from hparams import hparams
"""
This helps implement a user interface for a vocoder.
Currently this is Griffin-Lim but can be extended to different vocoders.
Required elements for the vocoder UI are:
self.sample_rate
self.source_action
self.vocode_action
"""
class Voice... | 1,538 | 478 |
from django.conf import settings
from django import template
from spreedly.functions import subscription_url
register = template.Library()
@register.simple_tag
def existing_plan_url(user):
return 'https://spreedly.com/%(site_name)s/subscriber_accounts/%(user_token)s' % {
'site_name': settings.SPREEDLY_SI... | 472 | 149 |
# -*- coding: utf-8 -*-
import pytest
from src.replace_lcsh import replace_term, lcsh_fields, normalize_subfields
# def test_flip_impacted_fields(fake_bib):
# pass
@pytest.mark.parametrize(
"arg,expectation",
[
(1, ["a", "local term", "x", "subX1", "x", "subX2", "z", "subZ."]),
(3, ["a... | 981 | 404 |
__author__ = ("Matthias Rost <mrost AT inet.tu-berlin.de>, "
"Alexander Elvers <aelvers AT inet.tu-berlin.de>")
__all__ = ["Data"]
from collections import OrderedDict
from typing import Dict, List, Optional
from . import tutor
from . import rooms
from ..util import converter
from ..util.settings import... | 6,178 | 1,851 |
from just_bin_it.exceptions import KafkaException
class SpyProducer:
def __init__(self, brokers=None):
self.messages = []
def publish_message(self, topic, message):
self.messages.append((topic, message))
class StubProducerThatThrows:
def publish_message(self, topic, message):
ra... | 359 | 108 |