content stringlengths 5 1.05M |
|---|
from .sampler import Sampler, SequentialSampler, RandomSampler, SubsetRandomSampler, WeightedRandomSampler, BatchSampler
from .dataset import Dataset, TensorDataset, ConcatDataset, Subset, random_split
from .dataloader import DataLoader
|
import json
import os
import requests
from utils import *
def download_file(url, file_name, out_dir):
"""Downloads file content from url and writes to a file."""
url = url.replace("http", "https")
r = requests.get(url)
content = r.content
XLS_DIR = out_dir + "/XLS/"
if not os.path.exists(XLS_DIR):
os.mkdir(... |
def show_figure():
plt.tight_layout()
plt.show() |
from pyspark.sql import SparkSession, SQLContext, GroupedData
from pyspark.sql.functions import *
from pyspark.sql.functions import date_add as d_add
from pyspark.sql.types import DoubleType
class Transformer:
"""
Realize transformations necessaries in order to create the model.
"""
@staticmethod
... |
import psycopg2
import pytest
from aiopg import IsolationLevel, Transaction
from aiopg.transaction import IsolationCompiler
@pytest.fixture
def engine(make_engine, loop):
async def start():
engine = await make_engine()
async with engine.acquire() as cur:
await cur.execute("DROP TABLE ... |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from framework.utils.common_utils import *
# By default every locator should be CSS
LOCATOR = "locator"
BY = "by"
#Registration Confirmation Page Locator
WELCOME_MESSAGE_LI = by_css("div[class^= 'form']")
|
from multiprocessing.pool import ThreadPool
from threading import Lock
from heapq import heappush, heapreplace
import random
from tqdm import tqdm
import time
n_tasks_done = 0
n_tasks_lock = Lock()
train_rem_lock = Lock()
test_lock = Lock()
def leave_k_out(interaction_dataset, k=1, min_user_interactions=0, last_time... |
from unittest.mock import Mock, patch
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from cms.models import Page, User
from djangocms_navigation.models import MenuContent
from djangocms_navigation.test_utils.app_1.models import TestModel1, Tes... |
import itk
itk.auto_progress(2)
d = itk.Directory.New()
d.Load(".")
n = d.GetNumberOfFiles()
i = 0
while i < n:
print d.GetFile(i)
i = i +1
|
#coding:utf-8
#
# id: bugs.core_4899
# title: GFIX -online: message "IProvider::attachDatabase failed when loading mapping cache" appears in Classic (only) if access uses remote protocol
# decription:
#
# tracker_id: CORE-4899
# min_versions: ['3.0']
# versions: 3.0
# qmid: None
import p... |
import sqlite3
from abc import ABCMeta
class Database:
__metaclass__ = ABCMeta
_sql_table = u'''TABLE DEFINITION'''
def __init__(self, database_file, database_name):
self._connection = sqlite3.connect(database_file, detect_types=sqlite3.PARSE_DECLTYPES)
self._database_name = database_nam... |
# 下拉菜单选项
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("frame learning")
root.iconbitmap('@/home/zuqing/Downloads/apple_icon.xbm')
root.geometry("600x600")
list = [
"周一",
"周二",
"周三",
"周四"
]
print(*list)
clicked = StringVar()
clicked.set(list[0])
drop =OptionMenu(root, cl... |
from alvinchow.grpc.server.exceptions import ( # noqa
GrpcError, BadRequestError, UnauthorizedError, NotFoundError, ServerError
)
|
# Generated by Django 3.0.8 on 2020-09-13 18:18
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('donations', '0011_auto_20200913_1443'),
]
operations = [
migrations.RemoveField(... |
from setuptools import setup
import saverepos
with open("README.rst") as fd:
readme = fd.read()
setup(
name="saverepos",
version=saverepos.VERSION,
py_modules=["saverepos"],
entry_points={"console_scripts": ["saverepos=saverepos:main"]},
author="Javier Llopis",
author_email="javier@llopis... |
import django.forms as forms
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ValidationError
from django.forms.util import flatatt, ErrorDict, ErrorList, ValidationError
from django.conf import settings
import hashlib, re
from recaptcha.client import captcha
from django_utils import requ... |
"""
Calls the zernike.py command for individual optatmo PSF files (lets us see if starting position matters for the resultant fits). Also calls with and without the radial interpolation function.
"""
from __future__ import print_function, division
import glob
import subprocess
import os
import piff
def call_zernike... |
import os
import re
from contextlib import contextmanager
from cProfile import Profile
from functools import wraps
from pstats import Stats
from tornado.template import Template
from ..util import escape
from .state import state
def render_pyinstrument(sessions, timeline=False, show_all=False):
from pyinstrume... |
from zipfile import ZipFile
import glob
from os import walk, path
from os.path import isfile, isdir, join, abspath, splitext, basename, exists, dirname
from os import rename as file_rename
import json
import pprint
import string
import random
import fileinput
import re
import time
from cloakx.utils import log_factory
f... |
DB_PARAMS = {
'provider': 'postgres',
'host': 'localhost',
'database': 'ship',
'user': 'john',
'password': 'password',
}
SECRETE_KEY = 'PLEASE CHANGE THIS TO SOMETHiNG INSANELY DIFICULT THAT IS NOT THIS TEXT because security is awesome' |
from dash import Dash
app = Dash(__name__)
app.title = "Dash Template"
|
#this is part 2 solution, unfortunately not mine :( but it is so amazing that I left it here for learning reasons, to revisit and see how sweet it can be:
from itertools import *
z = 0
while s := input().strip():
a, b = s.split(' | ')
l = ['abcefg', 'cf', 'acdeg', 'acdfg', 'bcdf', 'abdfg', 'abdefg', 'acf', 'abc... |
from unittest import TestCase
from io import StringIO
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from dark.bowtie2 import Bowtie2
from dark.process import Executor
class TestBowtie2(TestCase):
"""
Test the Bowtie2 class.
"""
def testIndexAccession(self):
... |
import os
import sys
import re
import string
from nltk import word_tokenize
from nltk.corpus import stopwords
from util import platform
from cruncher import Cruncher
class Preprocessor:
valid_labels = { 'positive', 'negative', 'neutral', 'unknown' }
urlregex = r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9... |
from django.contrib import admin
# Register your models here.
from pokedex.models import Specie
@admin.register(Specie)
class SpecieAdmin(admin.ModelAdmin):
pass
|
#!/usr/bin/env vpython3
# Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. Al... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Patrick Wieschollek <mail@patwie.com>
from abc import ABCMeta, abstractmethod, abstractproperty
import tensorflow as tf
from tensorpack import *
from tensorpack.tfutils.scope_utils import auto_reuse_variable_scope
"""
I highly suggest to read
http://colah.githu... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 21:28:06 2016
@author: YPC
"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
uu=np.load('mentions.npy')
G = nx.from_edgelist(uu,create_using=nx.DiGraph())
G.remove_edges_from(G.selfloop_edges())
#%%
#%%
if True:
out_deg... |
#!/usr/bin/env python
# coding:utf-8
# Filename: org2md_cli.py
import os
import sys
markdown_title = '#'
org_title = '*'
org_begin_src = '#+BEGIN_SRC'
org_end_src = '#+END_SRC'
md_begin_src = '```'
md_end_src = '```'
markdown_file_suffix = '.markdown'
org_result = '#+RESULTS:'
org_begin_example = '#+begin_examp... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from yandex.cloud.mdb.clickhouse.v1 import resource_preset_pb2 as yandex_dot_cloud_dot_mdb_dot_clickhouse_dot_v1_dot_resource__preset__pb2
from yandex.cloud.mdb.clickhouse.v1 import resource_preset_service_pb2 as yandex_dot_cloud_dot_mdb... |
# Tai Sakuma <tai.sakuma@gmail.com>
import numpy as np
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from altdphi import AltDphi
from .testing import assert_altdphi_equal
##__________________________________________________________________||
def test_with_sample(tbl_scan_ev... |
import time
import Display
import thermocoupler
# 128x64 display with hardware I2C - Setting it up.
screen = Display.Screen(24, 0x3C)
screen.clear()
# Putting start up.
screen.write_text("Cook Assist", "/home/pi/cook_assist/Verdana.ttf", 14)
screen.start()
thermocouple = thermocoupler.Thermocoupl... |
#!/usr/bin/env python
import rospy, sys, os, cv2, pickle
from navigation.graph import Graph
from navigation.graph_search import GraphSearchProblem
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from navigation.srv import *
from navigation.generate_duckietown_map import graph_creator
im... |
import logging
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_control, patch_cache_control
from mayan.apps.rest_api import generics
from .classes import AppImageErrorImage
from .literals import ASSET_IMAGE_TASK_TIMEOUT
from .models import Asset
f... |
# this script generates an input .csv file for
# amazon mturk temporal annotator
# categories are based on your input
# first argument to script is number of videos per category
# imports
import sys
import random
import csv
import re
import json
import math
import requests
from settings import *
# initial variables
c... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Mpileaks(AutotoolsPackage):
"""Tool to detect and report MPI objects like MPI_Requests and... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""
Code for federated learning and ... |
import sys
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_20newsgroups ,fetch_rcv1
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from keras.datasets import imdb
def load_20news():
"""
"""
print 'Loading data...'
newsg... |
n,k = map(int,input().split())
l = list(map(int,input().split()))
ans = []
for i in range(k):
f = i
res = 0
for j in range(i,i+n,k):
res += l[j]
ans.append([f,res])
ans = sorted(ans, key=lambda x:x[1])
final = ans[0][0]
print(final+1) |
from allauth.account.views import PasswordChangeView as allauth_PasswordChangeView
from django.urls import reverse_lazy
class PasswordChangeView(allauth_PasswordChangeView):
success_url = reverse_lazy('home')
|
from gym.envs.mujoco import HalfCheetahEnv
import rlkit.torch.pytorch_util as ptu
from rlkit.data_management.env_replay_buffer import EnvReplayBuffer
from rlkit.launchers.launcher_util import setup_logger
from rlkit.samplers.data_collector import MdpPathCollector, CustomMDPPathCollector
from rlkit.torch.sac.policies i... |
'''
Created on 1 Feb 2019
@author: si
'''
from multiprocessing import Manager
WORK_AROUNG_PY34_BUG = True
class ScoreBoard:
"""
Shared memory to hold values read from sensors.
"""
def __init__(self):
# manager shouldn't be serialised and the scoreboard is passed between processes so
... |
{
'includes': [
'common.gypi',
],
'targets': [
{
'target_name': 'pdf',
'type': 'static_library',
'dependencies': [
'core.gyp:core',
'ports.gyp:ports',
'utils.gyp:utils',
'zlib.gyp:zlib',
],
'include_dirs': [
'../deps/skia/include/confi... |
import pytest
import os
from snapshottest import snapshot
from lmsrvlabbook.tests.fixtures import fixture_working_dir, fixture_working_dir_populated_scoped, fixture_test_file
from lmsrvlabbook.tests.fixtures import fixture_working_dir_env_repo_scoped
from gtmcore.fixtures import ENV_UNIT_TEST_REPO, ENV_UNIT_TEST_BASE,... |
'''
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... |
from zdiscord.util.general.Job import Job
from zdiscord.service.integration.chat.discord.DiscordClient import DiscordBot
from zdiscord.service.Service import Service
import time
from multiprocessing import Process
from zdiscord.util.general.JobQ import RUNNING_JOBS
from zdiscord.util.logging.LogFactory import LogFactor... |
import WebScrapper as WS
import TrieOOP
import dataWriter as DW
WS.mainStarter('radiohead', *WS.getAlbumSongs('radiohead', 'amnesiac'))
data1 = WS.tree.getData(WS.tree)
data2 = WS.tree.getAll(data1)
DW.xlsxWriter(data1, data2, "amnesiac")
|
#! /usr/bin/env python
exec(open('_get_data.py').read())
expenses = [int(_) for _ in data.split()]
for e1 in expenses:
for e2 in expenses:
for e3 in expenses:
if e1+e2+e3==2020:
print(e1*e2*e3)
exit()
|
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------... |
# Copyright (c) 2020, Matthew Waters <matthew@centricular.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version... |
"""global data structure"""
from colour import Color
gen2sorted_indices = {} # Global sorted index for sorting BCs
fitness_plot = None
cloud_plots = set()
canvas2cloud_plot = {} # Figure canvas to figure object
noise = None # Global Noise Table
numBins = 5 # Number of Color Bins for ColorBar
assert numBins > 1
COLO... |
import pathlib
import re
from typing import List, Tuple
def read_inputs(input_file: str) -> Tuple[List[Tuple[int, ...]], List[Tuple[str, int]]]:
with pathlib.Path(input_file).open() as fp:
lines = fp.readlines()
fold_line_regex = re.compile(r"fold along ([xy])=(\d+)\n")
coordinate_regex = re.comp... |
from dataclasses import dataclass
import json
from bs4 import BeautifulSoup
import pytest
from civic_jabber_ingest.models.base import DataModel
from civic_jabber_ingest.utils.xml import get_jinja_template
@dataclass
class MockDataModelBase(DataModel):
first_name: str
last_name: str
@dataclass
class MockDa... |
# Simple
a = 0
a = 1
a = 2
a = 3
a = 4
# Simple function
def test(a):
a = a + 1
return a
b = test(0)
print(b)
# Functions
def ret(a):
b = a + a
return b
def test(a):
v = ret(a)
return v + 'c'
c = 'a'
c = 'b'
d = ret(c)
e = test(d)
print(e)
# Recursion
def plop(a):
if (a == 0):
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/profiler/profile.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf im... |
import dicom
import os
import numpy
from matplotlib import pyplot, cm
import numpy as np
def show_liver_slice(slice, ArrayDicom):
pyplot.figure(dpi=500)
pyplot.axes().set_aspect('equal', 'datalim')
pyplot.set_cmap(pyplot.gray())
x = np.arange(0, ArrayDicom.shape[0], 1)
y = np.arange(0, ArrayDicom.... |
from .fund_event import FundEvent
from ...utilities.params import Events
class ManagementEvent(FundEvent):
"""Fund Management Event Class
Portfolio managers take a fee from the fund at the conclusion of the year.
Typically, this is some percentage of the assets-under-management (AUM) and
another perc... |
#!/usr/bin/env python3
import os, sys
import getpass
import tempfile
import subprocess
"""
Install Snakemake
This script runs the necessary commands to install Snakemake.
"""
def install_snakemake_the_slightly_easier_way():
user = getpass.getuser()
if(user=="root"):
raise Exception("You are root - y... |
'''
Michael Lam 2015
To do: grid: set clim such that 0 is white, not blue,mask data,add zorder
'''
import copy
import sys
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.signal import fftconvolve
import scipy.optimize as optimize
import scipy.interpolate ... |
import logging
import os
import threading
import boto3
from datetime import timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy_utils import create_database, d... |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcim', '0108_add_tags'),
('virtualization', '0016_replicate_interfaces'),
]
operations = [
migrations.RemoveField(
model_name='interface... |
import typing
def main() -> typing.NoReturn:
h, w = map(int, input().split())
grid = [input() for _ in range(h)]
que = [(0, 0)]
inf = 1 << 60
dist = [[inf] * w for _ in range(h)]
dist[0][0] = 0
dyx = [(1, 0), (0, 1)]
def on_grid(y: int, x: int) -> bool:
return 0... |
#! /usr/bin/env python3
import pytest
import numpy as np
from lammps import lammps
from matplotlib.figure import Figure
from matplotlib.axes import Axes
from matplotlib import gridspec
from mock import Mock, patch, call, mock_open, MagicMock
from popoff.lattice_parameters import (get_lattice, differences, run_relaxati... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# ./compute_stats_for_course.py course_id
#
# Textatistic is used to compute some statistics about module items that are Pages.
# For details of the metrics, see https://www.erinhengel.com/software/textatistic/
# and the code at https://github.com/erinhengel/Textatistic/blob... |
import time
from mpf.core.logging import LogMixin
from mpf.tests.MpfGameTestCase import MpfGameTestCase
class BenchmarkEvents(MpfGameTestCase):
def get_options(self):
options = super().get_options()
if self.unittest_verbosity() <= 1:
options["production"] = True
return optio... |
import LevelBuilder
from sprites import *
def render(name,bg):
lb = LevelBuilder.LevelBuilder(name+".plist",background=bg)
lb.addObject(Hero.HeroSprite(x=50, y=41,width=42,height=74))
lb.addObject(Beam.BeamSprite(x=171, y=64,width=128,height=128,angle='0' ,restitution=0.2,static='false',friction=0.5,density=5 ))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from glob import glob
from setuptools import find_packages
from setuptools import setup
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
# Utility function to read the README file.
# Used for the long_description. It's nice, because ... |
import sqlite3
import pandas as pd
import sys
dbname="./matchresult.sqlite3"
tablename = str(sys.argv[1])
#dbname = str(sys.argv[1])
#tablename = str(sys.argv[2])
conn = sqlite3.connect(dbname)
cur = conn.cursor()
# pandasでカレントディレクトリにあるcsvファイルを読み込む
# csvには、1列目にyear, 2列目にmonth, 3列目にdayが入っているとする。
csvname = "result"+t... |
/*
Copyright 2018 Google Inc. All Rights Reserved.
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 ... |
def div42by(divideBy):
return 42 / divideBy
print(div42by(2))
print(div42by(12))
print(div42by(0)) |
from pathlib import Path
import torch
import numpy as np
from ccdproc import cosmicray_lacosmic
from deepCR import deepCR
from collections import OrderedDict
from .backbone import VER_SIMS
from ..core.processor import CsstProcessor, CsstProcStatus
from ..msc import CsstMscImgData
from .. import PACKAGE_PATH
DEEPCR_... |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
version_added: "0.0"
module: repodownloader
short_description:... |
# pyintaller --onefile --icon="filename without quotes" -w first.py
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk,Image
import os
os.system('clear')
root = Tk()
root.title("Syncorized")
root.geometry("1024x480")
# image1 = Image.open("../images/moroccan-flower.png")
# background_image ... |
import sys
sys.path.append("..")
from identify_locus import *
import pytest
import pysam
def test_randomletters_len():
length = 5
letters = randomletters(length)
assert len(letters) == length
def test_randomletters_diff():
length = 10
letters1 = randomletters(length)
letters2 = randomletters(l... |
import sys
sys.path.append("lib")
import unittest
class TestTaskSchedule(unittest.TestCase):
def setUp(self):
pass
def test_add(self):
pass
def test_update(self):
pass
def test_next(self):
pass
def test_ready(self):
pass
def test_waiting(self):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PyCOMPSs Testbench Tasks
========================
"""
# Imports
from pycompss.api.task import task
from pycompss.api.parameter import *
import types
# #### DECORATORS #####
from decorator import decorator
import time
# #### SERIALIZER #####
import sys
if sys.version_i... |
import torch
import numpy as np
from baselines.baselines_configs import configs
class UnetBasedUncertainty:
def __init__(self, model_path, device="cuda", model_str="unet", **kwargs) -> None:
self.device = device
self.model_str = model_str
# load model
self.model = self.load_model(m... |
"""Minimialistic pysketcher example."""
import pysketcher as ps
from pysketcher.backend.matplotlib import MatplotlibBackend
code = ps.Text("print 'Hello, World!'", ps.Point(2.5, 1.5))
code.style.fontsize = 24
code.style.font_family = ps.TextStyle.FontFamily.MONO
code.style.fill_color = ps.TextStyle.Color.GREY
fig = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# License: BSD-3 (https://tldrlegal.com/license/bsd-3-clause-license-(revised))
# Copyright (c) 2016-2021, Cabral, Juan; Luczywo, Nadia
# Copyright (c) 2022, QuatroPe
# All rights reserved.
# =============================================================================
# D... |
VERSION = "1.4.11"
BRANCH = "master"
|
import itertools
import z3
combinations = {
}
def create_combinations():
for length in range(1, 12):
length_combinations = {
0: [],
1: []
}
for combination in itertools.product([0, 1], repeat=length):
result = sum(combination) % 2
... |
""" Module for getting features from cortex """
import os
import time
from functools import reduce
import inspect
import datetime
import pandas as pd
import altair as alt
import LAMP
import cortex.raw as raw
import cortex.primary as primary
import cortex.secondary as secondary
from cortex.feature_types import all_fea... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import numpy as np
import tensorflow as tf
from tensorflow.python import ipu
import unittest
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).absolute().parent.parent))
from normalization import batch_norm
class TestBatchNorm(unittest.Tes... |
### Old
import csv
import pandas as pd
import numpy as np
import zipfile
import os
from datetime import datetime, timedelta
import pickle
import gzip
import time
import timeit
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
retur... |
WEATHER_FILE = "weather.txt"
OUTPUT_STRING_FILE = "say.txt"
INPUT_STRING_FILE = "microphone.txt"
CAMERA_OUTPUT_FILE = "unknown.jpg"
SPEAKER_FILE = "speech.wav"
|
from typing import Optional, Union, Sequence
import numpy as np
import pandas as pd
from evidently.pipeline.column_mapping import ColumnMapping
class DatasetUtilityColumns:
def __init__(self,
date: Optional[str],
id_column: Optional[str],
target: Optional[str],... |
import uuid
import json
from typing import Dict, Union
import requests
import urllib.parse
from django.conf import settings
from django.db import models
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _
class TimestampMixin(models.Model):
"""Abstract model which provides... |
#! /usr/bin/env python3
def main():
x = input()
alpha = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}
print(alpha[x])
if __name__ == '__main__':
main() |
import registros
class registro_superior(registros.registro):
"""ensino superior de registro"""
def __init__(self,nome,id,escola,faculdade):
super().__init__(nome,id)
self._escola = escola
self._faculdade = faculdade
self._saldo *= 2 |
import boto3
import os
import subprocess
s3_client = boto3.client('s3')
def generate_thumbnail(video_path: str, thumbnail_path: str, timestamp: float, width: int, height: int):
print('Calling ffmpeg to seek and extract one frame')
print(f'Timestamp (in seconds): {timestamp}')
result = subprocess.call(
... |
'''
rtreeRange.py
Arguements: -d <datasetFile>, -q <queryFile>, -b <Bvalue>
Author: Yi Liu
Algorithm to solve range queries
'''
# standard libraries
import time
import getopt
import sys
# private libraries
import rtreeBuilder
import Rtree
import scanRange
# range-query algorithm
def rangeQuery(node, queryRange):
... |
import os #Import standart python modules.
import time
import json
import urllib.request
import base64 #Import libraries.
import vk_api
import socketio
from vk_api.utils import get_random_id
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
... |
import pandas as pd
from bs4 import BeautifulSoup as Bs4
from time import sleep
import requests
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path='C:/WebDrivers/chromedriver.exe')
def scroll(driver, timeout):
scroll_pause_time = ti... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 17 10:25:10 2014
@author: Brian
"""
import bbg.globals.constants as bc
import bbg.globals.exceptions as be
import bbg.globals.names as bn
from bbg.utils.misc import format_fld_name
import pandas as pd
from blpapi.event import Event
from collections import ... |
from __future__ import unicode_literals
import datetime
import json
import os
import sys
import pymediainfo
import pdb
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src.helpers as helpers
import src.retriever
# Commit 674ff8a17c3b4fcae8ae508200165bb7e953e8cc added a 'list of... |
"""Measurement records that serialize the tasks, strategies, and measurement results to files."""
from collections import namedtuple
import json
import os
from typing import Tuple
import numpy as np
from alpa.util import to_int_tuple
RECORD_VERSION = "v0.1"
class SearchTask:
"""
The input specification of ... |
import os, dotenv, datetime, platform, nextcord, quickchart, psutil
from nextcord.ext import commands, menus
from util.databases.vote import VoteManage
from util.extras import convert_size
from util.constants import Emojis, Tokens, Client
from util.messages import DeleteMessage
dotenv.load_dotenv()
class VoteButtonM... |
# measure CA(3) and CA(5), CA(7)
# Quantifying Facial Age by Posterior of Age Comparisons
import numpy as np
import os
import cv2
import dlib
import imutils
import csv
import logging
import time
from face_alignment import Face_aligned
from tqdm import tqdm
import pandas as pd
import tensorflow as tf
tf.logging.set_ver... |
import os
import unittest
import numpy as np
from gnes.encoder.audio.vggish import VggishEncoder
class TestVggishEncoder(unittest.TestCase):
@unittest.skip
def setUp(self):
self.dirname = os.path.dirname(__file__)
self.video_path = os.path.join(self.dirname, 'videos')
self.video_bytes... |
import tensorflow as tf
import os.path, time, random
import numpy as np
from agents.rl import RL
from agents.qrm_buffer import ReplayBuffer, PrioritizedReplayBuffer
from agents.dqn_network import create_net, create_target_updates
from common.schedules import LinearSchedule
"""
Interface:
- close(self):
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.