id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11474313 | import numpy as np
class ParticlesFilter:
def __init__(self, environment_config, robot_initial_config, predictor, params):
"""
Initialize the particles filter parameters.
:param environment_config: EnvironmentConfiguration
:param robot_initial_config: RobotConfiguration
:... |
11474360 | from faster_than_requests import scraper
print(scraper(["https://nim-lang.org", "https://nim-lang.org"], html_tag="h1", case_insensitive=False, deduplicate_urls=False, threads=False))
|
11474361 | from ....widgets import *
class USPhoneNumberInput(InputMask):
mask = {
'mask': '999-999-9999',
}
class USSocialSecurityNumberInput(InputMask):
mask = {
'mask': '999-99-9999',
}
class USZipCodeInput(InputMask):
mask = {
'mask': '99999-9999',
}
class USDecimalInput... |
11474371 | from constants import load_model
from model import load_gen_model, setUpModel
if __name__ == '__main__':
if load_model:
load_gen_model()
else:
setUpModel()
|
11474405 | import torch
def convert_pytcv_model(model,model_pytcv):
sd=model.state_dict()
sd_pytcv=model_pytcv.state_dict()
convert_dict={}
for key,key_pytcv in zip(sd.keys(),sd_pytcv.keys()):
clean_key='.'.join(key.split('.')[:-1])
clean_key_pytcv='.'.join(key_pytcv.split('.')[:-1])
conve... |
11474430 | import random
a=random.randint(1,101)
print("let's start game. press enter")
print("you have only 5 chances to win the game")
b=int(input("enter the 1 no.- "))
if(b>a):
print("the no. you entered is greater the required no.")
elif(b<a):
print("the no. you entered is less thanthe required no. ")
elif(b==a):
... |
11474436 | from os_dbnetget.utils import binary_stdout
from os_dbnetget.commands.qdb import QDB
from os_dbnetget.commands.qdb.get.processor import Processor
class Get(QDB):
HELP = 'get data from qdb'
DESCRIPTION = 'Get data from qdb'
def __init__(self, config=None):
super(Get, self).__init__(config)
... |
11474458 | import argparse
import chainer
from chainer import iterators
import chainermn
from chainercv.utils import apply_to_iterator
from chainercv.utils import ProgressHook
from eval_semantic_segmentation import models
from eval_semantic_segmentation import setup
def main():
parser = argparse.ArgumentParser()
par... |
11474488 | import unittest
from katas.beta.sum_of_all_arguments import sum_all
class SumAllTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(sum_all(6, 2, 3), 11)
def test_equals_2(self):
self.assertEqual(sum_all(756, 2, 1, 10), 769)
def test_equals_3(self):
self.assertE... |
11474542 | import os.path
from airflow_plugins.operators import UnzipOperator
def test_unzip_operator():
folder = os.path.dirname(os.path.realpath(__file__))
op = UnzipOperator(task_id='dag_task',
path_to_zip_folder=folder,
path_to_zip_folder_pattern='*.py')
try:
... |
11474587 | from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes"
elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle"
else: print "no"
|
11474607 | import numpy as np
from deeplookup import qnn, vis
from deeplookup.env import MalwareEnv
ROOT_DIR = ".h5"
dqn, dqn_history = qnn.fit_dqn(MalwareEnv(), root_dir=ROOT_DIR)
ddqn, ddqn_history = qnn.fit_dqn(MalwareEnv(), dueling=True, root_dir=ROOT_DIR)
ddpg, ddpg_history = qnn.fit_ddpg(MalwareEnv(), root_dir=ROOT_DIR... |
11474683 | from .testbase import display_tree
from binarytree import AvlTree
def do_task():
a = AvlTree()
for value in [10, 20, 30, 40, 50, 25, 100, 28, 140]:
a.insert(value)
print(' display tree a:')
display_tree(a)
###########################################
b = a.clone()
b.insert(22)
... |
11474718 | from setuptools import find_packages, setup
setup(
name="ray_lightning",
packages=find_packages(where=".", include="ray_lightning*"),
version="0.1.2",
author="<NAME>",
description="Ray distributed plugins for Pytorch Lightning.",
long_description="Custom Pytorch Lightning distributed plugins "
... |
11474725 | import json
import numpy as np
from model import create_model
class Generator:
def __init__(self, weights_file, id2token_file, embedding_size, hidden_size):
self._model, self._id2token = self._load_model(
weights_file,
id2token_file,
embedding_size,
hidden_size
)
self._token2id = {token: id for id, ... |
11474800 | class MockRequestGET:
"""
Mocked GET response for requests.get
"""
def __init__(self, url):
self.text = open(url)
class MockMessage:
"""
Mocked `Message` object from slackbot.
Passed to decorated plugin functions as first param.
"""
def __init__(self, debug=False):
... |
11474813 | import json
import warnings
import geopandas
from geopandas.io.arrow import (
_create_metadata,
_decode_metadata,
_encode_metadata,
_validate_dataframe,
)
from pyarrow import parquet
from .extension_types import construct_geometry_array
def _arrow_to_geopandas(table):
# NOTE this is copied and ... |
11474818 | import os
from django.core.management import call_command
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample_project.settings")
import django
print("Django Version: " + django.__version__)
django.setup()
call_command('migrate')
# call_command('makemigrations')
|
11474825 | import numpy as np
from gym.spaces import Box, Discrete
from gym import spaces
def check_homogenize_spaces(all_spaces):
assert len(all_spaces) > 0
space1 = all_spaces[0]
assert all(
isinstance(space, space1.__class__) for space in all_spaces
), "all spaces to homogenize must be of same general... |
11474831 | import sys
import uuid
import gam
from gam.var import *
from gam import controlflow
from gam import display
from gam import gapi
from gam.gapi import directory as gapi_directory
from gam import utils
def delete():
cd = gapi_directory.build()
resourceId = sys.argv[3]
gapi.call(cd.mobiledevices(),
... |
11474860 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.padding import ReplicationPad2d
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1)
class BasicBlock_ss(nn.Module)... |
11474929 | from pathlib import Path
from typing import Optional
import numpy as np
from numpy import ndarray
import onnxruntime
def make_yukarin_s_forwarder(yukarin_s_model_dir: Path, device, convert=False):
session = onnxruntime.InferenceSession(str(yukarin_s_model_dir.joinpath("yukarin_s.onnx")))
def _dispatcher(leng... |
11474983 | class Event(list):
def __call__(self, *args, **kwargs):
for item in self:
item(*args, **kwargs)
class PropertyObservable:
def __init__(self):
self.property_changed = Event()
class Person(PropertyObservable):
def __init__(self, age=0):
super().__init__()
self._age = age
... |
11474988 | pkgname = "awk"
pkgver = "20211104"
pkgrel = 0
_commit="c50ef66d119d87e06a041e5522430265ccdce148"
hostmakedepends = ["byacc"]
pkgdesc = "One true awk"
maintainer = "q66 <<EMAIL>>"
license = "SMLNJ"
url = "https://github.com/onetrueawk/awk"
source = f"https://github.com/onetrueawk/awk/archive/{_commit}.tar.gz"
sha256 = ... |
11474991 | import nvisii
import random
opt = lambda: None
opt.spp = 400
opt.width = 500
opt.height = 500
opt.noise = False
opt.out = '10_light_texture.png'
# # # # # # # # # # # # # # # # # # # # # # # # #
nvisii.initialize(headless = True, verbose = True)
if not opt.noise is True:
nvisii.enable_denoiser()
camera = nvi... |
11475000 | import numbers
from pathlib import Path
from typing import Tuple, List, Optional
import albumentations
import numpy as np
import pandas as pd
import torch
from albumentations.pytorch.functional import img_to_tensor
from torch.utils.data import Dataset
from utils.image import load_image, load_mask
class ImageClassif... |
11475011 | STOP_WORDS = {'Chinese': frozenset(['的'])}
BUILD_IN_MODELS = {
'newsgroups': (
'newsgroups.tar.gz',
'https://raw.githubusercontent.com/Windsooon/cherry_datasets/master/newsgroups.tar.gz',
'25952d9167b86d96503356d8272860d38d3929a31284bbb83d2737f50d23015e',
'latin1',
),
'r... |
11475018 | from django.contrib.auth.decorators import user_passes_test, login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django_filters.views import FilterVie... |
11475103 | import envexamples
from raytracing import *
nRays = 1000000 # Increase for better resolution
minHeight = -5
maxHeight = 5
minTheta = -0.5 # rad
maxTheta = +0.5
# define a list of rays with uniform distribution
inputRays = RandomUniformRays(yMin = minHeight,
yMax = maxHeight,
... |
11475137 | import importlib
from pipeline import msg
from PySide import QtGui
def import_module(modname,packagename=None):
module=None
try:
module=importlib.import_module(modname, packagename)
msg.logMessage(("Imported", modname), msg.DEBUG)
except ImportError as ex:
msg.logMessage('Module cou... |
11475145 | import math
import altair as alt
import pandas as pd
from aequitas.plot.commons.helpers import (
no_axis,
transform_ratio,
calculate_chart_size_from_elements,
to_list,
format_number,
)
from aequitas.plot.commons.tooltips import (
get_tooltip_text_group_size,
get_tooltip_text_disparity_expla... |
11475216 | import collections
import dataclasses
import dis
import functools
import importlib
import inspect
import itertools
import logging
import operator
import sys
import traceback
import types
import typing
from typing import Any
from typing import Dict
from typing import List
from unittest.mock import patch
import torchdyn... |
11475217 | from ajax_datatable.views import AjaxDatatableView
from django.contrib.auth.models import Permission
class PermissionAjaxDatatableView(AjaxDatatableView):
model = Permission
title = 'Permissions'
initial_order = [["app_label", "asc"], ]
length_menu = [[10, 20, 50, 100, -1], [10, 20, 50, 100, 'all']]
... |
11475244 | import heapq
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __eq__(self, other):
return self.val == other.val and self.next == other.next
def __repr__(self):
return '<Node {} {}>'.format(self.val, self.next)
class LinkedList(ListNode):
def ... |
11475252 | import inspect
import warnings
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union, get_type_hints
from pydantic import BaseModel
from pydantic.fields import Undefined
from typing_extensions import TypedDict
from pait.field import BaseField, Depends
from pait.model.core import PaitCoreMode... |
11475270 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import openpyxl
#Get pixel/distance (using ImageJ software) to output actual diameters of circles
dp = 1
accum_ratio = 1
min_dist = 5
p1 = 40
p2 = 30
minDiam = 1
maxDiam = 30
scalebar = 10
min_range = 0
max_range = 100
intervals = 10
ra... |
11475281 | import base64
from datetime import datetime
from sqlite3.dbapi2 import IntegrityError
from django.db import transaction
from django.db.models import Q
from nft_market.api.models import Operation, Asset
from nft_market.services import algorand
from nft_market.utils.constants import (
ASK_PRICE,
BID_PRICE,
S... |
11475287 | import sys
if (sys.version_info[0] == 2 and sys.version_info[:2] >= (2,7)) or \
(sys.version_info[0] == 3 and sys.version_info[:2] >= (3,2)):
import unittest
else:
import unittest2 as unittest
import os
import re
class TestRecipeImports (unittest.TestCase):
def test_imports(self):
import py... |
11475297 | import argparse
import itertools
from base_data_curve import start_jobs
path_model = {}
# Base models
path_model["on"] = "/srv/local1/paxia/exp_logs/public_icoref/ontonotes/checkpoint.bin"
path_model["preco"] = "/srv/local1/paxia/exp_logs/public_icoref/preco/checkpoint.bin"
path_model["en"] = "/srv/local1/paxia/exp_l... |
11475341 | from enum import Enum
from .. import db
from .base import BaseModel
class Disposition(Enum):
NEUTRAL = 'NEUTRAL'
POSITIVE = 'POS'
NEGATIVE = 'NEG'
EDGE = 'EDGE'
DESTRUCTIVE = 'DESTRUCTIVE'
class TestDatum(BaseModel):
__tablename__ = 'test_data'
# fields
test_id = db.Column(db.Intege... |
11475375 | from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy
from django.utils import timezone
from . import deliverytypes
from .abstract_is_admin import AbstractIsAdmin
from .abstract_is_candidate import AbstractIsCand... |
11475420 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('telegraf')
def test_telegraf_running_and_enabled(host):
telegraf = host.service("telegraf")
if host.system_info.distribution not in ['opensuse... |
11475424 | import torch
import numpy as np
from graphics.transform import compute_tsdf
def add_noise_to_grid(grid, config):
# transform to occupancy
occ = torch.clone(grid)
occ[grid < 0] = 1
occ[grid >= 0] = 0
noise = torch.rand(grid.shape)
noise[noise < (1. - config.DATA.noise)] = 0.
noise[noise ... |
11475438 | import torch, sys, random
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class AbsWeighting(nn.Module):
r"""An abstract class for weighting strategies.
"""
def __init__(self):
super(AbsWeighting, self).__init__()
def init_param(self):
r"""Define and i... |
11475548 | import pandas as pd
import sys
import os
import argparse
import time
from consts import NUM_WORKERS
def main():
# Parse command line arguments.
parser = argparse.ArgumentParser()
parser.add_argument("min", type=int, help="Minimum size to search.")
parser.add_argument("max", type=int, help="Maximum siz... |
11475551 | import numpy as np
import pandas as pd
from defect_features.config import conf
class Idmodel:
def getdata(self, pythonProjectPath,project):
data = pd.read_csv(pythonProjectPath+"/defect_features/report/"+project+'__'+conf.modelName+".csv")
trainSet = np.array(data)+0
trainSet = np.insert(t... |
11475565 | import numpy as np
import math
class schur_solver:
def __init__(self):
T_c_rel = []
R_v_rel = []
return
def set_vals(self, T_v_rel, T_c_rel):
self.T_v_rel = T_c_rel #Reversed should be fixed before we open source the code
self.T_c_rel = T_v_rel
return True
... |
11475580 | from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class DistributedDataStoreManagerAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedDataStoreManagerAI')
|
11475582 | from aiokafka import AIOKafkaProducer
import asyncio
loop = asyncio.get_event_loop()
async def send_one():
producer = AIOKafkaProducer(
bootstrap_servers='localhost:9092',
transactional_id="transactional_test",
loop=loop)
# Get cluster layout and topic/partition allocation
await ... |
11475621 | from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from PIL import Image
class Post(models.Model):
"""
The model to store Posts created by users.
Fields-
post_content: The text of the post
posted_by: User who created the post
post_date_post... |
11475711 | from reactive_robot.connectors.mqtt import MqttTopic
def test_mqtt_topic_has_wilcard():
topic1 = MqttTopic("device/+/temperture")
assert topic1.has_wild_card() == True
topic2 = MqttTopic("device/#")
assert topic2.has_wild_card() == True
topic2 = MqttTopic("device/a42b4d93/temperture")
assert... |
11475717 | from __future__ import print_function, division, absolute_import
from collections import OrderedDict
import numpy as np
from typing import List, Union, Tuple
from time import time
import collections
try:
from itertools import izip_longest
except Exception:
from itertools import zip_longest as izip_longest
def ... |
11475721 | import tensorflow as tf
from convLayerRelu import *
def resSkip(x,outMaps,stride):
"""
skip component for res layer for when the resolution changes during stride
number of channels also changes via linear combination
"""
with tf.variable_scope(None, default_name="resSkip"):
return convLayer(x,1,outMaps,stride)
... |
11475722 | from .base import ApibpTest
get_schema_json = """{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"title": {
"type": "string"
},
"content": {
"type": "string"
},
"tags": {
"type": "array",
... |
11475724 | from __future__ import absolute_import
import numpy as np
from keras import backend as K
from keras.layers import Layer
from keras import initializers, regularizers, constraints
def _softmax(x, dim):
"""Computes softmax along a specified dim. Keras currently lacks this feature.
"""
if K.backend() == 'te... |
11475732 | from django.conf.urls import url
from rest_framework.schemas import get_schema_view
from . import views
app_name = "api"
schema_view = get_schema_view(title="Cast API")
urlpatterns = [
url(r"^schema/$", schema_view),
url(r"^$", views.api_root, name="root"),
# image
url(r"^images/?$", views.ImageList... |
11475740 | from . import add, divide, multiply, subtract
from .__about__ import __version__
__all__ = [
"__version__",
"add",
"subtract",
"multiply",
"divide",
]
|
11475774 | import sys
sys.path.append("./lambda/helper/python")
import boto3
import unittest
from moto import mock_s3
from moto import mock_dynamodb2
from helper import S3Helper
from helper import DynamoDBHelper
BUCKET_NAME = "test-bucket"
S3_FILE_NAME = "test_file_name.txt"
TABLE_NAME = "TestsTable"
current_session = boto3.ses... |
11475776 | from dolfin import *
from xii.meshing.make_mesh_cpp import make_mesh
from xii.assembler.average_matrix import curve_average_matrix
from xii.assembler.average_shape import Square
from xii import EmbeddedMesh
import numpy as np
surface_average_matrix = lambda V, TV, bdry_curve: curve_average_matrix(V, TV, bdry_curve, w... |
11475780 | from dataclasses import dataclass
@dataclass
class RiotGameSource:
"""
Example source class for the Riot API
Use it with:
setattr(game.sources, 'riotLolApi', RiotGameSource(gameId=..., platformId=...))
"""
gameId: int = None
platformId: str = None
# Esports games field
gameHa... |
11475829 | import tkinter as tk
class Menubar:
def __init__(self, parent):
font_specs = ("ubuntu", 14)
menubar = tk.Menu(parent.master, font=font_specs)
parent.master.config(menu=menubar)
file_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
file_dropdown.add_command(label="... |
11475858 | def selection_sort(l):
# Outer loop for iterating until second to last index in list
for i in range(len(l)):
# Track least index position
least = i
# Inner loop to handle checking every item for lower number
for j in range(i + 1, len(l)):
# Set least to lowest index i... |
11475867 | def parity(x):
p = 0
while x:
p ^= x&1
x >>= 1
return p
def main():
print 'uint8_t byte_parity[256] = {'
for byte in range(256):
print '{parity},'.format(parity=parity(byte)),
if (byte + 1) % 16 == 0:
print
print '};'
if __name__ == '__main__':
... |
11475878 | import logging
import math
logger = logging.getLogger(__name__)
# Helps visualize the steps of Viterbi.
def log_dptable(V):
s = " " + " ".join(("%7d" % i) for i in range(len(V))) + "\n"
for y in V[0]:
s += "%.15s: " % y
s += " ".join("%.7s" % ("%f" % v[y]) for v in V)
s += "\n"
logger.debug('%s... |
11475943 | import json
from textwrap import dedent
class TestAddHostStoragePartition:
def test_no_args(self, host):
result = host.run('stack add host storage partition')
assert result.rc == 255
assert result.stderr == dedent('''\
error - "host" argument is required
{host ...} {device=string} {size=integer} [mountpo... |
11475954 | import shutil
import glob
import os
import inkml2img
from datetime import datetime
dataPath = 'CROHME_labeled_2016/'
dataMergedPath = 'data_merged/'
targetFolder = 'data_processed/'
logger = open('log.txt', 'w+')
def writeLog(message):
logger.write("[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + s... |
11476003 | from typing import Callable, Tuple
import tensorflow as tf
import tensorflow_model_optimization as tfmot
from absl.testing import parameterized
from test_efficientnet_lite.test_model import TEST_PARAMS
# Disable GPU
tf.config.set_visible_devices([], "GPU")
class TestWeightClusteringWrappers(parameterized.TestCase)... |
11476006 | from tests.unit import unittest
import boto.swf.layer1_decisions
class TestDecisions(unittest.TestCase):
def setUp(self):
self.decisions = boto.swf.layer1_decisions.Layer1Decisions()
def assert_data(self, *data):
self.assertEquals(self.decisions._data, list(data))
def test_continue_as_... |
11476014 | from pylongigetestcase import PylonTestCase
from pypylon import pylon
import unittest
class LoadAndSaveTestSuite(PylonTestCase):
def test_load_and_save(self):
nodeFile = "NodeMap.pfs"
# Create an instant camera object with the camera device found first.
camera = self.create_first()
... |
11476039 | import difflib
file1 = "precheck.txt"
file2 = "postcheck.txt"
diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())
print (''.join(diff),)
|
11476104 | from .universal_datamodule import UniversalDataModule
from .universal_sampler import PretrainingSampler, PretrainingRandomSampler
__all__ = ['UniversalDataModule', 'PretrainingSampler', 'PretrainingRandomSampler']
|
11476108 | from random import random
# This function takes
# - v: value in register
# - a: a scaling value for the logarithm based on Morris's paper
# It returns n(v,a), the approximate_count
def n(v, a):
return a*((1 + 1/a)**v - 1)
# This function takes
# - v: value in register
# - a: a scaling value for the loga... |
11476115 | import argparse
import numpy as np
import os
import pandas as pd
from tqdm import tqdm
import yaml
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SequentialSampler, RandomSampler
from mean_average_precision import MetricBuilder
from models import SiimCo... |
11476125 | from collections import OrderedDict
import torch as T
import torch.nn as nn
from torch._six import container_abcs
import sympy as sp
from .. import utils
__all__ = ['wrapper', 'Sequential', 'Lambda', 'Module', 'MultiSingleInputModule', 'MultiMultiInputModule',
'SingleMultiInputModule']
class _LayerMetho... |
11476143 | from setuptools import setup
setup(
name='devops-pipeline',
packages=['devops_pipeline'],
version='0.1',
description='infrastructure as code, pipeline tool',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/samsquire/devops-pipeline',
include_package_data=True,
insta... |
11476159 | import datetime
import logging
import shlex
import subprocess
import sys
import time
from typing import Sequence, Dict
import click
from lib.amazon import as_client, target_group_arn_for, get_autoscaling_group
from lib.ce_utils import describe_current_release, are_you_sure, logger, \
wait_for_autoscale_state, set... |
11476209 | from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = sp.search(q='weezer', limit=20)
for i, t in enumerate(results['tracks']['items']):
print(' ', i, t['name'... |
11476261 | import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.session import Session
from tqdm.notebook import tqdm
import datetime as dt
from couchers.config import config
from couchers.db import session_scope
from couchers.models import (
Cluster,
C... |
11476289 | import logging
from functools import reduce
from operator import mul as operator_mul
import cfdm
import numpy as np
from . import mixin
from .constructs import Constructs
from .data import Data
from .decorators import _inplace_enabled, _inplace_enabled_define_and_cleanup
from .functions import _DEPRECATION_ERROR_ARG,... |
11476296 | import tensorflow as tf
k= int(tf.__version__.split('.')[0])
if k >=2:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import tensornets as nets
import cv2
import numpy as np
import time
import argparse
import sys
from create_folder import createFolder
tf.disable_v2_behavior()
class YoloObjectDe... |
11476300 | from __future__ import print_function
import time
import numpy as np
from keras.callbacks import Callback
import keras.backend as K
import tensorflow as tf
# NOTE: So far we observed asynchronous feeding for StagingAreaCallback.
# There's a simpligied implementation StagingAreaCallbackFeedDict which uses
# feed_dict... |
11476320 | import os
from preprocessing.caselaw_stat_corpus import preprocess_label_file, count_words
from analysis.caselaw_compare_bm25_dpr import read_in_run_from_pickle, remove_query_from_ranked_list, evaluate_weight
from analysis.diff_bm25_dpr import first_diff_analysis, write_case_lines, get_diff_query_ids, compare_overla... |
11476347 | import re
from collections import defaultdict
p5 = re.compile("(\S+)", re.MULTILINE|re.I)
def length_in_words(sub_element):
tmp2 = p5.findall(sub_element)
return len(tmp2)
f = open("756109104-10-K-19960321.txt")
#f = open("test.txt", 'r')
x = ""
for line in f:
x += line
p1 = re.compile("([^\"])(item\s+7[... |
11476379 | from typing import List
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
return sum(a == b for i, a in enumerate(nums) for b in nums[i + 1 :])
|
11476407 | import sqlite3
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import numpy as np
import pandas as pd
from dash.dependencies import Input, Output
from components import card, tweet
from utils import human_format, get_color_from_score
from pathl... |
11476411 | import pytest
import numpy as np
from . import full_path, remove
@pytest.fixture
def dummy_metadata():
import zarr
from ..metadata import MetaData
fn = full_path("dummy_metadata.zarr")
remove(fn)
g = zarr.open(fn)
data = np.array([1, 1, 1, 1, 0, 0, 1, 1, 1]).astype(bool)
g.create_dataset(... |
11476418 | from __future__ import print_function
import numpy as np
import tensorflow as tf
in_channels = 3 # 3 for RGB, 32, 64, 128, ...
out_channels = 6 # 128, 256, ...
input = np.ones((5,5,in_channels)) # input is 3d, in_channels = 32
# filter must have 3d-shpae x number of filters = 4D
weight_4d = np.ones((3,3,in_channels, ... |
11476430 | from maestro_agent.app_state import ApplicationState
from maestro_agent.services.maestro_api.run import RunApi
from maestro_agent.logging import Logger
from maestro_agent.services.agent.hooks import AgentHooks
from maestro_agent.services.running_test import (
RunningTestThreadsManager,
prepare_for_running,
)
... |
11476436 | import pytest
from qtpy import PYQT5, PYSIDE2
@pytest.mark.skipif(not (PYQT5 or PYSIDE2), reason="Only available in Qt5 bindings")
def test_qtwebchannel():
"""Test the qtpy.QtWebChannel namespace"""
from qtpy import QtWebChannel
assert QtWebChannel.QWebChannel is not None
assert QtWebChannel.QWebChann... |
11476443 | import discograph
from abjad.tools import stringtools
class Test(discograph.DiscographTestCase):
def test_01(self):
entity = discograph.PostgresEntity.get(entity_type=1, entity_id=32550)
roles = ['Alias', 'Member Of']
relations = entity.structural_roles_to_relations(roles)
relatio... |
11476458 | import os
import itertools
import numpy as np
import tensorflow as tf
from utils import *
from collections import Counter
from nltk.tokenize import TreebankWordTokenizer
EOS_TOKEN = "_eos_"
class TextReader(object):
def __init__(self, data_path):
train_path = os.path.join(data_path, "train.txt")
valid_path... |
11476477 | c = 0
j = 0
i = 0
while(j < 10):
i = 0
while (i < 1000000):
b = 1
c = c + b
i = i + 1
j = j + 1
print(c) |
11476490 | import collections
import logging
import math
import sys
import copy
import torch
import torch.distributed as dist
import functools
def flatten_tensors(tensors):
"""
Reference: https://github.com/facebookresearch/stochastic_gradient_push
Flatten dense tensors into a contiguous 1D buffer. Assume tensors ar... |
11476508 | from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import os
import secrets
import encrypted_secrets.conf as secrets_conf
from encrypted_secrets.util import write_secrets
DEFAULT_YAML_PATH = f'{secrets_conf.SECRETS_ROOT}/secrets.yml.enc'
DEFAULT_ENV_PATH = f'{secrets_c... |
11476521 | from .convolution import CFConv
from .dense import Dense
from .embedding import Embedding
from .pooling import PoolSegments
from .rbf import RBFExpansion
from .module import Module
from .distances import EuclideanDistances |
11476541 | import os
# Directories where data and output will be saved.
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data')
OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
SECOND_OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
LO... |
11476623 | from xml.dom import minidom
import numpy as np
from pathlib import Path
import sys
import os
sys.path.append('../')
from utils import plot_stroke
# for flask app
def path_string_to_stroke(path, str_len, down_sample=False):
path_data = path.split(" ")[:-1]
print(len(path_data))
stroke = np.zeros((len(path_... |
11476628 | import sys
import cv2
import numpy as np
def get_all_contours(img):
ref_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(ref_gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 1, 2)
return contours
if __name__=='__main__':
#img = cv2.imread('../images/input_... |
11476629 | load("@bazel_skylib//lib:paths.bzl", "paths")
BUILD_PRELUDE = """
package(default_visibility = ["//visibility:public"])
load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
"""
BUILD_TAR_TEMPLATE = """
pkg_tar(
name = "{}",
deps = [":{}"],
)
"""
def _archive_url(folder, version, archive):
retur... |
11476639 | from django.shortcuts import render
# Create your views here.
from .serializers import UserRegSerializer, SmsSerializer, UserDetailSerializer, LogSerializer, EmailSerializer, \
UserUpdateSerializer
from .models import UserProfile, VerifyCode, UserLoginLog
from rest_framework import mixins, generics, permissions
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.