id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3258783 | import ast
import keyword
import string
from hypothesis import assume
from hypothesis.strategies import lists, sampled_from, recursive, text, composite, one_of, none, booleans, integers
@composite
def name(draw):
n = draw(text(alphabet=string.ascii_letters, min_size=1, max_size=3))
assume(n not in keyword.kw... |
3258793 | import libpagekite
from libpagekite import PK_EV_RESPOND_DEFAULT
class BaseEventHandler(object):
def __init__(self, pk):
self.pk = pk
self._map = {
libpagekite.PK_EV_CFG_FANCY_URL: self.fancy_rejection_url,
libpagekite.PK_EV_TUNNEL_REQUEST: self.tunnel_request}
def get... |
3258796 | from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^event/add/$', EventCreate.as_view(), name='community_calendar_event_create'),
url(r'^event/(?P<pk>[\d]+)/edit/$', EventUpdate.as_view(), name='community_calendar_event_edit'),
url(r'^event/(?P<pk>[\d]+)/delete/$', EventDelete.as_... |
3258817 | import os
import glob
import scipy.misc as misc
import numpy as np
import imageio
from io import BytesIO
def normalize_image(img):
"""
Make image zero centered and in between (0, 1)
"""
normalized = img / 255.
return normalized
def read_split_image(img):
mat = misc.imread(img).astype(np.flo... |
3258826 | import argparse
import os
from bisect import bisect_left
from random import randint
from itertools import repeat
from itertools import accumulate
from math import sqrt
import json
parser = argparse.ArgumentParser()
parser.add_argument('models', nargs='+', action='store', help='A list of model filenames.')
parser.add_a... |
3258831 | from espnet2.torch_utils.set_all_random_seed import set_all_random_seed
def test_set_all_random_seed():
set_all_random_seed(0)
|
3258902 | import logging
from datetime import datetime
from typing import (
Generic,
Optional,
List,
Dict,
Any,
ClassVar,
Type,
TypeVar,
cast,
TYPE_CHECKING,
)
import attr
from marshmallow import fields
from simple_smartsheet import utils
from simple_smartsheet.models import sheet as she... |
3258914 | from metasmt.core import *
import inspect
# Expressions
def install_operator( sym, types, functions ):
# Process Types
if types == '*':
types = [ predicate, bitvector, logic_expression ]
elif not isinstance( types, list ):
types = [ types ]
# Process Functions
if not isinstance( ... |
3258940 | from __future__ import unicode_literals
from django.db import models
from vecihi.users.models import User
class Question(models.Model):
whom = models.ForeignKey(User)
question = models.CharField(max_length=100, blank=False, null=False)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self... |
3258954 | import argparse
from tqdm import tqdm
import pandas as pd
import nltk
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_file", type=str)
parser.add_argument("--text_col", type=str, default="sentence")
parser.add_argument("--output_file", type=str)
parser.add_argument("... |
3258967 | from . import importer
importer.install(check_options=True)
from django.core.management import (execute_from_command_line, # noqa
call_command)
|
3258973 | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
return 0
start = count = 0
product = 1
for i, num in enumerate(nums):
product *= num
while product >= k:
product //= nums[start]
... |
3258974 | import math
import torch.nn as nn
from torch.optim import Adam
from gym import spaces
from common.distributions import *
from common.util import Flatten
def atari(env, **kwargs):
in_dim = env.observation_space.shape
policy_dim = env.action_space.n
network = CNN(in_dim, policy_dim)
optimizer = Adam(n... |
3258988 | import pytest
import abc
import os
import sys
from glob import glob
import xarray as xr
import numpy as np
import logging
from climt import (
HeldSuarez, GrayLongwaveRadiation,
Frierson06LongwaveOpticalDepth, GridScaleCondensation,
BergerSolarInsolation, SimplePhysics, RRTMGLongwave,
RRTMGShortwave, Sla... |
3259011 | from __future__ import division
def diff_percentage(max_count, min_count, **kwargs):
difference_count = int(max_count) - int(min_count)
if difference_count == 0:
return 0
variation = int(difference_count/int(min_count))*100
return variation
|
3259019 | from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('profile/', include('user_profile.urls')),
# comment app
path('comment/', include('comment.urls')),
... |
3259052 | from django.conf.urls.defaults import *
urlpatterns = patterns('payments.views',
url(r'^home/purchased/(?P<uid>\d+)/(?P<id>\d+)/$', 'purchased'), # callback
url(r'^pay/$', 'stripePayment'),
url(r'^receipt/(?P<pid>[0-9]+)/$', 'receipt', name='receipt'),
)
|
3259071 | from keras.datasets import cifar10
import numpy as np
class Cifar10(object):
def __init__(self, batch_size=64, test=False):
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
if test:
images = x_test
else:
images = x_train
self.images = (images - 127.5) / 127.5
self.batch_size... |
3259122 | import unittest2 as unittest
from datetime import datetime
from redish import utils
class test_maybe_list(unittest.TestCase):
def test_list(self):
self.assertListEqual(utils.maybe_list([1, 2, 3]), [1, 2, 3])
def test_value(self):
self.assertListEqual(utils.maybe_list(1), [1])
def test_... |
3259145 | import logging
import os
from pathlib import Path
import toml
from dpymenus.exceptions import ButtonsError
def load_settings():
"""Attempts to parse a pyproject.toml file and get all data under the [dpymenus] header."""
data = {}
try:
with open(Path(os.getcwd()) / 'pyproject.toml', 'r') as file... |
3259161 | import os
import sys
import struct
import argparse
import numpy as np
import pycuda.autoinit
import pycuda.driver as cuda
import tensorrt as trt
BATCH_SIZE = 1
INPUT_H = 224
INPUT_W = 224
OUTPUT_SIZE = 1000
INPUT_BLOB_NAME = "data"
OUTPUT_BLOB_NAME = "prob"
EPS = 1e-5
WEIGHT_PATH = "./densenet121.wts"
ENGINE_PATH =... |
3259169 | from xiblint.rules import Rule
from xiblint.xibcontext import XibContext
class NoAttributedStringColors(Rule):
"""
Ensures attributed strings don't specify colors.
"""
def check(self, context): # type: (XibContext) -> None
for element in context.tree.findall(".//color"):
# Skip <c... |
3259189 | from __future__ import absolute_import, division
import unittest
import numpy as np
from gofft.bench import (BenchmarkCase, BenchmarkSuite, BenchmarkLoader,
BenchmarkRunner)
class FakeStream(object):
def write(self, *args, **kwargs):
""" Do nothing in unit test stage. """
... |
3259241 | class AlgoHashTable:
def __init__(self, size):
self.size = size
self.hash_table = self.create_buckets()
def create_buckets(self):
return [[] for _ in range(self.size)]
def set_val(self, key, value):
hashed_key = hash(key)%self.size
bucket = self.hash_table[hashed_k... |
3259263 | f"echo '{self.FLUSH_CMD}'\n"
f"echo '{self.FLUSH_CMD}'\\n"
f"echo '{self.FLUSH_CMD}'\n"
f"echo '{self.FLUSH_CMD}'\\n"
|
3259270 | import os
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoretable import TableCheckpointStore
CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"]
EVENTHUB_NAME = os.environ["EVENT_HUB_NAME"]
STORAGE_CONNECTION_STR = os.environ["AZURE_STORAGE_CONN_STR"]
TABLE_NAME = "your-tab... |
3259307 | import sys, os, re, time, math, random, struct, zipfile, operator, csv, hashlib, uuid, pdb
from collections import defaultdict
dir_path = os.path.dirname([p for p in sys.path if p][0])
sys.path.insert(0, 'libs')
import logging
LOG_FILENAME = dir_path+'/CassDriver.log'
logging.basicConfig(filename=LOG_FILENAME, level=l... |
3259325 | from django.conf import settings
from django.urls import include, path
from .views import ListGene, GeneDetail, GenesetDetailView
from django.contrib import admin
admin.autodiscover()
from genes.models import GeneList
from . import views
from django.contrib.auth.decorators import login_required, permission_required
... |
3259346 | import torch.nn.functional as F
from torch import nn
from cortex.plugins import ModelPlugin
from cortex.main import run
class Autoencoder(nn.Module):
"""
Encapsulation of an encoder and a decoder.
"""
def __init__(self, encoder, decoder):
super(Autoencoder, self).__init__()
self.encod... |
3259349 | from particle import Particle
# A subclass of Particle
class CrazyParticle(Particle):
# Just adding one variable to a CrazyParticle.
# It inherits all other fields from "Particle", and we don't have to
# retype them!
# The CrazyParticle constructor can call the parent class (super class)
# c... |
3259361 | from flask_restful import Resource
from flask import request
from services import LabseAlignerService
from models import CustomResponse, Status
from utilities import MODULE_CONTEXT
from anuvaad_auditor.loghandler import log_info, log_exception
class LabseAlignerResource(Resource):
def post(self):
inputs = ... |
3259427 | from pydantic import BaseModel
class Invoice(BaseModel):
INVOICE_DATE: str
INVOICE_NUMBER: str
TOTAL: float
|
3259452 | import torch
# Masking the sequence mask
def make_mask(feature):
"""
:param feature:
for img: (bs, proposals, 2048/512)
for text - do text.unsqueeze(2) first : (bs, seq_len, 1)
:return:
shape: (bs, 1, 1, seq_len/proposal)
"""
return (torch.sum(
torch.abs(feature),
... |
3259457 | import torch
import torch.nn
from models.convlstm.convlstm import ConvLSTMCell
import torch.nn.functional as F
class LSTMSequentialEncoder(torch.nn.Module):
def __init__(self, height, width, input_dim=13, hidden_dim=64, nclasses=8, kernel_size=(3,3), bias=False):
super(LSTMSequentialEncoder, self).__init__... |
3259463 | from ..utils.common import user
def test_bloom_release_dash_h():
assert 0 == user('bloom-release -h'), "Exited with non-zero status."
|
3259482 | import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import Subplot
fig = plt.figure(1, (3,3))
ax = Subplot(fig, 111)
fig.add_subplot(ax)
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
plt.show()
|
3259498 | import argparse
from collections import defaultdict
import json
import os
import sys
sys.path.append(os.getcwd())
import glob
import csv
from rich.table import Table
from rich.console import Console
from rich import print
from rich.console import RenderGroup
from rich.panel import Panel
#
# config
#
parser = argpa... |
3259504 | from yacs.config import CfgNode as CN
_C = CN()
# -----------------------------------------------------------------------------
# EXPERIMENT
# -----------------------------------------------------------------------------
_C.EXP = CN()
_C.EXP.MODEL_NAME = '2d'
_C.EXP.EXP_ID = ""
_C.EXP.SEED = 0
# ----------------------... |
3259505 | import gc
import os
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.metrics import mean_squared_error, roc_auc_score, median_absolute_error
from termcolor import colored
from torch.optim.lr_scheduler import MultiStepLR
from torch import nn
from torch import optim
from tqdm import tqdm
fro... |
3259509 | from memoize import memoize_configuration
# needed if one has tornado installed (could be removed otherwise)
memoize_configuration.force_asyncio = True
import asyncio
from datetime import timedelta
from aiocache import cached, SimpleMemoryCache # version 0.11.1 (latest) used as example of other cache implementation... |
3259531 | import re
import subprocess
from ...exc import BleakError
def check_bluez_version(major: int, minor: int) -> bool:
"""
Checks the BlueZ version.
Returns:
``True`` if the BlueZ major version is equal to *major* and the minor
version is greater than or equal to *minor*, otherwise ``False``... |
3259533 | import sys
import pandas as pd
from pubsub import pub
from sklearn.preprocessing import LabelEncoder
import matplotlib
if "linux" not in sys.platform:
matplotlib.use("WXAgg")
try:
import seaborn as sns
sns.set()
except ImportError:
pass
import wx
def prepare_data(df):
"""
A helper function... |
3259549 | from __future__ import absolute_import
from setuptools import setup
from lambkin.version import VERSION
import os.path
if(os.path.isfile('README.md')):
import pypandoc
with open('README.rst', 'w') as rst:
rst.write(pypandoc.convert('README.md', 'rst', format='md'))
setup(
name='lambkin',
packages=... |
3259557 | from computer import Computer
with open('input05', 'r') as data:
data = list(map(int, data.read().split(',')))
tape = Computer(int_code=data)
print(*tape.compute_n(niter=2, feed=(1, 5))) |
3259566 | from wagtail.core.models import Page
from wagtail_app_pages.models import AppPageMixin
class HomePage(AppPageMixin, Page):
url_config = 'home.urls'
|
3259575 | from typing import *
@overload
def pprint_thing(thing: Literal["0"]):
"""
usage.koalas: 2
"""
...
@overload
def pprint_thing(thing: int):
"""
usage.dask: 2
usage.koalas: 1
"""
...
@overload
def pprint_thing(thing: Literal["a"]):
"""
usage.koalas: 2
"""
...
@ov... |
3259580 | import asyncio
from asynctnt import Response
from asynctnt.exceptions import TarantoolDatabaseError, ErrorCode
from tests.util import get_complex_param
from tests import BaseTarantoolTestCase
class CallTestCase(BaseTarantoolTestCase):
def has_new_call(self):
return self.conn.version >= (1, 7)
async ... |
3259654 | import re
import logging
import datetime
from os import makedirs
from os.path import join, exists, getsize
import requests
from wordpad import pad
from homura import download
from .errors import IncorrectLandsat8SceneId, RemoteFileDoesntExist, IncorrectSentine2SceneId
logger = logging.getLogger('sdownloader')
S3_LAN... |
3259674 | from kairos_face import settings, exceptions
def validate_file_and_url_presence(file, url):
if not file and not url:
raise ValueError('An image file or valid URL must be passed')
if file and url:
raise ValueError('Cannot receive both a file and URL as arguments')
def validate_settings():
... |
3259729 | import logging
import torch
from torch import Tensor, nn
from typing import Dict, Tuple, List
from detectron2.config import configurable
from detectron2.layers import cat
from detectron2.modeling.matcher import Matcher
from detectron2.modeling.poolers import ROIPooler
from detectron2.modeling.meta_arch.build import ME... |
3259754 | import streamlit as st
from tensorflow.keras.models import model_from_json
from numpy import asarray
import numpy as np
import base64
from PIL import Image
json_file = open("ResNetModel.json","r")
loaded_json_model = json_file.read()
json_file.close()
model = model_from_json(loaded_json_model)
model.load_weight... |
3259787 | import torch
import logging
from torch import nn
import torch.nn.functional as F
from model.tcn_block import TemporalConvNet
# from model.pe import PositionEmbedding
# from model.optimizations import VariationalDropout, WeightDropout
from IPython import embed
logging.basicConfig( \
level = logging.INFO, \
for... |
3259792 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from cloudera.director.d6_1.authentication_api import AuthenticationApi
from cloudera.director.d6_1.clusters_api import ClustersApi
from cloudera.director.d6_1.database_servers_api import DatabaseServersApi
from cloudera.director.d6_... |
3259796 | import os
import shutil
from collections import OrderedDict
from git import Repo
def get_raw_data():
cldr_version = '31.0.1'
raw_data_directory = "../raw_data"
cldr_data = {
'dates_full': {
'url': 'https://github.com/unicode-cldr/cldr-dates-full.git',
'dir': "{}/cldr_date... |
3259862 | from .i_base_dev import IBaseDev
from .i_base_model import IBaseModel
from .i_torch_model import ITorchModel
from .i_base_dev_torch import IBaseDevTorch
|
3259865 | from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from typing import Callable
from functools import wraps
def plotaxes():
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(1.0,1.0,1.0)
glBegin(GL_LINES)
glVertex2f(0,-100)
glVertex2f(0,100)
glEnd()
glBegin(GL_LINES)
glVerte... |
3259874 | from typing import Tuple
def split_addr(addr: str) -> Tuple[str, int]:
host, _, port = addr.rpartition(":")
return host, int(port)
# vim: set et ts=4 sw=4:
|
3259902 | from hydromet import*
#---------------------------------------------------------------------------#
def main(binData: list, incr_excess: pd.DataFrame, tempE: float,
convE: float, volE: float, tsthresh: float,
display_print: bool=True) -> dict:
... |
3259918 | from model.tokenization_gpt2 import GPT2Tokenizer
import torch
import torch.nn as nn
import numpy as np
import tqdm
tokenizer = GPT2Tokenizer(vocab_file='../data/DialoGPT/small/vocab.json',
merges_file='../data/DialoGPT/small/merges.txt')
tokenizer.init_kwargs = {'vocab_file': '../data/Dialo... |
3259931 | import random
import vampire.common as common
import vampire.preprocess_adaptive as pre
def test_filters():
unfiltered = common.read_data_csv('adaptive-filter-test.csv')
correct = common.read_data_csv('adaptive-filter-test.correct.csv')
filtered = pre.apply_all_filters(unfiltered)
assert correct.equa... |
3259941 | from __future__ import print_function
from datetime import date
import shutil
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
from clockifytool import helpers
def list_entries(args, config, app_data):
today_raw = date.today()
today = today_raw.strft... |
3259952 | from os.path import dirname as _dirname, basename as _basename, isfile as _isfile
import glob as _glob
exec('\n'.join(map(lambda name: "from ." + name + " import *",
[_basename(f)[:-3] for f in _glob.glob(_dirname(__file__) + "/*.py") \
if _isfile(f) and not _basename(f).startsw... |
3259957 | from constants import *
from constants.paths import Paths
from experiments.baseline.model.coref import MentionMentionCNN
from experiments.baseline.model.linking import MentionClusterEntityLinker
from experiments.baseline.tools.evaluators import *
from experiments.baseline.tools.ioutils import SpliceReader
from experime... |
3259972 | import gspread
gc = gspread.oauth()
sh = gc.open("Example spreadsheet")
print(sh.sheet1.get('A1'))
|
3259984 | import vim
import re
from view import *
from utils import *
from conn import *
from change import *
#======================== Global Setup/Config ================================#
ExplorerCharOpened = u'\u25bd'
ExplorerCharClosed = u'\u25b6'
if int(vim.eval('exists("g:GeeknoteExplorerNodeOpened")')):
Explo... |
3259994 | from urllib.parse import urlencode
from thenewboston_node.business_logic.models import Block, NodeDeclarationSignedChangeRequest
from thenewboston_node.business_logic.tests.base import as_primary_validator, force_blockchain
API_V1_LIST_NODES_URL = '/api/v1/nodes/'
def test_can_list_nodes(
api_client, file_block... |
3260012 | class UnknownPixelFormatException(Exception):
pass
class InvalidMagic(Exception):
pass
class InvalidEncryptionKey(Exception):
pass
class ParserException(Exception):
pass |
3260027 | import sys
import os
import re
from collections import defaultdict
tag_props = {
'ATOM': {
'name': (13, 16),
'altLoc': (17, 17),
'resName': (18, 20),
'chainID': (22, 22),
'iCode': (27, 27),
'element': (77, 78),
'charge': (79, 80),
},
'HELIX': {
'class': (39, 40),
},
}
... |
3260038 | import json
import os
import requests
from google.cloud import logging
from google.cloud import secretmanager
import sentry_sdk
def message_post(data):
# pprint.pprint(payload)
token = get_secret("slack-handler-token")
channel_id = get_secret("slack-handler-channel")
payload = data if type(data) is ... |
3260057 | def prime_factors(num):
factor = []
for i in range(2, int(num ** 0.5 + 1)):
while not num % i:
factor.append(i)
num /= i
if num != 1:
factor.append(num)
return factor
if __name__ == '__main__':
print(prime_factors(120))
|
3260087 | import sys
import logging
import sys
import ee
import subprocess
import string
import os
import ee
def copy(initial,final):
for line in subprocess.check_output("earthengine ls "+initial,shell=True).split('\n'):
try:
src= line
dest=line.replace(initial,final)
com=(str('ea... |
3260088 | import pika.adapters
import pika
import uuid
import json
EXCHANGE = 'chatexchange'
EXCHANGE_TYPE = 'topic'
BINDING_KEY_DEFAULT = 'public.*'
PORT = 5672
# few utility print functions
def pi(msg):
print '\n[RabbitMQClient] : inside ' + msg.upper() + '()'
def pc(msg):
print '[RabbitMQClient] : Calling ' + ms... |
3260092 | import uuid
from django.db import models
class Other(models.Model):
pass
class EverythingModel(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
username = models.CharField(max_length=20, unique=True)
address = models.TextField()
o1 = models.ForeignKey(Other)... |
3260094 | import sys
from itertools import repeat
lots_of_fours = repeat(4, times=100_000_000)
print(f"Using itertools.repeat: {sys.getsizeof(lots_of_fours)} bytes")
lots_of_fours = [4] * 100_000_000
print(
f"Using list with 100.000.000 elements: {sys.getsizeof(lots_of_fours) / (1024**2)} MB"
)
|
3260117 | from . import visualizer, Visualizer
from ..dsp import sampler
@visualizer(name='dummy')
class DummyVisualizer(Visualizer):
ANALYZER_TYPE = sampler.Sampler
WINDOW_TITLE = 'Dummy Visualizer'
def _setup_analyzer(self):
self._analyzer_kwargs['sample_size'] = 256
self._analyzer_kwargs['buffer... |
3260156 | from RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_tools import *
# In this file we define the locations of the MVA weights, cuts on the MVA values
# for specific working points, and configure those cuts in VID
# The following MVA is derived for Spring16 MC samples for non-triggering photons.
# See more ... |
3260170 | import config
from flask import Flask, Response, request
from twilio import twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
client = TwilioRestClient(config.TWILIO_ACCOUNT_SID,
config.TWILIO_AUTH_TOKEN)
#Receive incoming call from customer
@app.route('/call', methods=['P... |
3260198 | import cv2 as cv
import numpy as np
src = cv.imread("D:/Images/lena.jpg")
cv.namedWindow("src", cv.WINDOW_NORMAL)
cv.imshow("src", src)
# X flip 镜像
dst = cv.flip(src, 0)
cv.namedWindow("X_flip", cv.WINDOW_NORMAL)
cv.imshow("X_flip", dst)
# Y flip 倒影
dst = cv.flip(src, 1)
cv.namedWindow("Y_flip", cv.WIN... |
3260208 | import pytest
import tensorflow as tf
from psychrnn.backend.rnn import RNN
from pytest_mock import mocker
import sys
if sys.version_info[0] == 2:
from mock import patch
else:
from unittest.mock import patch
# clears tf graph after each test.
@pytest.fixture()
def tf_graph():
yield
tf.compat.v1.reset... |
3260219 | import numpy as np
from numba import njit
@njit(fastmath=True)
def func(d,par):
return par.chi*np.log(1+d) |
3260235 | from auri.vendor.Qt import QtWidgets
from functools import partial
class MenuBarView(QtWidgets.QMenuBar):
def __init__(self, common_ctrl, main_ctrl):
"""
Args:
common_ctrl (auri.controllers.common_controller.CommonController):
main_ctrl (auri.controllers.main_controller.Ma... |
3260241 | import math
import datetime
from .location import Location
import logging
class Sun:
"""
Calculate sunrise and sunset based on equations from NOAA
http://www.srrb.noaa.gov/highlights/sunrise/calcdetails.html
typical use, calculating the sunrise at the present day:
import datetime
i... |
3260249 | from guppy.heapy.test import support
class IdentityCase(support.TestCase):
def test_1(self):
import random
vs = range(100)
random.shuffle(vs)
vs = [float(i) for i in vs]
x = self.iso(*vs).byid
if self.allocation_behaves_as_originally:
self.aseq(str(x)+'\n'+str(x.more)+'\n', """\
Set of 100 <float> objec... |
3260257 | from __future__ import absolute_import, division, print_function, unicode_literals
import json
import twitter
import urllib
from echomesh.base import DataFile
from echomesh.util.string import Truncate
TWITTER_SIZE = 140
API = None
def _get_api():
global API
if not API:
try:
auth = DataF... |
3260263 | import gumbocy
from test_word_groups import TAGS_SEPARATORS
def analyze(html, options=None):
parser = gumbocy.HTMLParser(options=options)
parser.parse(html)
return parser.analyze()
def test_separators():
html = """
<p>text</p>
<p>text 2</p>
<p>pre<p>inner</p></p>
"""
... |
3260285 | from common.exceptions import CustomException
class BadRequestException(CustomException):
error_message = "BAD_REQUEST"
def __init__(self):
super().__init__({})
class UnableToInitiateException(CustomException):
error_message = "UNABLE_TO_INITIATE"
def __init__(self):
super().__init... |
3260295 | import time
from datetime import timedelta
import torch
from torch import optim
def format_time(avg_time):
avg_time = timedelta(seconds=avg_time)
total_seconds = int(avg_time.total_seconds())
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{hours:02... |
3260300 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('Salaries.csv')
print(data)
x = data.iloc[:, 1:2].values
print(x)
y = data.iloc[:, 2].values
from sklearn.ensemble import RandomForestRegressor
# create regressor object
regressor = RandomForestRegressor(n_estimators = 100,... |
3260316 | import numpy as np
import pandas as pd
def read_data(data_path, word2idx, relation2idx, max_sequence_len=60):
data_csv = pd.read_csv(data_path, header=None, index_col=None, sep='\t',
names=['line_id', 'subject', 'entity_name', 'entity_type', 'relation', 'object',
... |
3260323 | from rest_framework import serializers
from .models import Search, SearchResult
class SearchResultSerializer(serializers.ModelSerializer):
class Meta:
model = SearchResult
fields = '__all__'
class SearchSerializer(serializers.ModelSerializer):
class Meta:
model = Search
field... |
3260324 | class Solution:
def nextPermutation(self, nums):
l = len(nums)
for i in range(l - 1, 0, -1):
if nums[i - 1] < nums[i]:
nums[i:] = sorted(nums[i:])
for j in range(i, l):
if nums[j] > nums[i - 1]:
nums[j], nums[i -... |
3260329 | length = int(input())
l = list(map(int, input().split()))
m = max(l)
s = sum(l)
print("{0:.2f}".format(s/length/m*100)) |
3260403 | import sys
from remoto.backends import local
class TestLocalConnection(object):
def test_hostname_gets_ignored(self):
conn = local.LocalConnection(hostname='node1')
assert conn.hostname == 'localhost'
def test_defaults_to_localhost_name(self):
conn = local.LocalConnection()
a... |
3260412 | from django.db.models import UUIDField
class CustomUUIDField(UUIDField):
""" Returns database value as a string, so that dashes are preserved. """
def from_db_value(self, value, expression, connection, context=None):
return str(value)
|
3260453 | from polyphony import testbench
foo = 1
def f():
def ff():
print('ff.foo', foo)
return foo == 2
foo = 2
return ff()
@testbench
def test():
assert f() == True
test()
|
3260521 | import argparse
import pprint
from client import Client
def main(host, port, verbose):
c = Client(host=host, port=port, verbose=verbose)
while True:
text = raw_input("sql> ").strip()
if text.lower() == "quit":
break
elif text:
result = c.query(text)
... |
3260548 | load("@bazel_skylib//lib:shell.bzl", "shell")
def _google_java_format_impl_factory(ctx, test_rule = False):
args = ["--aosp"]
if test_rule:
args.append("--set-exit-if-changed")
else:
args.append("--replace")
runner_files = depset(ctx.files._runner).to_list()
if len(runner_files) !=... |
3260557 | from enum import Enum
# Genie
from genie.decorator import managedattribute
from genie.conf.base.config import CliConfig
from genie.conf.base.base import DeviceFeature
from genie.conf.base.attributes import DeviceSubAttributes,\
InterfaceSubAttributes,\
... |
3260581 | def fib(num):
a = 0
b = 1
for i in range(num):
yield a
temp = a
a = b
b = b + temp
n = int(input())
for x in fib(n):
print(x)
|
3260618 | import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
dcc.Graph(
id='my-graph',
figure={
'data': [{'x': [1, 2, 3]}]
},
config={
'modeBarButtonsToRemove': [
'sendDataToCloud',
'pan2d',
'zoomIn2d',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.