filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_16638 | import logging
import os
import sys
import numpy as np
from pySDC.core import Hooks as hookclass
from pySDC.core.BaseTransfer import base_transfer
from pySDC.helpers.pysdc_helper import FrozenClass
# short helper class to add params as attributes
class _Pars(FrozenClass):
def __init__(self, params):
self... |
the-stack_106_16640 | import collections
import re
from functools import wraps
from grainy.core import int_flags
from ctl.exceptions import PermissionDenied
class expose:
"""
Decorator to expose a ctl plugin's method - permissions will be checked before
method is executed
"""
def __init__(self, namespace, level=Non... |
the-stack_106_16643 | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-ajax-tables',
... |
the-stack_106_16644 | # Bethesda Structs documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 29 15:54:27 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration ... |
the-stack_106_16646 | import unittest
from unittest.mock import patch
from tmc import points
from tmc.utils import load, load_module, reload_module, get_stdout, check_source
from functools import reduce
import os
import os.path
import textwrap
from random import choice, randint
exercise = 'src.own_language'
function = "run"
class OwnLang... |
the-stack_106_16650 | # -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,wcshen1994@163.com
Reference:
[1] Tang J, Qu M, Wang M, et al. Line: Large-scale information network embedding[C]//Proceedings of the 24th International Conference on World Wide Web. International World Wide Web Conferences Steering Committee, 2015: 1067-... |
the-stack_106_16651 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from collections import namedtuple
from struct import Struct
# binary output and reader version
VERSION = 100
SINGLE_BIN_FILE_TYPE = 1
COMBINE_BIN_FILE_TYPE = 2
# used to share header info between writer and reader, with 31 bytes padding for l... |
the-stack_106_16652 | # Copyright (C) 2018-2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import io
import json
import os
import os.path as osp
import shutil
import traceback
import uuid
from datetime import datetime
from distutils.util import strtobool
from tempfile import mkstemp, TemporaryDirectory
import cv2
from django.db.mo... |
the-stack_106_16653 | #
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BERI... |
the-stack_106_16655 | # Copyright 2019 The Johns Hopkins University Applied Physics Laboratory
#
# 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 ... |
the-stack_106_16657 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hpe.com>
#
# 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/... |
the-stack_106_16658 | import sys
import piecash
if sys.version_info.major == 3:
def run_file(fname):
with open(fname) as f:
code = compile(f.read(), fname, "exec")
exec(code, {})
else:
def run_file(fname):
return execfile(fname, {})
if len(sys.argv) == 1:
print("Specify as argument... |
the-stack_106_16659 | # Copyright 2018 The TensorFlow Authors. 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 applica... |
the-stack_106_16660 | #import modules
import heterocl as hcl
from PIL import Image
import math
import os
import numpy as np
import imageio
import time
#need to initiate hcl
hcl.init(init_dtype=hcl.Float())
#path to input image
path = 'lane_fixed.png'
image = imageio.imread(path)
npimage = np.asarray(image)
imgdata = hcl.as... |
the-stack_106_16662 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
the-stack_106_16664 | import abc
import collections
import copy
import confu.schema
import datetime
import logging
import os
import munge
from future.utils import with_metaclass
import vaping.io
from vaping.config import parse_interval
class PluginConfigSchema(confu.schema.Schema):
"""
Configuration Schema for [PluginBase](#plug... |
the-stack_106_16665 | import nose.tools as nt
from .test_embed_kernel import setup, teardown, setup_kernel
TIMEOUT = 15
def test_ipython_start_kernel_userns():
cmd = ('from IPython import start_kernel\n'
'ns = {"tre": 123}\n'
'start_kernel(user_ns=ns)')
with setup_kernel(cmd) as client:
msg_id = cli... |
the-stack_106_16667 | """
Misc tools for implementing data structures
"""
import re
import collections
import numbers
import codecs
import csv
import types
from datetime import datetime, timedelta
from numpy.lib.format import read_array, write_array
import numpy as np
import pandas as pd
import pandas.algos as algos
import pandas.lib as ... |
the-stack_106_16670 | # -*- coding: utf-8 -*-
"""
log
~~~
Implements color logger
:author: Feei <feei@feei.cn>
:homepage: https://github.com/WhaleShark-Team/cobra
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2018 Feei. All rights reserved
"""
import os
import sys
import re
impor... |
the-stack_106_16671 | import os
def solve():
filepath = os.path.join(os.path.dirname(__file__), '042_words.txt')
with open(filepath) as f:
word_value_list = (sum([(ord(i) - 96) for i in word]) for word in f.read().replace('"', '').lower().split(','))
triangle_numbers = [n * (n + 1) / 2 for n in range(1, 1000)]
re... |
the-stack_106_16672 | """
Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py
To create the package for pypi.
1. Change the version in __init__.py, setup.py as well as docs/source/conf.py. Remove the master from the links in
the new models of the README:
(https://huggingface.co/transformers... |
the-stack_106_16673 | import glob
import os
import shutil
from conans import ConanFile, CMake, tools
class CjsonConan(ConanFile):
name = "cjson"
description = "Ultralightweight JSON parser in ANSI C."
license = "MIT"
topics = ("conan", "cjson", "json", "parser")
homepage = "https://github.com/DaveGamble/cJSON"
url ... |
the-stack_106_16675 | import comet_ml
import torch
import torch.nn as NN
import torch.nn.functional as F
import torch.utils.data as data_utils
import deepracing_models.data_loading.proto_datasets as PD
from tqdm import tqdm as tqdm
import deepracing_models.nn_models.LossFunctions as loss_functions
import deepracing_models.nn_models.Models
i... |
the-stack_106_16676 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# PlazaRoute documentation build configuration file, created by
# sphinx-quickstart on Fri Nov 24 12:26:53 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
#... |
the-stack_106_16678 | """Indent new lines automatically when Enter is pressed."""
from __future__ import annotations
import dataclasses
import logging
import re
import tkinter
from functools import partial
from typing import Optional, Tuple
from porcupine import get_tab_manager, tabs
# without this, pressing enter twice would strip all t... |
the-stack_106_16680 | import os
# rlaunch = 'rlaunch --cpu=4 --memory=4096 --gpu=1 --preemptible=no '
datasets = ['cifar-10']
depths = [20]
gpu_id = '0'
batchsize = 256
epoch = 150
exp_dir = '/data/ouyangzhihao/Exp/ICNN/LearnableMask/tb_dir/learnable_mask_baseline/TwoStep_Algorithm2_Sigmoid10_Lmax'
# exp_dir = '/data/ouyangzhihao/Exp/ICNN/... |
the-stack_106_16682 | import pytest
from adventofcode2020.solutions.day08 import Day08PartB
class TestDay08PartB:
instruction_1 = "\n".join(
[
"nop +0",
"acc +1",
"jmp +4",
"acc +3",
"jmp -3",
"acc -99",
"acc +1",
"jmp -4",
... |
the-stack_106_16684 | #!/usr/bin/env python3
import os
import sys
sys.path.append('./_model')
from env import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--distribution',
help='Policy Distribution',
type=str,
default='Normal',
required=False)
parser.add_argument(
'--maxExperiences',
... |
the-stack_106_16686 | import os
import cv2
import torch.utils.data
from PIL import Image
import pandas as pd
import numpy as np
import json
import torch
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.config import cfg
class SYSUDataset(torch.utils.data.Dataset):
CLASSES = ("__background__ ", '... |
the-stack_106_16687 | """A WeatherController Module."""
from masonite.request import Request
from masonite.view import View
from masonite.controllers import Controller
from app.City import City
import requests
class WeatherController(Controller):
"""WeatherController Controller Class."""
def __init__(self, request: Request):
... |
the-stack_106_16688 | """1332_removing_non_null_constraints_on_entity
Revision ID: b2749f31f268
Revises: 4a305e1c8c69
Create Date: 2019-09-24 14:48:54.760496
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b2749f31f268'
down_revision = '4a305e1c8c69'
branch_labels = None
depends_on... |
the-stack_106_16689 | from __future__ import annotations
import math
from typing import NamedTuple, Optional
import numpy as np
import pandas as pd
import torch
from sklearn.model_selection import train_test_split
from chorus import metadata
from chorus.config import DATA_FOLDER
from chorus.geo import Presence
AUDIO_FOLDER = DATA_FOLDER... |
the-stack_106_16690 | #!/usr/bin/env python3
"""William Jenkins
Scripps Institution of Oceanography, UC San Diego
wjenkins [at] ucsd [dot] edu
May 2021
Contains functions, routines, and data recording for DEC model
initialization, training, validation, and inference.
"""
from datetime import datetime
import fnmatch
import os
import pickl... |
the-stack_106_16692 | #Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://bitbucket.org/rptlab/reportlab/history-node/tip/src/reportlab/graphics/renderPS.py
__version__='3.3.0'
__doc__="""Render drawing objects in Postscript"""
from reportlab.pdfbase.pdfmetrics import getFont, stringWidth, unico... |
the-stack_106_16693 | from typing import Union, Dict
import pytest
@pytest.fixture(scope="session")
def client():
"""Return TestClient for the regular OPTIMADE server"""
from .utils import client_factory
return client_factory()(server="regular")
@pytest.fixture(scope="session")
def index_client():
"""Return TestClient ... |
the-stack_106_16694 | import torch
from torch import nn
from torch_geometric.nn import GCNConv
from torch_geometric.nn import GraphConv, TopKPooling
from torch_geometric.nn import global_mean_pool as gap, global_max_pool as gmp
import torch.nn.functional as F
from layers import KGPool
class CharEmbeddings(nn.Module):
def __init__(self,... |
the-stack_106_16695 | _base_ = [
'../../../../_base_/default_runtime.py',
'../../../../_base_/datasets/coco_wholebody_hand.py'
]
evaluation = dict(
interval=10, metric=['PCK', 'AUC', 'EPE'], key_indicator='AUC')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config... |
the-stack_106_16696 | import cupy
def eye(m, n=None, k=0, dtype='d', format=None):
"""Creates a sparse matrix with ones on diagonal.
Args:
m (int): Number of rows.
n (int or None): Number of columns. If it is ``None``,
it makes a square matrix.
k (int): Diagonal to place ones on.
dtype:... |
the-stack_106_16697 | # Minibatch Size
BATCH_SIZE = 32
# Gradient clip threshold
GRAD_CLIP = 10
# Learning rate
LEARNING_RATE = 0.0005
# Maximum number of steps in BPTT
GRAD_STEPS = -1
# Number of epochs for training
NUM_EPOCHS = 10
# do validation every VALIDATION_FREQ iterations
VALIDATION_FREQ = 100
# maximum word length for character mo... |
the-stack_106_16699 | import json
import random
from app import app, db
from app.models import *
from app.module import *
from instance.config import LINE_CHANNEL_ACCESS_TOKEN, LINE_CHANNEL_SECRET_TOKEN
from flask import (
Flask, request, abort
)
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
... |
the-stack_106_16702 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test the nearest matching hex color lookup"""
import time
from random import randint
from colored import fg, bg, attr
from colored.hex import HEX, _xterm_colors
def compare_with_expected( in_hex, expected ):
nearest = HEX( in_hex )
# Look up the matched hex va... |
the-stack_106_16703 | import copy
import datetime
import logging
from math import ceil
import os
from typing import Any, Dict, List, Optional, Text
import rasa.nlu
from rasa.shared.exceptions import RasaException
import rasa.shared.utils.io
import rasa.utils.io
from rasa.constants import MINIMUM_COMPATIBLE_VERSION, NLU_MODEL_NAME_PREFIX
fr... |
the-stack_106_16705 | import json
from collections import defaultdict
class Role(object):
"""
Role class
"""
def __init__(self, Id, Name, Parent):
self.Id = Id
self.Name = Name
self.Parent = Parent
def __roleObjDecoder(obj):
"""
Role decoder
:param obj: object
"""
return Role(... |
the-stack_106_16706 | import asyncio
import logging
import pickle
import aiohttp
from aiohttp import web
import sys
from harmonicIO.stream_connector.stream_connector import StreamConnector
from haste.cloud_gateway.auth import is_valid_login
_secret = None
# std_idle_time is in seconds
HIO_MASTER_HOST = '192.168.1.24'
HIO_MASTER_PORT... |
the-stack_106_16710 | from __future__ import absolute_import
import json
import os
import re
AUTOMATIC = u"automatic"
MANUAL = u"manual"
TEST_TYPES = [AUTOMATIC, MANUAL]
class TestLoader(object):
def initialize(
self,
exclude_list_file_path,
include_list_file_path,
results_manager,
api_titles
... |
the-stack_106_16711 | from unittest.mock import patch
import pytest
from ariane.apps.core import Ariane
class TestAriane:
"""Test the ariane core class."""
@pytest.mark.parametrize(
('intents', 'error'),
[
[[], None],
[['intent1'], None],
[['intent1', 'intent2'], None],
... |
the-stack_106_16713 | """deCONZ binary sensor platform tests."""
from unittest.mock import patch
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.components.deconz.const import (
CONF_ALLOW_CLIP_SENSOR,
CONF_ALLOW_NEW_DEVICES,
CONF_MASTER_GATEWAY,
DOMAIN as DECONZ_DOMAIN,
)
from... |
the-stack_106_16714 | print('Gerador de PA (Advanced)')
print('-=' * 8)
pt = int(input('Primeiro Termo: '))
r = int(input('Razão da PA: '))
c = 10
count = 0
while c != 0:
d = c
while d != 0:
count += 1
d -= 1
print('{} -> '.format(pt), end='')
pt += r
print('PAUSA')
c = int(input('Quantos term... |
the-stack_106_16715 | # -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2018. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
import datetime
import tempfile
import os
import io
import mimetypes
import logging
import resilient
from bs4 import BeautifulSoup
from six import string_types
from cachetools import cache... |
the-stack_106_16716 | import json
from flask import Flask, jsonify, request
from github import Github
from googlesearch import search
try:
from dotenv import load_dotenv
except ImportError:
print("No module named 'google' found")
from os import environ as env
from os.path import join, dirname
dotenv_path = join(dirname(__file__), '... |
the-stack_106_16717 | from matplotlib.pyplot import show
import streamlit as st
import datetime
import yfinance as yf
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
from plotly import graph_objs as go
from plots import plot_history, plot_candles, plot_forecast
symbols = [
'FLRY3.SA',
'ITSA4.... |
the-stack_106_16718 | import requests
import datetime
import urllib.request
import urllib.error
import os
import io
import csv
import pandas as pd
class Job(object):
class Costant(object):
""" An innner class that stores all the constants. """
def __init__(self):
self.DAY_ZERO = datetime.datetime(2020, 1, 22... |
the-stack_106_16720 | # Copyright 2017 Battelle Energy Alliance, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
the-stack_106_16721 | # -*- coding: utf-8 -*-
"""SparkMonitor Jupyter Web Server Extension
This module adds a custom request handler to Jupyter web server.
It proxies the Spark Web UI by default running at 127.0.0.1:4040
to the endpoint notebook_base_url/sparkmonitor
TODO Create unique endpoints for different kernels or spark applications... |
the-stack_106_16723 | from rest_framework import status
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
class BulkCreateModelMixin(CreateModelMixin):
"""
Either create a single or many model instances in bulk by using the
Serializers ``many=True``.
Example:
class Co... |
the-stack_106_16725 | """
Defines functions for double precision 16 character field writing.
"""
import sys
import warnings
from typing import List, Union
from pyNastran.utils.numpy_utils import integer_types
from pyNastran.bdf.cards.utils import wipe_empty_fields
def print_scientific_double(value: float) -> str:
"""
Prints a value... |
the-stack_106_16726 | from tkinter import *
from tkinter.tix import Tk, Control, ComboBox # 升级的控件组包
from tkinter.messagebox import showinfo, showwarning, showerror # 各种类型的提示框
from tkinter import filedialog
from PIL import Image, ImageTk
from tkinter.messagebox import *
import os
import operator
from numpy import *
import cv2
from sklearn... |
the-stack_106_16729 | from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from os.path import expanduser, dirname, join
from glob import glob
from itertools import chain
from subprocess import check_output, CalledProcessError
import sys
import distutils.unixccompiler
__version__ = '1.4.0'
###########... |
the-stack_106_16730 | # _*_ coding:utf-8 _*_
'''
Vectorindexer
'''
from pyspark.sql import SparkSession
from pyspark.ml.feature import VectorIndexer
spark = SparkSession.builder.appName("vectorindexer").getOrCreate()
paths="/export/home/ry/spark-2.2.1-bin-hadoop2.7/data/mllib/"
data=spark.read.format("libsvm").load(paths+"... |
the-stack_106_16731 | # Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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 a... |
the-stack_106_16733 | from keras.models import Sequential
from keras.optimizers import Adam
from ntm_keras.ntm import NeuralTuringMachine as NTM
from ntm_keras.ntm import controller_input_output_shape as controller_shape
from keras.layers.recurrent import LSTM
import numpy as np
def generator():
input_file = "input.npy"
target_file = ... |
the-stack_106_16734 | """Webserver example."""
from aiohttp import web
from aries_staticagent import StaticConnection, utils
from common import config
def main():
"""Create StaticConnection and start web server."""
keys, target, args = config()
conn = StaticConnection(keys, target)
@conn.route("https://didcomm.org/basicm... |
the-stack_106_16735 | import re
import time
import threading
from .utils import is_windows, encode_attr
from .event import Event
from .control import Control
class Connection:
def __init__(self, conn_id):
self.conn_id = conn_id
self.lock = threading.Lock()
self.win_command_pipe = None
self.win_event_pip... |
the-stack_106_16739 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ast
import distutils
from typing import Optional, Text, List, Dict, Any, Union
from absl import logging
from tfx import types
from tfx.components.example_gen import component, base_example_gen_executor
... |
the-stack_106_16740 | """
A Spawner for JupyterHub that runs each user's server in a separate docker container
"""
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
import os
from pprint import pformat
import string
from tarfile import TarFile, TarInfo
from textwrap import dedent
from urllib.parse import urlparse
impo... |
the-stack_106_16742 | __all__ = ["RCNNModelAdapter"]
from icevision.imports import *
from icevision.utils import *
from icevision.metrics import *
from icevision.engines.lightning.lightning_model_adapter import LightningModelAdapter
from icevision.models.torchvision_models.loss_fn import loss_fn
class RCNNModelAdapter(LightningModelAdapt... |
the-stack_106_16743 | # TensorFlow external dependencies that can be loaded in WORKSPACE files.
load("//third_party/gpus:cuda_configure.bzl", "cuda_configure")
load("//third_party/gpus:rocm_configure.bzl", "rocm_configure")
load("//third_party/tensorrt:tensorrt_configure.bzl", "tensorrt_configure")
load("//third_party/nccl:nccl_configure.b... |
the-stack_106_16745 | import os
import csv
from vivarium_cell.data.spreadsheets import load_tsv
FLAT_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "flat")
LIST_OF_FLAT_FILENAMES = (
os.path.join("wcEcoli_genes.tsv"),
os.path.join("wcEcoli_proteins.tsv"),
os.path.join("wcEcoli_environment_molecules.tsv... |
the-stack_106_16749 | # coding=utf-8
# pylint: disable-msg=E1101,W0612
from datetime import datetime
import numpy as np
import pytest
from pandas.compat import lrange, range, zip
from pandas import DataFrame, Index, MultiIndex, RangeIndex, Series
import pandas.util.testing as tm
class TestSeriesAlterAxes(object):
def test_setinde... |
the-stack_106_16752 | #!/usr/bin/python
import LocalMachine
import BlockDeviceHandler
def hum_readable_list_devices(full_info=False):
if full_info:
cmd="lsblk"
exit_code, stdout, stderr = LocalMachine.run_command(cmd)
if exit_code == 0:
print("[CMD] " + str(cmd))
print(stdout)
... |
the-stack_106_16753 | # SPDX-FileCopyrightText: 2019 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
This demo shows the latest icons from a connected Apple device on a TFT Gizmo screen.
The A and B buttons on the CircuitPlayground Bluefruit can be used to scroll through all active
notifications. The ... |
the-stack_106_16756 | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
import os
import sys
import shutil
import unittest
from pathlib import Path
from contextlib import contextmanager
TEST_CONFIG = {
'USE_COLOR': 'False',
'SHOW_PROGRESS': 'False',
'OUTPUT_DIR': 'data.tests',
'SAVE_ARCHIVE_DOT_ORG': 'False',
... |
the-stack_106_16758 | #!/usr/bin/env runaiida
#Not required by AiiDA
import os.path as op
import sys
#AiiDA classes and functions
from aiida.engine import submit
from aiida.orm import load_code, load_node
from aiida.orm import (Str, List, Dict, StructureData, KpointsData, Int, Float)
from aiida_pseudo.data.pseudo.psf import PsfData
from a... |
the-stack_106_16759 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... |
the-stack_106_16760 | from message import *
from database import Database
from global_manager import GlobalManger
from utils import *
from user import User
import socket
import traceback
import threading
class Transfer(threading.Thread):
"""
数据交互类
维持客户端与服务器的数据交互和客户端的消息转发
"""
def __init__(self, sock: socket.sock... |
the-stack_106_16761 | '''
implemented by PyTorch.
'''
import numpy as np
import torch.nn as nn
import torch
from torch.optim import Adam
from typing import Tuple
import os
class ReplayBuffer:
def __init__(self, state_dim, max_size=10000, device=torch.device('cpu')):
self.device = device
self.state_buffer = torch.empty(... |
the-stack_106_16762 | #!/usr/bin/env python
# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Evan Shapiro <eashapir@andrew.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of ... |
the-stack_106_16765 | from collections import defaultdict
adj = defaultdict(list)
with open('input-day12.txt') as file:
for line in file:
line = line.rstrip()
parts = line.split('-')
adj[parts[0]].append(parts[1])
adj[parts[1]].append(parts[0])
paths = []
def trace(path: list[str], curr: str) -> None:
if curr == 'end'... |
the-stack_106_16766 | import os
import sys
sys.path.append(os.getcwd())
from package import *
table_name = 'ods_house'
print('hello world, hello python, hello azkaban')
if __name__ == '__main__':
for day in DAYS:
for rpt_type in RPT_TYPES:
print(day)
print(rpt_type)
sql_day = f"select * f... |
the-stack_106_16767 | import io
import os
import os.path
from typing import IO, Callable, Iterable, Set, Iterator
from itertools import repeat
from zipfile import ZipFile
from collections import OrderedDict
from contextlib import contextmanager
from jawa.cf import ClassFile
from jawa.constants import ConstantPool, ConstantClass
def _walk... |
the-stack_106_16768 | from __future__ import absolute_import, division, print_function
from collections import defaultdict, Iterator, Mapping
from datetime import date, datetime, timedelta
import itertools
import numbers
import warnings
import toolz
from toolz import first, unique, assoc
from toolz.utils import no_default
import pandas as... |
the-stack_106_16770 | import htcondor
def remove_job(self, job_id):
"""
Remove the specified job from the queue
"""
constraint = 'ProminenceType == "job" && ClusterId == %d' % int(job_id)
try:
schedd = htcondor.Schedd()
schedd.edit(constraint, 'ProminenceRemoveFromQueue', 'True')
except:
... |
the-stack_106_16771 | import mysql.connector
from mysql.connector import Error
class DAO:
def __init__(self):
try:
self.conexion = mysql.connector.connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='universidad2'
... |
the-stack_106_16775 | import pytest
from godot.bindings import (
Array,
Node,
Resource,
Area2D,
Vector2,
PoolColorArray,
PoolVector3Array,
PoolVector2Array,
PoolStringArray,
PoolRealArray,
PoolIntArray,
PoolByteArray,
)
class TestArray:
def test_base(self):
v = Array()
... |
the-stack_106_16776 | import json
import os
from .client import Client
from .exceptions import NotChecked
from .xml_parser import XmlParser
class ArfToJson(Client):
def _set_attributes(self):
self.show_failed_rules = self.arg.show_failed_rules
self.show_not_selected_rules = self.arg.show_not_selected_rules
sel... |
the-stack_106_16778 | import datetime
import os
import gym
import numpy
import torch
from games.abstract_game import AbstractGame
class MuZeroConfig:
def __init__(self):
self.seed = 0 # Seed for numpy, torch and the game
### Game
self.observation_shape = (1, 1,
4) # Dimens... |
the-stack_106_16780 | # -*- coding: utf-8 -*-
import importlib
from a4kSubtitles.lib import utils
__all = utils.get_all_relative_entries(__file__)
__display_names = {
'addic7ed': 'Addic7ed',
'bsplayer': 'BSPlayer',
'opensubtitles': 'OpenSubtitles',
'podnadpisi': 'Podnadpisi',
'subscene': 'Subscene',
}
def __set_fn_if_... |
the-stack_106_16781 | import logging
import os
def is_true(value: str) -> bool:
return value.lower() in ['true', '1', 't', 'y', 'yes']
def is_not_blank(value) -> bool:
return value and str.strip(value)
def initialize_logger(output_dir):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create console h... |
the-stack_106_16782 | s = input("Please enter the number of seconds:")
try:
s = int(s)
s0 = s
except ValueError:
print("Please enter a number.")
else:
if s >= 0:
s = int(s)
m,s = (divmod(s,60))
h,m = (divmod(m,60))
d,h = (divmod(h,24))
print(f"{s0} seconds correspond to {d} day, {h} ho... |
the-stack_106_16784 | # -*- coding: utf-8 -*-
"""Forms to edit action content.
EditActionOutForm: Form to process content action_out (Base class)
EditActionIn: Form to process action in elements
"""
from typing import Any, Dict, List, Tuple
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summ... |
the-stack_106_16785 | import datetime
import os
from re import sub
import signal
import subprocess
import time
import uuid
from pathlib import Path
import rq
from fuzzware_pipeline.logging_handler import logging_handler
from rq.worker import WorkerStatus
from .. import naming_conventions as nc
from ..run_target import gen_run_arglist, run... |
the-stack_106_16787 | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option)... |
the-stack_106_16789 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
def check_zero_crossings(st, min_crossings=1.0, config=None):
"""
Check for a large enough density.
This is intended to screen out instrumental failures or resetting.
Value determined empirically from observations on the GeoNet network... |
the-stack_106_16792 | import os
import cv2
import numpy as np
import logging
from colorlog import ColoredFormatter
import pinyin
import timeit
def get_logger(name=__name__):
logger_base = logging.getLogger(name)
logger_base.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
color_formatter = ColoredFormatter(... |
the-stack_106_16793 | from bs4 import BeautifulSoup
from molo.core.models import Main
from molo.polls.tests.base import BasePollsTestCase
from molo.polls.models import (
PollsIndexPage,
Question,
)
class TestMultiSitePolls(BasePollsTestCase):
def test_multi_site_different_polls(self):
# create poll on site 1
... |
the-stack_106_16795 | from __future__ import absolute_import, division, print_function
import math
import numbers
import re
import textwrap
from distutils.version import LooseVersion
import sys
import traceback
from contextlib import contextmanager
import numpy as np
import pandas as pd
import pandas.util.testing as tm
from pandas.api.ty... |
the-stack_106_16796 | from __future__ import print_function
import os
import pathlib as p
import copy
import subprocess
import shutil
import sys
from math import floor
# GRABS .mp4 OR .mkv FILES (preferably called E??.mp4/.mkv) AND TRANSFORMS THEM INTO DASH READY FILES, ORGANISED INTO vid?? DIRECTORIES (for the dash) AND E?? DIRECTORIES (f... |
the-stack_106_16797 | #!/usr/bin/env python3
# GUI for the Python scripts of DARx automation. Made on https://github.com/chriskiehl/Gooey
from gooey import Gooey, GooeyParser
import sys
import module_run
import module_home
import module_rvol
import module_calibrate
import config
import streamtologger
import json
def get_positions(): #gett... |
the-stack_106_16798 | '''
=========================
Automatic Text Offsetting
=========================
This example demonstrates mplot3d's offset text display.
As one rotates the 3D figure, the offsets should remain oriented the
same way as the axis label, and should also be located "away"
from the center of the plot.
This demo triggers ... |
the-stack_106_16800 | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.