text string | size int64 | token_count int64 |
|---|---|---|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Firefox(executable_path="./drivers/geckodriver")
browser.get('https://ACCOUNTNUMBER.signin.aws.amazon.com/console?region=us-east-1')
browser.find_element_by_xpath('//*[@id="username"]').send_keys('USERNAME')... | 1,692 | 619 |
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.ima... | 4,307 | 1,373 |
import argparse
import glob
import hashlib
import json
import os
import string
DATASET_INDEX_PATH = '../mirdata/datasets/indexes/phenicx_anechoic_index.json'
def md5(file_path):
"""Get md5 hash of a file.
Parameters
----------
file_path: str
File path.
Returns
-------
md5_hash: ... | 4,888 | 1,490 |
from nonebot import on_command, CommandSession, get_bot
from nonebot.command import call_command
from nonebot.message import escape as message_escape
import aiohttp
from nonebot.argparse import ArgumentParser
__plugin_name__ = "运行代码"
RUN_API_URL_FORMAT = "https://glot.io/run/{}?version=latest"
SUPPORTED_LANGUAGES = {... | 4,341 | 1,535 |
import os
from os import listdir
from os.path import isfile, join
'''
Author: Shufeng KONG, Cornell University, USA
Contact: sk2299@cornell.edu
This is an example script to run jobs. Set single_job to be True if you only have one setting or dataset to run.
In our experiments, we have 69 systems to run, so we set sing... | 2,905 | 1,028 |
import re
import numpy as np
from pyquil import Program
from pyquil.device import gates_in_isa
from pyquil.gates import I, RX, CNOT, MEASURE
from pyquil.noise import decoherence_noise_with_asymmetric_ro
from forest_benchmarking.readout import get_flipped_program, estimate_confusion_matrix, \
estimate_joint_confus... | 3,460 | 1,254 |
import platform
def default_platform():
if platform.system() == 'Windows':
return 'Windows-x86'
if platform.system() == 'Linux' and platform.architecture()[0] == '32bit' and platform.machine()[0:3] == 'ppc':
return 'Linux-ppc32'
if platform.system() == 'Linux' and platform.architecture()[0]... | 768 | 247 |
"""
Written by Jesse Evers
A basic calculator.
"""
# Adds x and y
def add(x, y):
return x + y
# Subtracts y from x
def subtract(x, y):
return x - y
# Multiplies x by y
def multiply(x, y):
return x * y
# Divides x by y
def divide(x, y):
return x / y
# Raises x to the y
def exponent(x, y):
r... | 853 | 304 |
#!/usr/bin/env python
# python WebMinerAnalyzer.py www.mejortorrent.org ./data 10
import requests
import json
import sys
import os
import subprocess
import time
import json
import re
import time as t
import shutil
import datetime
import magic
import run_web
import util
import pdb
fil = ['chatbro','tidio.co', 'getcou... | 20,328 | 9,188 |
import logging
from os.path import join
from numpy import savetxt, column_stack
from pywps import ComplexInput, ComplexOutput
from pywps import Format
from pywps import LiteralInput
from pywps import Process
from pywps.app.Common import Metadata
from shapely.geometry import Point
from eggshell.nc.ocg_utils import cal... | 5,367 | 1,420 |
# SPDX-License-Identifier: MIT
from freshmaker.parsers import BaseParser
from freshmaker.events import FlatpakModuleAdvisoryReadyEvent
from freshmaker.errata import Errata, ErrataAdvisory
class ErrataAdvisorySigningChangedParser(BaseParser):
"""
Parses errata.activity.signing messages (a build attached to ad... | 1,166 | 384 |
# coding: utf-8
import requests
def get_song_comments(music_id, offset=0, total='false', limit=100):
action = 'http://music.163.com/api/v1/resource/comments/R_SO_4_{}/?rid=R_SO_4_{}&\
offset={}&total={}&limit={}'.format(music_id, music_id, offset, total, limit)
# proxy = {"http": "http://dev-prox... | 1,940 | 734 |
from typing import Union
from torch.utils.data.dataset import Dataset
from data_modules.dataset_factory import DatasetFactory
from torch.utils.data import DataLoader
import pytorch_lightning as pl
class ImageDatasetDataModule(pl.LightningDataModule):
def __init__(self, dataset_factory: Union[DatasetFa... | 2,356 | 693 |
import settings
import const
import pandas as pd
import numpy as np
import matplotlib
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True}) # to prevent labels going out of plot!
matplotlib.use('TkAgg')
import seaborn as sns
import matplotlib.pyplot as plt
from src.preprocess import reform
from ... | 3,429 | 1,197 |
# vim: set et sw=4 ts=4 nu fdm=indent:
# coding: utf8
import numpy as np
import random
from demag import demagnetization
from llg import Bth
class Object:
def __init__(self, position, magnetization, a=1.0, b=1.0, h=1.0, angle=0, M0=1720e3):
if len(magnetization) == 2 and len(position) == 2:
... | 6,002 | 2,115 |
import taichi as ti
import taichi_three as t3
import numpy as np
ti.init(ti.cpu)
scene = t3.Scene()
obj = t3.readobj('assets/cube.obj', scale=0.6)
model = t3.Model(t3.Mesh.from_obj(obj))
model.material = t3.Material(t3.CookTorrance(
color=t3.Texture(ti.imread('assets/cloth.jpg')),
normal=t3.NormalMap(texture=... | 828 | 360 |
def test_artificial_objects_2d():
import pyclesperanto_prototype as cle
cle.artificial_objects_2d()
| 108 | 38 |
import vcf
from django.http import HttpResponse
from django.core.files import File
import xlsxwriter
import os
from .vcf_functions import getBasePath, save_binary, getFilePath, parse_fasta, getEspPath
import subprocess
import collections
from .dictionaries import esp_col_dic
from pytera.settings import BASE_DIR
# PYTE... | 132,733 | 33,636 |
# -*- coding: utf-8 -*-
import clr
import sys
import math
import getmethod
import genRtf
clr.AddReferenceByPartialName("IronPython")
#initpath=r"d:\Program Files\NCS\CS3000"
#initpath=r"C:\Program Files (x86)\NCS\ONH3000"
# initpath=r"C:\CS3000备份\CS3000_1.7.0"
initpath=r"C:\Program Files (x86)\NCS\CS3000"
# initpath=r... | 13,003 | 5,654 |
"""Common utils.
* CORS pre-flight decorator. A simple decorator to add the options method to a Request Class.
"""
from .constants import ALLOW_ALL_ORIGINS
def cors_preflight(methods: str = "GET"):
"""Render an option method on the class."""
def wrapper(f): # pylint: disable=invalid-name
def option... | 799 | 229 |
from .shop import Shop
from .allyouneed import AllYouNeed
from .kaufland import Kaufland
| 89 | 28 |
"""
# week3 madness...
# filter, process (map-match) and output data to new postgres database
# aim by thurs, to be able to answer question, where are (best-guess/estimate) all the taxis at time T.
# then, work out, how far each one is from one another, likely a) search with in BBox, then b) do some fast osrm routing (... | 11,323 | 4,392 |
class LOCK_KINDS(object):
""" The different kinds of lock which you can use.
WEAK is not guaranteed to be robust, but can be used for situations where avoiding
simultaneous code execution is preferable but not critical.
STRONG is for where preventing simultaneous code execution is *require... | 372 | 99 |
import sys
sys.path.append('.')
from lgy.algorithm.StdIOTestContainer import StdIOTestContainer as T
def main():
v1 = input()
v2 = input()
length = max(len(v1), len(v2))
dp = [[0 for i in range(len(v2) + 1)] for j in range(len(v1) + 1)]
ans = 0
for i in range(1, len(v1) + 1):
for j i... | 668 | 305 |
#!/usr/bin/env python
import os
import socket
import unittest
from ..gstat import gstat, gstats, gstat_event, gstat_elapsed
class MockSocket(object):
def __init__(self, *args, **kwargs):
self._sendto_msg = []
self._closed = False
def sendto(self, msg, hostport):
sent = {'msg': msg}
... | 5,164 | 1,727 |
from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap
# from flask_appconfig import AppConfig
from flask_wtf import Form, RecaptchaField
from wtforms import TextField, HiddenField, ValidationError, RadioField, BooleanField, SubmitField
from wtforms.validators import Required
import ge... | 1,721 | 550 |
from markdown.preprocessors import Preprocessor
class CalcReadingTimePreprocessor(Preprocessor):
def __init__(self, cfg, *args, **kwargs):
self.cfg = cfg
super(CalcReadingTimePreprocessor, self).__init__(*args, **kwargs)
def run(self, root):
word_count = len(root)
print("... | 427 | 139 |
import csv
import importlib
import sys
sys.path.append('..')
import os
import json
import argparse
import copy
from enum import IntEnum
from datetime import datetime
import numpy as np
import scipy.integrate as solve
import scipy.optimize as opt
import matplotlib.pylab as plt
from scripts.tsv import parse as parse_ts... | 19,842 | 7,462 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class AbstractFold(nn.Module):
def __init__(self, predict, partfunc):
super(AbstractFold, self).__init__()
self.predict = predict
self.partfunc = partfunc
def clear_count(self, param):
param_count = {}
... | 3,396 | 1,033 |
import optparse
def fib(n, prin):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
if prin:
print a
return a
def Main():
parser = optparse.OptionParser('usage %prog ' + \
'-n <fib number> -o <output file> -a <print all>', version = '%prog 1.0')
parser.add_option('-n', dest = 'num', type = 'int', \
help... | 998 | 409 |
#/usr/bin/env python3.4
#
# Copyright (C) 2016 The Android Open Source Project
#
# 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 requir... | 3,651 | 1,125 |
# coding=utf-8
import numpy as np
# fromfile = np.fromfile('/Users/xiebaiyuan/PaddleProject/paddle-mobile/tools/python/imagetools/datas/jpgs/0000_0.9834-148196_82452-0ad4b83ec6bc0f9c5f28101539267054.jpg_p0_0.126571263346.jpg.npfile', 'f')
# fromfile = np.fromfile('/Users/xiebaiyuan/PaddleProject/paddle-mobile/tools/py... | 3,568 | 1,770 |
from flask_wtf import FlaskForm # , RecaptchaField
from wtforms import validators, StringField
from wtforms.validators import Length
# from wtforms.fields.html5 import URLField
class UrlForm(FlaskForm):
old = StringField('Title', [
validators.InputRequired(),
validators.Length(
min=4,... | 663 | 213 |
'''
Author : MiKueen
Level : Easy
Problem Statement : Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
'''
class... | 645 | 226 |
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyMoira",
version="4.3.2",
description="PyMoira - Python bindings for the Athena Moira library",
author="Evan Broder",
author_email="broder@mit.edu",
lice... | 655 | 211 |
import uuid
from django.db import models
from django.contrib.auth.models import AbstractUser
import django.utils.timezone
import environ, requests
env = environ.Env()
environ.Env.read_env()
class AuthorManager(models.Manager):
def get_queryset(self):
queryset = super().get_queryset()
# # TODO: Ite... | 7,818 | 2,191 |
"""Faker data providers for biological data."""
from random import choice
from faker.providers import BaseProvider
from . import utils
class GeneticProvider(BaseProvider):
"""Genomic data provider.
Acid data source:
http://www.cryst.bbk.ac.uk/education/AminoAcid/the_twenty.html
"""
acids = {
... | 1,727 | 602 |
POSITIVE_PHRASES = [
"That said, I liked it.",
"That said, I loved it.",
"That said, I couldn't be happier.",
"That said, I'm pleased.",
"That being said, I liked it.",
"That being said, I loved it.",
"That being said, I couldn't be happier.",
"That being said, I'm pleased."
]
NEGATIVE_... | 640 | 227 |
import pytest
import factory
import asyncio
from cuve.order_service.db import transaction, tables
from cuve.order_service.db.helpers import async_create_database
from cuve.order_service.app import application_factory
from cuve.order_service.config import load_config, ConfigSchema
def pytest_addoption(parser):
pa... | 2,708 | 762 |
'''
检查系统内文件是否完备
'''
from pathlib import Path
import os
basepath = os.path.dirname(__file__) # 当前文件所在路径
file_list = []
for file in file_list:
my_file = Path(f'{basepath}/analysis_result/asd')
if not my_file.exists():
# 检测是否存在id路径不存在
os.makedirs(my_file) # 只能创建单级目录 =.=对这个用法表示怀疑
... | 351 | 193 |
# Copyright 2013 OpenStack Foundation
#
# 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 ... | 7,983 | 2,432 |
from pyspark import SparkContext
import os
import re
import json
import sys
import time
import logging
import collections
from itertools import combinations
from itertools import product
s_logger = logging.getLogger('py4j.java_gateway')
s_logger.setLevel(logging.ERROR)
sc = SparkContext('local[*]', 'task1')
sc.setLogL... | 1,792 | 733 |
import os
from argparse import ArgumentParser
import json
import copy
import shutil
def process_kb(in_kb):
all_values = set({})
items = in_kb.get('items', {})
if items is None:
items = {}
for item in items:
for key, value in item.items():
all_values.add(value)
return so... | 3,917 | 1,235 |
if __name__ == '__main__':
from sys import exit
from mk60.app import main
exit(main())
else:
raise RuntimeError("runner must be run, not imported")
| 164 | 51 |
#! python3
"""A stopwatch program with a prettier output and pyperclip functionality."""
import time
import pyperclip
# Display the programs instructions.
print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch.'
'Press Ctrl-c to quit.')
input()
print('Started.')
start_time = time.time()... | 1,038 | 323 |
"""Modulo principal que utiliza todas las demas clases para ejecutar el framework"""
from .Algorithms import GeneticAlgorithm, SimulatedAnnealing, LocalSearch, IteratedLocalSearch, timer
from . import sys, os, AlgorithmsOptions, MHType, Tsp, Tour, bcolors
def main(argv=sys.argv) -> None:
"""
Funcion principal... | 2,768 | 865 |
#!/usr/bin/env python
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
import os
import threading
from sklearn.externals import joblib
import bnpy
import rospy
import copy
from std_msgs.msg import (
Header
)
from birl_sim_examples.msg import (
Tag_MultiModal,
Hmm_Log
)
data_arr = ... | 5,879 | 1,920 |
"""
Tests for MemoryEngine::RemoteMemory
"""
import unittest
import cPickle
from cStringIO import StringIO
import mock
from FelixMemoryServes import MemoryEngine
class WebMocker(unittest.TestCase):
def set_request_val(self, val):
self.req_val = cPickle.dumps(val)
def get_request(s... | 4,838 | 1,559 |
#! python3
# -*- coding: utf-8 -*-
from typing import Union
"""Internal module with functions for print to console.
"""
__version__ = "0.13.0"
class __Print:
"""Class with functions for print to console.
"""
def __init__(self, *args, **kwargs):
from threading import Lock
self.s_print_loc... | 6,033 | 1,748 |
import io
import logging
import os
from pathlib import Path
from zipfile import ZipFile
from cognite.client.data_classes import DataSet, FileMetadata
from cognite.client.exceptions import CogniteAPIError
from cognite.experimental import CogniteClient
from retry import retry # type: ignore
from configs import Functio... | 3,514 | 1,124 |
'''
BUILT-IN DATA TYPES
Mutable - the value can change
Immutable - the value cannot change
'''
# Immutable object
age = 99
id(age)
age = 100
id(age)
'''
We didn't change 99 to 100. We actually just pointed age to a different location: the new int object whose value is 100.
We print the IDs by calling the built-in ... | 474 | 181 |
from keras.applications import inception_v3
from keras import backend as K
import scipy
import imageio
from keras.preprocessing import image
import numpy as np
K.set_learning_phase(0)
model = inception_v3.InceptionV3(weights='imagenet', include_top=False)
layer_contributions = {'mixed2': 0.2, 'mixed3': 3., 'mixed4':... | 3,147 | 1,315 |
import pygame
import argparser
import lib
import ai.neatinterface.neatcore
pygame.init()
if __name__ == "__main__":
args = argparser.get_args()
# pygame initialization
pygame.init()
# initialize properly and make links make them as common resources
# for other modules
# I admit this looks ... | 978 | 296 |
import unittest
from cv2 import imwrite
import numpy as np
from simple_3dviz import Scene, Lines, Spherecloud
from simple_3dviz.window import show
class TestLines(unittest.TestCase):
def test_line(self):
points = np.array([[-0.5, 0.5, -0.5],
[ 0.5, 0.5, 0.5]])
color... | 495 | 189 |
# -*- coding: utf-8 -*-
'''
Module contains all of the functions to create a radio telemetry project.'''
# import modules required for function dependencies
import numpy as np
import pandas as pd
import os
import sqlite3
import datetime
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.dates as mdat... | 39,946 | 11,495 |
from manim import *
from tests.test_graphical_units.testing.frames_comparison import frames_comparison
__module_test__ = "mobjects"
@frames_comparison(base_scene=ThreeDScene)
def test_PointCloudDot(scene):
p = PointCloudDot()
scene.add(p)
| 250 | 87 |
from __future__ import division, print_function
import pytest
from itertools import product
import numpy as np
from libgdf_cffi import ffi, libgdf
from librmm_cffi import librmm as rmm
from libgdf_cffi.tests.utils import (new_column, unwrap_devary,
get_dtype, gen_rand, buffer_as_bits, count_nulls)
params_... | 3,284 | 1,287 |
from py.test import raises
from collections import namedtuple
from pytest import raises
from graphene.core.fields import (
Field,
StringField,
)
from graphql.core.type import (
GraphQLObjectType,
GraphQLInterfaceType
)
from graphene import Schema
from graphene.contrib.django.types import (
DjangoNo... | 1,889 | 550 |
#!/usr/bin/env python
"""Sets up a flask-restx server for running the swabseq analysis R-script."""
from script_runner.server import app, api
from script_runner.api.script import api as script
from script_runner.api.health import api as server_health
api.add_namespace(script)
api.add_namespace(server_health)
if _... | 357 | 118 |
# pylama:ignore=W0401,W0611
from .iso8601 import *
| 51 | 30 |
import argparse
import json
import logging
import threading
from pyinstrument import Profiler
from landia.client import GameClient
from landia.config import GameDef, PlayerDefinition, ServerConfig
from landia.content import Content
from landia.common import StateDecoder, StateEncoder
from landia.registry import lo... | 10,225 | 3,195 |
import io
import datetime
class Vehicle:
def __init__(self, name, rank, max_rank=50):
self.name = name
self.rank = rank
self.max_rank = max_rank
self.voyage = None
def add_voyage(self, voyage):
self.voyage = voyage
def delete_voyage(self):
self.voyage = None
... | 3,734 | 1,143 |
from collections import defaultdict, deque
from contextlib import suppress
from dataclasses import field
from datetime import datetime
from decimal import Decimal
from typing import Union
import arrow
import runtype
from runtype.typesystem import TypeSystem
from preql.utils import dataclass
from .base import Object
... | 10,735 | 3,737 |
"""
Version naming has been simplified in 2.0 going forward.
Production releases will be MAJOR.MINOR format.
Increments to major are reserved for significant updates.
Increments to minor are available for all new versions
Test releases are MAJOR.MINOR.PATCH format.
"""
import setuptools
with open("README.md", "r") as... | 947 | 300 |
from pyspark import SparkConf, SparkContext
from pyspark.sql import Row
from pyspark.sql import SparkSession
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import json
import sys
import rethinkdb as r
from generate_simulate_data import get_attributes_summary
from generat... | 2,966 | 1,013 |
import subprocess
import itertools
def dictate(parts):
"""Converts `parts` to valid input for mac os 'say' util."""
# todo: could feed it phrases one by one, to allow the user to pause
input_string = " ".join(parts)
subprocess.run(['say', '-v', 'Daniel'],
stdout=subprocess.PIPE,
... | 1,464 | 545 |
import os
import numpy as np
import SimpleITK as sitk
from pymic.io.image_read_write import load_image_as_nd_array
from pymic.transform.trans_dict import TransformDict
from pymic.util.parse_config import parse_config
def get_transform_list(trans_config_file):
config = parse_config(trans_config_file)
transf... | 1,964 | 621 |
import argparse
import json
from typing import List
from . import utils
def pylint_argument_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Pylint analyzer")
parser.add_argument("--rcfile", dest="rcfile", type=str, help="Specify a configuration file.")
utils.add_python... | 1,433 | 458 |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2019. All Rights Reserved.
"""
These are methods for accessing Jira. The Jira REST API is used for general access.
Requirements: JIRA URL and basic authentication user/password
"""
import json
import fn_jira.... | 5,485 | 1,509 |
import random
print 10000
random.seed(a=None)
for i in xrange(0,10000):
length = random.randint(5,20)
string = ""
for j in xrange(0, length):
x = random.randint(ord('a'), ord('z'))
string += chr(x)
print string
| 224 | 103 |
import pytest
from indy_common.authorize.auth_constraints import AuthConstraint, IDENTITY_OWNER
@pytest.fixture(scope='module')
def write_auth_req_validator(write_auth_req_validator, key):
write_auth_req_validator.auth_cons_strategy.get_auth_constraint = lambda a: AuthConstraint(IDENTITY_OWNER, 1)
return wri... | 1,075 | 337 |
import time
from typing import Any
from django.core.management import BaseCommand
from django.db import connections
from django.db.utils import OperationalError
class Command(BaseCommand):
def handle(self, *args: Any, **options: Any) -> None:
self.stdout.write("Waiting for database to be ready...")
... | 660 | 165 |
S = input()
print(S+"s" if S[-1] != "s" else S+"es")
| 53 | 27 |
import argparse
parser = argparse.ArgumentParser(description='parameters')
# -- Basic --
parser.add_argument('--seed', type=int, default=42,
help='random seed (default: 42)')
parser.add_argument('--eps', type=float, default=1e-6,
help='epsilon (default: 1e-6)')
parser.add_argum... | 8,905 | 2,832 |
import numpy as np
def state_value_function(p,r,v):
gamma=0.9
while True:
value=r.T+gamma*p*v
if(value==v).all():
break
v=value
return v
if __name__ =='__main__':
#c1 c2 c3 pass pub fb sleep
#probability matrix
P_matrix=np.mat([[0,0,0,0,0,0,0],
... | 693 | 318 |
#1.温度转换
# C = float (input('请输入摄氏温度:'))
# F = (9 /5) * C + 32
# print('%.2f 华氏度' %F)
#2.计算圆柱体的体积
#area:面积 radius:半径 volume:体积 length:高 π=3.14
#radius=float(input('请您输入圆柱体的半径:'))
#length=float(input('请您输入圆柱体的高:'))
#area= radius * length * 3.14
#print('圆柱体的面积为: %0.4f' %area)
#volume= area * length
#pri... | 1,372 | 960 |
__all__ = ('log', 'progress_callback_factory', 'progress_callback_divisions', 'BadUserError', 'setup')
import binascii
import hashlib
import mimetypes
import mmap
import os
import posixpath
import re
import time
import boto3
import botocore
import termcolor
log = lambda msg: None
progress_callback_factory = lambda: ... | 22,428 | 6,136 |
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(se... | 363 | 115 |
#!/usr/bin/env python2
from sys import stdin
import sys
# There shouldn't be any input
assert len(stdin.readline()) == 0
sys.exit(42)
| 136 | 51 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Solutions to chapter 4 exercises.
###############################################################################
# chapter4_exercises.py
#
# Revision: 1.00
# Date: 6/27/2021
# Author: Alex
#
# Purpose: Solutions to chapter 4 exercises from "Data... | 14,393 | 4,207 |
rules_adjetive = []
with open("MM.adj.txt",'r') as f:
for line in f.readlines():
rule = line.split()
rules_adjetive.append({"word":rule[0], "lemma":rule[1], "code":rule[2]})
rules_noun = []
with open("MM.nom.txt",'r') as f:
for line in f.readlines():
rule = line.split()
rules_n... | 4,220 | 1,419 |
from setuptools import setup, find_packages
auth_deps = ['oauthlib', 'requests_oauthlib']
extras_require = {
'adobe': ['adobe_analytics'],
'azure_mssql': ['pyodbc'],
'dataiku': ['dataiku-api-client'],
'elasticsearch': ['elasticsearch'],
'facebook': ['facebook-sdk'],
'google_analytics': ['google... | 1,746 | 678 |
import sqlite3
conn = sqlite3.connect('bookstore.sqlite')
c = conn.cursor()
c.execute('''
CREATE TABLE books
(id INTEGER PRIMARY KEY ASC,
timestamp DATETIME NOT NULL,
title VARCHAR(250),
author VARCHAR(250),
rating INTEGER,
price REAL
... | 367 | 106 |
import pytest
from _pytest.unittest import UnitTestCase
__version__ = '0.2.1'
INI_OPTION_CLASSES = 'python_unittest_classes'
INI_OPTION_UNDERSCORE = 'python_unittest_exclude_underscore'
def pytest_addoption(parser):
parser.addini(
INI_OPTION_CLASSES,
type='args',
default=None,
... | 1,125 | 376 |
# 問題URL: https://atcoder.jp/contests/abc134/tasks/abc134_b
# 解答URL: https://atcoder.jp/contests/abc134/submissions/24157832
from math import ceil
n, d = map(int, input().split())
print(ceil(n / (2 * d + 1)))
| 210 | 109 |
# Copyright 2018 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 agreed to in writing, ... | 5,058 | 1,672 |
from visual_mpc.envs.base_env import BaseEnv
class OfflineSawyerEnv(BaseEnv):
"""
Emulates a real-image Sawyer Env without access to robot, only works together with the Offline Agent!
"""
def __init__(self, env_params_dict, reset_state=None):
self._hp = self._default_hparams()
... | 1,151 | 385 |
import unittest
import Export_To_File
import gen_rand_password
class ExportToFileTestCase(unittest.TestCase):
def test_append_file(self):
pass
def test_gen_rand_password(self):
pass
if __name__ == '__main__':
unittest.main()
| 258 | 88 |
from . import test_rocket
| 26 | 9 |
import numpy as np
# from ray.dataframe import pd
# def pairwise_correlations( g_t)
def euclidean_metric( g_t,delta):
n_d = g_t.shape[0]
v = np.gradient( g_t, delta, axis=0 )
vv = np.empty( n_d, dtype=np.float32 )
for t in np.arange( n_d ):
vv[t] = np.dot( v[t], v[t].T )
return vv
de... | 4,241 | 1,764 |
from random import random
def mutate(chromosome, p):
return ''.join((a, '01'[a == '0'])[random() <= p] for a in chromosome)
| 130 | 51 |
# INFO : ini merupakan copy source code dari repo one4ubot, dan sudah mendapatkan izin dari pemilik.
# INFO : This is a copy of the source code from the One4ubot repo, and has the permission of the owner.
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d ... | 5,243 | 1,940 |
"""
Module: 'uasyncio.core' on pyboard 1.13.0-95
"""
# MCU: (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-95-g0fff2e03f on 2020-10-03', machine='PYBv1.1 with STM32F405RG')
# Stubber: 1.3.4 - updated
from typing import Any
class CancelledError(Exception):
""""""
class IOQueue:
""""... | 1,291 | 493 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from scipy.special import erf, erfinv
import cPickle as pickle
import glob
import os
import scipy
import scipy.ndimage.interpolation
#print glob.glob(os.path.expanduser("~/storage/metadata/kaggle-heart/predictions/j7_jeroen_ch.pkl"))
#... | 1,675 | 608 |
from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter
from django.urls import include, path
from django_celery.api.users.views import UserViewSet
if settings.DEBUG:
router = DefaultRouter()
else:
router = SimpleRouter()
router.register("users", UserViewSet)
app_name... | 437 | 132 |
# stdlib
import os
import sys
import logging
import json
from json import JSONEncoder
import praw
from kinesis_producer import StdoutProducer
from twitter_query_parser import TwitterSeachQuery
log = logging.getLogger(__name__)
class RedditException(Exception):
"""Invalid SubRedditException."""
... | 3,366 | 1,060 |
import concurrent.futures
import click
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import KFold
from models import NbSvmClassifier
from utils.constants import RANDOM_SEED, CLASS_NAMES
from utils.data_loader import tf_idf_vectors
cv_params = [
... | 3,523 | 1,237 |
# -*- coding: utf-8 -*-
# Author: Arthur Imbert <arthur.imbert.pro@gmail.com>
# License: BSD 3 clause
"""
Unitary tests for bigfish.stack.filter module.
"""
import pytest
import numpy as np
import bigfish.stack as stack
from bigfish.stack.filter import _define_kernel
from numpy.testing import assert_array_equal
fr... | 15,217 | 6,179 |
# QoS Manager
# Managing all requests related to QoS
# Author: Deyuan Guo, Chunkun Bo
# Date: Dec 10, 2015
import sys
import os
import socket
import errno
import monitor_container
import qos_scheduler
import itf_spec
import itf_database
QOS_SERVER_ADDR = ('localhost', 20000)
# Define a class for QoS requests
class Q... | 9,071 | 2,670 |
################################################################################
################################## BLUEBOTTLE ##################################
################################################################################
#
# Copyright 2012 - 2018 Adam Sierakowski and Daniel Willen,
# ... | 4,527 | 1,670 |