text string | size int64 | token_count int64 |
|---|---|---|
'''
Spider IPCA v.1
---------------
Captura variação do IPCA do site do IBGE
Para o Blog Ciência de Dados
Thiago Serra F. Carvalho (C073835)
'''
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import time
class Captura:
'''
PASSO 1: Abrir o navegador
O objeto webdriver é o... | 4,808 | 1,482 |
from __future__ import division
from __future__ import print_function
from .unittest_tools import unittest
import numpy as np
from quantlib.settings import Settings
from quantlib.instruments.option import (
EuropeanExercise)
from quantlib.instruments.payoffs import PAYOFF_TO_STR
from quantlib.models.shortrate... | 13,358 | 4,632 |
__all__ = [
"manual_segmentation",
"correct_watershed",
"correct_decreasing_cell_frames",
]
import warnings
import numpy as np
import xarray as xr
from .array_utils import axis2int
from .segmentation import (
napari_points_to_peak_mask,
peak_mask_to_napari_points,
watershed_single_frame_presee... | 13,470 | 4,345 |
from napari_plugin_engine import napari_hook_implementation
from PartSeg.plugins.napari_widgets.mask_create_widget import MaskCreateNapari
from PartSeg.plugins.napari_widgets.roi_extraction_algorithms import ROIAnalysisExtraction, ROIMaskExtraction
from PartSeg.plugins.napari_widgets.search_label_widget import SearchL... | 1,388 | 441 |
# NOT_RPYTHON
class CFFIWrapper(object):
def __init__(self):
import cffi
ffi = cffi.FFI()
ffi.cdef("""
HINSTANCE ShellExecuteA(HWND, LPCSTR, LPCSTR, LPCSTR, LPCSTR, INT);
HINSTANCE ShellExecuteW(HWND, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, INT);
""")
self.NULL =... | 1,433 | 502 |
import csv
import pandas as pd
from ast import literal_eval
import matplotlib.pyplot as plt
import seaborn as sns
# DATA_PATH = "/content/drive/MyDrive/ExplainedKinshipData/data/all_pairs_also_unrelated_complete.csv"
# data = pd.read_csv(DATA_PATH, converters={"feat1": literal_eval, "feat2": literal_eval})
# print(dat... | 1,815 | 754 |
a, b = map(int, input().split())
if a >= 10 or b >= 10:
print(-1)
else:
print(a*b)
| 91 | 45 |
# coding=utf-8
class Revoke:
"""
A revoke is described by :
- The database on which it exists
- The privilege revoked
- The user on wich the revoke applies
- The table on which the revoke applies
- The owner of the table on which the revoke applies
"""
def __in... | 2,147 | 577 |
#!C:\Users\INDIA\PycharmProjects\patient5\venv\Scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| 172 | 61 |
from torch import tensor
from numpy.random import choice,shuffle
max_len = 128
def random_cut(length):
s = choice(length-max_len+1)
return s,s+max_len
def differeniate(statesA,statesB):
return [[i,b] for i,(a,b) in enumerate(zip(map(int,statesA),map(int,statesB))) if b!=a]
def generate_targe... | 4,394 | 1,594 |
from keras.models import load_model
from numpy import array, asarray, shape
from dataset import DatasetGenerator
def classify_sound(model, sound_file):
model = load_model(model)
LABELS = 'no yes'.split()
dsGen = DatasetGenerator(label_set=LABELS)
x = array(dsGen.process_wav_file(sound_file))
x = asarray(x).resh... | 467 | 189 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg["Subject"] = "Hallo Welt"
msg["From"] = "Donald Duck <don@ld.de>"
msg["To"] = "Onkel Dagobert <d@gobert.de>"
text = MIMETe... | 489 | 193 |
'''
slrfield slrclasses subpackage
This subpackage defines some classes that facilitate the processing of the SLR(Satellite Laser Ranging) data.
# cpfpred.py
Class structure:
CPFdata
- attributes:
- info: all information about the cpf ephemeris file
- version: version number of ... | 841 | 244 |
from rest_framework import serializers
from api.models import User, Log
class UserSerializer(serializers.ModelSerializer):
logs = serializers.RelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('name','token','logs')
class LogSerializer(serializers.ModelSerializer):
... | 396 | 106 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-18 20:29
from __future__ import unicode_literals
import enum
from django.db.models import Sum
from django.db import migrations
from moneyed import Money
class TrxTypeOld(enum.Enum):
INCOMING = 0
OUTGOING = 1
class TrxType(enum.Enum):
FINAL... | 2,346 | 817 |
############################################################################
# Copyright (C) by gempa GmbH, GFZ Potsdam #
# #
# You can redistribute and/or modify this program under the #
# terms o... | 20,935 | 5,576 |
# © 2018 Gerard Marull-Paretas <gerard@teslabs.com>
# © 2014 Mark Harviston <mark.harviston@gmail.com>
# © 2014 Arve Knudsen <arve.knudsen@gmail.com>
# BSD License
"""Mostly irrelevant, but useful utilities common to UNIX and Windows."""
import logging
def with_logger(cls):
"""Class decorator to add a logger to ... | 543 | 204 |
"""
RoundedTube
Copyright: MAXON Computer GmbH
Written for Cinema 4D R18
Modified Date: 05/12/2018
"""
import os
import math
import sys
import c4d
from c4d import plugins, utils, bitmaps, gui
# Be sure to use a unique ID obtained from www.plugincafe.com
PLUGIN_ID = 1025250
class RoundedTube(plugins.ObjectData):
... | 13,665 | 5,572 |
# -*- coding: utf-8 -*-
from scripts.utils.saving import save_soccer_model
def checkpoint(model, early_stopping=True):
losses = model.losses
patience_rate = model.es_patience
if(len(losses['train']) > 1 and len(losses['eval']) > 1 and early_stopping):
last_train_loss = losses['train'][-2]
... | 1,548 | 501 |
import numpy as np
import os
import cv2
from multiprocessing import Process
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
def process_directory(directory):
print 'Processing {}: started'.format(directory)
images = os.listdir(directory)
for img in images:
image = cv2.imrea... | 1,115 | 369 |
from euler.primes import smallest_prime_factor
def compute(n: int) -> int:
while True:
prime = smallest_prime_factor(n)
if prime < n:
n //= prime
else:
return n
| 215 | 65 |
#!/usr/bin/env python3
# 成绩排名 (20)
n = int(input())
l = input()
maxRecord = l
minRecord = l
maxScore = int(l.split()[2])
minScore = int(l.split()[2])
for i in range(n-1):
l = input()
s = int(l.split()[2])
if s < minScore:
minScore = s
minRecord = l
if s > maxScore:
maxScore = s
maxRecord = l
p... | 398 | 173 |
# db init
from tinydb import TinyDB
from constants.directory import DB_PATH, TRAINING_PATH
def main():
initialize_db()
def initialize_db():
try:
if not TRAINING_PATH.exists():
print(f"Dir - [{TRAINING_PATH}] not found. Proceeding to create the dir.")
TRAINING_PATH.mkdir(paren... | 505 | 174 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, query_size, attention_size):
super(Attention, self).__init__()
self.query_size = query_size
self.key_size = attention_size
self.map_query = nn.Linear(query_size, attent... | 9,057 | 2,949 |
class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__... | 610 | 226 |
# 76. Minimum Window Substring
import collections
class Solution:
def minWindow(self, s: str, t: str) -> str:
cnt = collections.Counter(t)
fix_cnt = cnt.copy()
n = rem = len(t)
l = r = 0
ans = None
while r < len(s):
while r < len(s) and rem > 0:
... | 877 | 297 |
# Copyright (c) 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.
#
"""
InferSent models. See https://github.com/facebookresearch/InferSent.
"""
from __future__ import absolute_import, division,... | 3,737 | 1,372 |
from copy import copy
from django.utils.http import urlencode
from django.utils.datastructures import MergeDict
from django.http import QueryDict
from hyperadmin.links import LinkCollectionProvider, LinkCollectorMixin
class State(MergeDict):
def __init__(self, substates=[], data={}):
self.active_diction... | 5,680 | 1,626 |
"""This module provides constants used in the rest of the package
"""
# some constants
missingval = -99999999.
m2km = 0.001
km2m = 1000.
gravity = 9.81
maxparcels = 99999
L = 2.501e6 # latent heat of vaporization
Rd = 287.04 # gas constant dry air
Rv = 461.5 # gas constant water vapor
epsilon ... | 799 | 419 |
from collections import defaultdict
from typing import Union, List, Dict, Set, Iterable, Optional
from baikal._core.data_placeholder import is_data_placeholder_list, DataPlaceholder
from baikal._core.digraph import DiGraph
from baikal._core.step import Step, InputStep
from baikal._core.typing import ArrayLike
from bai... | 23,161 | 6,138 |
'''
Encode dataset as biLM embeddings to a file.
'''
import argparse
import json
from bilm import dump_bilm_embeddings
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', '-g', type=int, default=-1,
help='GPU ID (negative value indicates CPU)')
parser.add_argument('--batchsize', '-b', ... | 1,127 | 403 |
import cv2
import cv2.aruco as aruco
import numpy as np
import configparser
import os
class ARTracker:
# Constructor
def __init__(self, cameras, write=False):
self.write=write
self.distanceToMarker = -1
self.distanceToMarker1 = 0
self.distanceToMarker2 = 0
self.widthOf... | 7,023 | 2,147 |
import os
import requests
PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
def send_msg(data):
res = requests.post("https://graph.facebook.com/v2.6/me/messages",
params={'access_token': PAGE_ACCESS_TOKEN},
json=data)
if res.status_code == 200:
pass
... | 1,850 | 677 |
import random, string, sys
GROWTH_RATE = 2 # we only place repo's in locations that support at least GROWTH_RATE times the size of the repo
CHIP_RATE = 0.9 # if a repo has no locations that support GROWTH_RATE * repo.local_size, we chip off a bit off the desired size to see if we can find a repo anyway
MAX_SERVERS = 1... | 5,015 | 2,031 |
class Solution(object):
def compareVersion(self, version1, version2):
v1 = version1.split('.')
v2 = version2.split('.')
int_v1 = 0
int_v2 = 0
point_v1 = 0
point_v2 = 0
int_v1 = self.convert(v1[0])
int_v2 = self.convert(v2[0])
if len(v1) > 1:
point_v1 = self.convert(v1[1])
if len(v2) > 1:
... | 881 | 497 |
#!/bin/python3
# Copyright (C) 2020 Matheus Fernandes Bigolin <mfrdrbigolin@disroot.org>
# SPDX-License-Identifier: MIT
"""Day Three, Toboggan Trajectory."""
from sys import argv
from utils import open_file, arrange, usage_and_exit, product
def solve(terrain, slopes):
"""Return the product of the number of t... | 1,003 | 395 |
from mamba.loader import describe, context
from mamba.hooks import before, after
from mamba.decorators import pending
__all__ = ['describe', 'context', 'before', 'after', 'pending']
__version__ = '0.6'
| 203 | 64 |
import pickle
# openしたfileのread, write関数を細工して,2**3
class LargeObject(object):
def __init__(self, f):
self.f = f
def __getattr__(self, item):
# 項目名'item'を参照されたらf.'item'を返す
# (itemは任意の文字列)
# 要するにfile objectのread write以外は元のファイルオブジェクトを見ればよい
return getattr(self.f, item)
... | 1,753 | 691 |
from magnebot.test_controller import TestController, ActionStatus
"""
Test whether the Magnebot is initialized successfully.
"""
if __name__ == "__main__":
m = TestController()
status = m.init_scene()
assert status == ActionStatus.success, status
status = m.move_by(1)
assert status == ActionStatus... | 349 | 103 |
from blue_connect import BluetoothComm
from ledstrip import Ledstrip
from button_manager import ButtonManager
import subprocess
import constants
import pprint
import time
import datetime
# ps -ef | grep python
# sudo kill -9 [pid]
# pip freeze > requirements.txt
# pip install -r requirements.txt
# sudo systemctl st... | 4,373 | 1,468 |
# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution II
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-normal-distribution-2/problem
# challenge id: 21230
#
import math
def N(x, µ, σ):
""" Normal Distribution """
π = math.pi
return math.exp(... | 837 | 360 |
import pygame
from random import randrange
from cloud_part import Cloud_Part
import math
'''
This class creates clouds at random locations in the screen.
'''
class Cloud(object):
# Class initializer
def __init__(self, screen, width, height, horizontal_constraints, vertical_constraints, VERBOSE):
super... | 2,214 | 692 |
import base64
import json
import pathlib
import requests
import sys
BASE_DIR = pathlib.Path(__file__).parent.absolute()
with open(BASE_DIR.joinpath('config.json')) as config_file:
config = json.load(config_file)
WEB_HOOK = "https://pabe.vanillacre.me/deepwebhook"
querystring: dict = {
"apikey": config['API_K... | 2,070 | 684 |
import numpy as np
import matplotlib.pyplot as plt
data = np.load("uv-coverage.npy")
print(data.shape) | 104 | 37 |
from _binding import *
class SndFileError(Exception):
pass
class VirtualIO(SF_VIRTUAL_IO):
def __init__(self, fd):
# references
self._fd = fd
self._c_char = c_char
self._string_at = string_at
def get_filelen(userdata):
where = self._fd.tell()
... | 4,587 | 1,492 |
# -*- coding: utf-8 -*-
from .facebookbirthday import FacebookBirthdayPlugin
| 77 | 27 |
"""tkimage.pyw 简单的图片查看器
"""
import tkinter as tk
import tkinter.filedialog as fd
def openimage(canvas):
"""事件处理函数:使用文件对话框打开图片
"""
filename = fd.askopenfilename(filetypes=[("PNG图片", "*.png"),
("GIF图片", "*.gif")])
global image # 注意这个需要定义为全局变量
... | 833 | 361 |
import joblib
import pandas as pd
from util import draw_boxes, display_image, get_image_from_s3, get_image_boxes
import os
objects = joblib.load(os.path.join('..','data','data.joblib'))
id2url = joblib.load(os.path.join('..','data','id2url.joblib'))
meta = pd.read_csv(os.path.join('..','open_images_', 'validation-ima... | 1,027 | 365 |
# -*- coding: utf-8 -*-
"""Codice Viola © 2020."""
| 52 | 32 |
import Command
class RemoteControlWithUndo :
def __init__(self) :
no_command = Command.NoCommand()
self.on_commands = [no_command, no_command, no_command, no_command, no_command, no_command, no_command]
self.off_commands = [no_command, no_command, no_command, no_command, no_command, no_comm... | 1,233 | 409 |
# 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... | 2,458 | 672 |
from cryptography.fernet import Fernet
import os
def validated_input():
while True:
text = input("Enter Choice: ")
if text != 'Y' and text != 'N':
print("Invalid Input")
print()
continue
return text
def generate_fernet_key():
if os.path.exists('fer... | 1,174 | 345 |
import numpy as np
def inference(x, targets, model, alphabet):
"""Evaluate the log likelihood ratios given the model and input.
Then maps the distribution over the alphabet.
Args:
x(ndarray(float)): 3 dimensional np array first dimension is
channels second dimension is trials and thir... | 1,221 | 374 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import re
import os
import argparse
from os.path import *
from subprocess import Popen, PIPE
from CheckOptions import CheckOptions
class CheckManpage (CheckOptions):
def __init__(self, args):
CheckOptions.__init__(... | 1,231 | 393 |
# Generated by Django 3.2.6 on 2021-08-21 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('detector', '0002_auto_20210821_1201'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='mode'... | 449 | 156 |
import hydra
from fseval.adapters.openml import OpenMLDataset
from fseval.config import DatasetConfig, EstimatorConfig, PipelineConfig
from fseval.main import run_pipeline
from fseval.types import Task
from hydra.core.config_store import ConfigStore
from sklearn.base import BaseEstimator
from sklearn.feature_selection ... | 1,789 | 647 |
from random import choice
from string import ascii_lowercase, digits
from django.utils import timezone
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
import j... | 2,776 | 821 |
# HABET Basic Tracking Payload CircuitPython Script
# Recieves GPS data and transmits it via LoRa radio module
# Utilizes Adafruit Feather M4 Express, Ultimate GPS FeatherWing, RFM95W 433 MHz FeatherWing
# Last updated 9/2/2020 by Austin Trask
import time
import board
import busio
import digitalio
import analogio
impo... | 2,276 | 859 |
#!/usr/bin/env python
#===============================
# MNEMOSINE PY EXCHANGE
#===============================
from threading import Thread
import queue
import logging
import uuid
from message_broker.broker.broker import Broker
logging.basicConfig(level=logging.INFO,
format='[... | 1,058 | 340 |
import time
from functionality_core import FCore
from functionality_cores.utilcore import asynced
from functionality_cores.kerberos import require_ring
class jokes(FCore):
"""Collection of joke commands."""
def get_commands(self):
return {"recursion":self.recursion, "bee":self.bee}
@asynced
... | 1,293 | 411 |
from pathlib import Path
import os
from json_handler.utils import save_as_json, load_from_json, create_new_file
class List(list):
def __init__(self, seq=(), on_change=None):
if on_change is None:
self.__on_change__ = lambda x: None
else:
self.__on_change__ = on_change
... | 7,195 | 2,114 |
import os
import subprocess
from random import randint
os.system("g++ hillClimb.cpp -o test -std=c++11")
inf = 1<<20
radious = [90, 45, 30, 360, 10]
best = []
for i in range(len(radious)):
f = open("%d" % (radious[i]), "w")
b = open("best%d" % (radious[i]), "w")
best += [[-inf]]
f.close()
b.close()... | 1,403 | 561 |
# Simple TCP server
import socket
import queue
import select
class TCPServer:
def __init__(self, ip, port, callback=None, max_connections=5, bytes_count=1024):
# The IP address this server binds to
self.ip = ip
# The port this server binds to
self.port = port
# Callbac... | 5,243 | 1,266 |
from protos.plugin import library_pb2_grpc, common_pb2
class Methods(library_pb2_grpc.LibraryServiceServicer):
def Detect(self, request, context):
return common_pb2.ServiceOutputBool(value=True, error=None)
def IsUsed(self, request, context):
return common_pb2.ServiceOutputBool(value=True, er... | 445 | 144 |
# -*- coding: utf-8 -*-
# @Author: Macsnow
# @Date: 2017-05-11 10:53:57
# @Last Modified by: Macsnow
# @Last Modified time: 2017-05-11 15:36:00
from flask.ext.restful import Resource, reqparse
from flask import session
from src.common.util import abortIfSubjectUnauthenticated
from src.common.util import abo... | 2,225 | 689 |
import string
import unittest
class TestUtil(unittest.TestCase):
def test_random_string(self):
from vmreflect.utils import get_random_string
for l in range(20):
self.assertEquals(l, len(get_random_string(length=l)))
for alphabet in ['1234', string.letters, '!$(AJ$)AF(A@F']:
... | 449 | 138 |
# -*- coding: utf-8 -*-
###############################################################################
#
# RegisterCallback
# Allows you to generate a unique URL that can "listen" for incoming data from web request.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache Licens... | 4,740 | 1,236 |
# -*- coding: utf8 -*-
from flask import url_for, current_app
from nose.tools import *
from base import Test, db, with_context
from explicates.model.collection import Collection
from explicates.model.annotation import Annotation
class TestModelAnnotation(Test):
def setUp(self):
super(TestModelAnnotatio... | 2,788 | 712 |
#!/usr/bin/env python
'''
Copyright (c) 2016, Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Hutmacher Robin, Karrenbauer Oliver, Marek Felix, Meissner Pascal, Trautmann Jeremias, Wittenbeck Valerij
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted... | 6,641 | 1,825 |
from nose.tools import set_trace
class AdminAuthenticationProvider(object):
def __init__(self, integration):
self.integration = integration
def auth_uri(self, redirect_url):
# Returns a URI that an admin can use to log in with this
# authentication provider.
raise NotImplemente... | 474 | 119 |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""Unit test of paragraph processing classes: PreProcessed and PostProcessed
as well as Processor subclasses.
Copyright: Ian Vermes 2019
"""
from tests.base_testcases import ParagraphsTestCase, BaseTestCase, ProcessorTestCase_Genuine
from tests.special_testcases import Pr... | 58,296 | 17,939 |
from .tldry import TLDRy
| 25 | 12 |
import json
from numpy import *
from geode import *
def from_ndarray(v, typ = float):
return map(typ, v.flatten())
def from_array(v, typ = float):
return map(typ, v)
to_json_fn = {}
from_json_fn = {}
from_json_fn['int'] = lambda v: int(v)
from_json_fn['real'] = lambda v: real(v)
from_json_fn['float'] = ... | 2,911 | 1,291 |
from .version import __version__
# __version__ = version
__author__ = 'Niclas Rieger'
__email__ = 'niclasrieger@gmail.com'
| 124 | 45 |
from tibanna_ffcommon.core import API as _API
from .stepfunction import StepFunctionPony
from .stepfunction_cost_updater import StepFunctionCostUpdater
from .vars import (
TIBANNA_DEFAULT_STEP_FUNCTION_NAME,
LAMBDA_TYPE,
IAM_BUCKETS,
DEV_ENV,
PROD_ENV
)
class API(_API):
# This one cannot be im... | 2,350 | 729 |
import pca9685
_DC_MOTORS = ((8, 9, 10), (13, 12, 11), (2, 3, 4), (7, 6, 5))
class DCMotors:
def __init__(self, i2c, address=0x40, freq=1600):
self.pca9685 = pca9685.PCA9685(i2c, address)
self.pca9685.freq(freq)
def _pin(self, pin, value=None):
if value is None:
return b... | 1,262 | 536 |
#!/usr/bin/env python3
# -*-coding:utf-8-*-
"""chargen
Usage:
chargen.py start project <project>
chargen.py add template <template_file> into <project>
chargen.py (-h | --help)
chargen.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
from docopt import docopt
import c... | 978 | 330 |
import sys,os,random
class Body:
def __init__(self):
self.name = "Planet no. 1"
self.type = "body"
self.sprite = "null"
self.dock = 0
self.race = "human"
self.faction = "rebel"
self.wealth = 20 # in trillions
self.population = 70 # in bil... | 6,914 | 2,005 |
from orangecontrib.recommendation import Learner, Model
import numpy as np
__all__ = ["LearnerRecommendation", "ModelRecommendation"]
class ModelRecommendation(Model):
def predict_on_range(self, predictions):
# Just for modeling ratings with latent factors
try:
if self.min_rating is... | 2,092 | 621 |
#!/usr/bin/python3
from datetime import datetime
import os
import shutil
import logging
import base64
import requests
import json
import cv2 as cv
from PIL import Image, ImageEnhance
import pandas as pd
import numpy as np
import math
logging.basicConfig(filename='app.log', filemode='w',level=logging.INFO, format="... | 14,480 | 4,557 |
from discord.ext import commands
class WalletOpFailedException(commands.CommandError):
pass
class NoMatchingCurrency(WalletOpFailedException):
pass
class MultipleMatchingCurrencies(WalletOpFailedException):
pass | 229 | 67 |
#!/usr/bin/env python3
# This is a simple 4 banger calculator
LICENSE = """DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2015 Arti Zirk <arti.zirk@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, ... | 3,445 | 1,077 |
from hetdesrun.component.registration import register
from hetdesrun.datatypes import DataType # add your own imports here
from hetdesrun.utils import plotly_fig_to_json_dict
import pandas as pd
def handle_substitutions(original_series, substitution_series):
"""Applies substituion series on raw values
... | 2,444 | 732 |
import os
import torch
import numpy as np
from torch.utils.data import TensorDataset, DataLoader
from src.data_preprocessing.witness_complex_offline.config import ConfigWC
from src.datasets.datasets import SwissRoll
if __name__ == "__main__":
n_samples = 5
#
labels = torch.from_numpy(np.array(range(n_sa... | 1,047 | 374 |
'''Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty.
The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the t... | 2,688 | 947 |
import getpass
import argparse
import boto3
import sys, os, csv
from github import Github
from github.InputFileContent import InputFileContent
import json
from datetime import timedelta
from collections import OrderedDict
from . import utils
from .utils import ensure, ymd, splitfilter, vals, lmap, lfilter, utcnow
MAX_... | 16,366 | 5,321 |
# Copyright 2016 - Nokia
#
# 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, sof... | 3,805 | 1,127 |
#!/usr/bin/env python
# coding: utf-8
# # Gaussian Code Exercise
#
# Read through the code below and fill out the TODOs. You'll find a cell at the end of the Jupyter notebook containing unit tests. After you've run the code cell with the Gaussian class, you can run the final cell to check that your code functions as ... | 9,032 | 2,572 |
#!/usr/bin/env python3
# md_poly_lj_module.py
#------------------------------------------------------------------------------------------------#
# This software was written in 2016/17 #
# by Michael P. Allen <m.p.allen@warwick.ac.uk>/<m.p.allen@bristol.ac.uk> ... | 10,958 | 3,551 |
#!/usr/bin/python
# This code is part of GET-Evidence.
# Copyright: see COPYING
# Authors: see git-blame(1)
"""
usage: %prog genome_gff_file
"""
# Process the sorted genome GFF data and the json report of coding region
# coverage to get and return meta data.
import gzip
import re
import sys
from utils import gff
D... | 6,667 | 2,089 |
# encoding: utf-8
import os
import traceback
from app.pyinstaller.readers import CArchiveReader
from app.pyinstaller.readers import ZlibArchiveReader
from extractor import ArchiveExtractor
class PyinstallerExtractor(ArchiveExtractor):
def __init__(self, fpath, **kwargs):
key = kwargs.get("key","")
... | 524 | 164 |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | 68,602 | 25,663 |
from win32com import client as wc
import os, time
class Pdf_docx_md(object):
def load_files(self, path):
'''
加载所需文件,返回文件名(All)
'''
os.chdir(path)
dir = os.getcwd()
files = os.listdir(dir)
for file in files:
yield file
def do_exchange(sel... | 1,609 | 593 |
# https://www.hackerrank.com/domains/python?filters%5Bsubdomains%5D%5B%5D=py-sets
# Set Union
input()
first = set(map(int, input().split()))
input()
second = set(map(int, input().split()))
print(len(first.union(second)))
# Set Intersection
input()
first = set(input().split())
input()
second = set(input().split())
... | 649 | 230 |
class EntityExtractor:
def __init__(self, data_source):
self.data_source = data_source
def extract(self, query):
query = query.lower()
aggregation = self._extract_aggregation(query)
dimensions = self._extract_dimensions(query)
filters = self._extract_filters(query)
... | 1,146 | 302 |
import os
from glob import glob
from time import sleep
from flask_cors import CORS
from flask import Flask, jsonify, request, render_template, Response, send_file
import Common
import threading
from liveDownloader import run as RUN
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_credential... | 5,938 | 2,053 |
"""
ASGI config for newv project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
settings_exists = os.path.exists(
... | 512 | 178 |
import json
import os
import sys
import cv2
import numpy as np
import pandas as pd
import torch
from tqdm import tqdm
from aim_target.utils import compute_accuracy
with open(sys.argv[1], "r") as f:
config = json.load(f)
model = torch.load(
f"{config['checkpoints']}/{config['image_size']}_{config['model']}.p... | 1,300 | 474 |
#!/usr/bin/env python3
"""Assembly metadata methods."""
import sys
from collections import defaultdict
from tolkein import toinsdc
from tolkein import tolog
from .es_functions import index_stream
from .es_functions import query_keyword_value_template
from .es_functions import query_value_template
from .hub import a... | 11,471 | 3,498 |
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2015 Richard Hull
#
# 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 righ... | 2,754 | 875 |