filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_12607 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
the-stack_0_12608 | import os
import warnings
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import gym
import numpy as np
from stable_baselines3.common import base_class
from stable_baselines3.common.callbacks import EvalCallback, BaseCallback
from stable_baselines3.common.vec_env import VecEnv, sync_envs_normaliz... |
the-stack_0_12609 | # -*- coding: utf-8 -*-
countries = {
"ad" : "Andorra",
"ae" : "the United Arab Emirates",
"af" : "Afghanistan",
"ag" : "Antigua and Barbuda",
"ai" : "Anguilla",
"al" : "Albania",
"am" : "Armenia",
"an" : "the Netherlands Antilles",
"ao" : "Angola",
"aq" : "Antarctica",
"ar"... |
the-stack_0_12610 | """
======================================================================
A demo of structured Ward hierarchical clustering on an image of coins
======================================================================
Compute the segmentation of a 2D image with Ward hierarchical
clustering. The clustering is spatially ... |
the-stack_0_12611 | from Tkinter import *
class Test(Frame):
def printit(self):
print(self.hi_there["command"])
def createWidgets(self):
# a hello button
self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH)
... |
the-stack_0_12612 | # -*- coding: utf-8 -*-
import time
from common.base_test import BaseTest
from project import INIT0_PK, INIT1_PK, INIT2_PK, INIT3_PK, INIT4_PK
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import check_that, not_equal_to
SUITE = {
"description": "Operation 'committee_member_deactivate'"
}
@lc... |
the-stack_0_12615 | from flaskapp.models import Question
from test.main.base_classes import BaseUnit
from test.main.utils import test_post_request
class AddQuestionTestCase(BaseUnit):
def test_add_sub_question(self):
# Test valid data
new_question = dict(
question="Is it okay?",
mark=8,
... |
the-stack_0_12616 | import keras.metrics
import tensorflow as tf
def weighted_crossentropy(y_true, y_pred):
class_weights = tf.constant([[[[1., 1., 10.]]]])
unweighted_losses = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_true, logits=y_pred)
weights = tf.reduce_sum(class_weights * y_true, axis=-1)
weighted_lo... |
the-stack_0_12617 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
from scipy.integrate._ivp.ivp import OdeResult
import matplotlib.pyplot as plt
plt.style.use('seaborn')
def solve_ivp(fun, t_span, y0, t_eval=None, dt=0.01):
t0, tf = float(t_span[0]), float(t_span[-1])
if t_eval is not None:
... |
the-stack_0_12618 | #!/usr/bin/env python3
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import io
import re
import string
from test.helper import FakeYDL
from yt_dlp.extractor import YoutubeIE
from y... |
the-stack_0_12619 | # -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming OAuth 2.0 RFC6749.
"""
from __future__ import absolute_import, unicode_literals
import time
import warnings
from oauthlib.common import generate_token
from oauthlib.oauth... |
the-stack_0_12621 | from typing import TYPE_CHECKING, List
from django.conf import settings
from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField
from . import (
GatewayConfig,
authorize,
capture,
get_client_token,
list_client_sources,
process_payment,
refund,
void,
)
GATEWAY_NAME = "... |
the-stack_0_12623 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import inspect
import sys
from math import trunc
def get_locale(name):
"""Returns an appropriate :class:`Locale <arrow.locales.Locale>`
corresponding to an inpute locale name.
:param name: the name of the locale.
"""
... |
the-stack_0_12624 | # Copyright 2020 The MuLT 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 applicable la... |
the-stack_0_12625 | """
Программа для построения интегральных кривых дифференциального уравнения 3-го порядка,
разрешенного относительно производной y''' = f(x, y, y', y'').
Левая кнопка мыши - зафиксировать начальное условие или зафиксировать интегральную кривую.
Правая кнопка мыши - сменить началные условия.
... |
the-stack_0_12627 | from typing import List
from pyrep.objects.dummy import Dummy
from pyrep.objects.joint import Joint
from rlbench.backend.task import Task
from rlbench.backend.conditions import JointCondition
OPTIONS = ['left', 'right']
class TurnTap(Task):
def init_task(self) -> None:
self.left_start = Dummy('waypoint0... |
the-stack_0_12628 | import glob
import os
import ast
import sys
import json
from collections import Counter
sys.setrecursionlimit(1000000)
CODE_DIR = "python_top_code"
OUT_DIR = "stats"
def make_dir_ignore_exists(d):
try:
return os.mkdir(d)
except FileExistsError as E:
pass
def decode_data(data):
try:
... |
the-stack_0_12629 | # qubit number=2
# total number=10
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy a... |
the-stack_0_12630 | import logging
import asyncio
from .http_utils import Request, Response
from .exceptions import (
BadRequestException,
NotFoundException,
TimeoutException,
)
TIMEOUT = 5
# 一个 HTTPServer 对象,需要一个 Router 对象和一个 http_parser 模块,并使用它们来初始化
class HTTPServer(object):
"""
Contains objects that are shared b... |
the-stack_0_12631 | # -*- coding: utf-8 -*-
import logging
from pyramid.interfaces import IRequest
from openregistry.assets.core.includeme import IContentConfigurator
from openregistry.assets.core.interfaces import IAssetManager
from openregistry.assets.basic.models import Asset, IBasicAsset
from openregistry.assets.basic.adapters import... |
the-stack_0_12632 | import base64
import os
import shutil
import string
import sys
import tempfile
import unittest
from datetime import timedelta
from django.conf import settings
from django.contrib.sessions.backends.cache import SessionStore as CacheSession
from django.contrib.sessions.backends.cached_db import \
SessionStore as Cac... |
the-stack_0_12635 | def math():
i_put = int(input())
if 5 < i_put < 2000:
for i in range(1, i_put+1):
if i % 2 == 0:
print(str(i) + '^2 =', i*i)
if __name__ == '__main__':
math()
|
the-stack_0_12637 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''
------------------------------------------------------------
Main entry for ImgReSizer.
.. module:: `Main`
:platform: Unix
:synopsis: Takes configuration json with :py:class: imgresizer.CommandLine and run image processing
.. moduleauthor:: Tumurtogtokh Davaak... |
the-stack_0_12640 | from rest_framework.urlpatterns import format_suffix_patterns
from django.urls import re_path
from api.bookmarks import views as bookmark_views
from api.experiment_groups import views
from constants.urls import GROUP_ID_PATTERN, ID_PATTERN, NAME_PATTERN, USERNAME_PATTERN
groups_urlpatterns = [
re_path(r'^{}/{}/g... |
the-stack_0_12641 | # coding:utf-8
import collections
import csv
import os
from util.log import logger
logger = logger()
class Template(object):
def __init__(self,
base_dic, cmp_dic,
base_cost, cmp_cost,
base_call_times, cmp_call_times,
base_method_thread, cmp_met... |
the-stack_0_12643 | import re
import os
import nltk
import zlib
import codecs
import shutil
import logging
from unidecode import unidecode
from indra.literature.pmc_client import extract_text
from indra.resources.greek_alphabet import greek_alphabet
logger = logging.getLogger(__name__)
class IsiPreprocessor(object):
"""Preprocess a... |
the-stack_0_12644 | import numpy as np
import math
from instrument.geometry.pml import weave
from instrument.geometry import shapes, operations
import os, sys
class Clampcell(object):
def __init__(self, total_height=False):
self.sample_height=28.57 #mm
if total_height is True:
self.sample_height=95.758... |
the-stack_0_12648 | import tensorflow as tf
import numpy as np
import os
import math
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
@tf.function
def one_hot(labels, class_size):
"""
Create one hot label matrix of size (N, C)
Inputs:
- labels: Labels Tensor of shape (N,) representing a ground-trut... |
the-stack_0_12649 | import numpy as np
import torch
from gym import spaces
from torch import nn as nn
from torch.nn import functional as F
def loss_function_factory(loss_function):
if loss_function == "l2":
return F.mse_loss
elif loss_function == "l1":
return F.l1_loss
elif loss_function == "smooth_l1":
... |
the-stack_0_12651 | # Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import os
import re
import types
import copy
import inspect
import traceback
from os.path import expanduser
f... |
the-stack_0_12655 | """"Example usage of BayesianDense layer on MNIST dataset (~1.5% test error). """
import os
import logging
import logging.config
from sklearn.utils import shuffle
from keras.layers import Dense, Input
from keras.models import Model
from keras.datasets import mnist
from keras.optimizers import Adam
import numpy as np
... |
the-stack_0_12656 | __author__ = 'yuxiang'
import datasets
import datasets.kitti_tracking
import os
import PIL
import datasets.imdb
import numpy as np
import scipy.sparse
from utils.cython_bbox import bbox_overlaps
from utils.boxes_grid import get_boxes_grid
import subprocess
import pickle as cPickle
from fast_rcnn.config import cfg
impo... |
the-stack_0_12658 | import DAO
def show_my_courses(student, course_list):
print('\nMy Courses:')
print('#\tCOURSE NAME\tINSTRUCTOR NAME')
attending_dao = DAO.AttendingDAO()
my_courses = attending_dao.get_student_courses(course_list, student.get_email())
i = 1
for course in my_courses:
print(f'{i}\t{course.... |
the-stack_0_12661 | '''
Copyright 2017 The Regents of the University of Colorado
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 appl... |
the-stack_0_12662 | import unittest
import requests
class UnitTestsIbanAPI(unittest.TestCase):
# https://ibanapi.com/get-api
def test_get_get_api(self):
print('test_get_get_api')
params = (
('api_key', 'API_KEY'),
)
iban = "EE471000001020145685"
url = "https://api.ibanapi.co... |
the-stack_0_12663 | """ formatting.py """
import math
from enum import Enum, unique
from typing import Dict, Iterable, List
from .layer_info import LayerInfo
@unique
class Verbosity(Enum):
""" Contains verbosity levels. """
QUIET, DEFAULT, VERBOSE = 0, 1, 2
class FormattingOptions:
""" Class that holds information about ... |
the-stack_0_12664 | import time
import torch
import functools
import argparse
import pyaudio
import wave
import torch.nn.functional as F
from utils import data
from ctcdecode import CTCBeamDecoder
from data.utility import add_arguments, print_arguments
parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_... |
the-stack_0_12665 | """
Put files into the LeoShadow subfolder.
Usage:
1. convert.py <filename> LeoShadow x
This copy file <filename> into the subfolder leoShadow,
adds the prefix, and creates an empty file at the
current location.
After restarting Leo, <filename> will be re-created without
an... |
the-stack_0_12666 | """
Helpers for plugin app
"""
import os
import subprocess
import pathlib
import sysconfig
import traceback
import inspect
import pkgutil
from django.conf import settings
from django.core.exceptions import AppRegistryNotReady
# region logging / errors
class IntegrationPluginError(Exception):
"""
Error that e... |
the-stack_0_12667 | import logging
from botocore import exceptions
import json
import sys
from utils.utils import get_region_name, get_price1, get_price2, handle_limit_exceeded_exception
class Pricing:
"""For getting and returning the price of the Elastic IP's."""
#Filter for get_products pricing api call used to fetch EIP pric... |
the-stack_0_12668 | from collections import deque
d = deque()
for _ in range(int(input())):
line = input().split()
if line[0] == 'append':
d.append(line[1])
elif line[0] == 'pop':
d.pop()
elif line[0] == 'popleft':
d.popleft()
elif line[0] == 'appendleft':
d.appendleft(line[1])
print(*... |
the-stack_0_12669 | from typing import List, Optional
from enum import IntEnum
import numpy as np
import logging
from numpy import random
# The two following classes just make it convenient to select which mutation/recombination/selectoin to use with EA
class Recombination(IntEnum):
NONE = -1 # can be used when only mutation is re... |
the-stack_0_12670 | # Copyright Amazon.com Inc. or its affiliates. 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. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanyin... |
the-stack_0_12671 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='scrapy-autounit',
version='0.0.22',
author='',
author_email='',
description='Automatic unit test generation for Scrapy.',
long_description=long_description,
long_description_conten... |
the-stack_0_12673 | # find the minimum number of coins needed to make up a given amount
# greedy version, not dynamic programming version
denominations = [1, 2, 5, 10, 20, 50, 100, 1000]
# add the largest coin that does not exceed the target amount to the total
def coins_required(amount):
total = 0
coins = []
for denominat... |
the-stack_0_12675 | from typing import List
from secrets import choice
from discord.ext import commands
from .. import config
keywords = ["dm"]
reply = (
"SCAM ALERT! Never accept any trade on DEVNET, SOL on this network are fake and unlimited.",
"SCAM ALERT! PLEASE ONLY DO BUSINESS ON MAGICEDEN OR SOLANART.",
"SCAM ALERT... |
the-stack_0_12676 | # Copyright 2020 . All Rights Reserved.
# Author : Lei Sha
from Hyperparameters import args
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', '-g')
parser.add_argument('--modelarch', '-m')
parser.add_argument('--aspect', '-a')
parser.add_argument('--choose', '-c')
cmdargs = parser.parse_... |
the-stack_0_12678 | import skimage.transform as st
import numpy as np
import matplotlib.pyplot as plt
from skimage import data, feature
def ex_1(): # Hough Transform
image = np.zeros((100, 100))
idx = np.arange(25, 75)
image[idx[::-1], idx] = 255
image[idx, idx] = 255
h, theta, d = st.hough_line(image)
fig, (ax... |
the-stack_0_12682 | from django.utils.encoding import force_unicode
from django.forms.forms import BoundField
from django.utils.html import conditional_escape
def as_p(instance=None, cls=None):
"Returns this form rendered as HTML <p>s."
if not instance and not cls:
return TypeError('as_p takes at least 1 argument (0 give... |
the-stack_0_12683 | import numpy as np
import statistics as stat
from config import *
def process_info(info):
"""
Process a line of info from data source and extract distance
:param info: a line of info. See below for format sample
:return: directory of {node_id (str): distance}
"""
dist = {}
rough_split = ... |
the-stack_0_12685 | # Copyright (c) 2013, Yanky and contributors
# For license information, please see license.txt
import frappe
def execute(filters=None):
columns, data = [], []
columns = get_columns()
article_data = get_article_data(filters)
for article in article_data:
temp_dict = {
"title":article.get("title"),
"isbn":art... |
the-stack_0_12686 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import atexit
import bisect
import multiprocessing as mp
from collections import deque
import cv2
import torch
from detectron2.data import MetadataCatalog
from detectron2.engine.defaults import DefaultPredictor
from detectron2.utils.video_visualize... |
the-stack_0_12687 | from torch.utils.data import TensorDataset
import numpy as np
import logging
import os
import random
import torch
import time
from tqdm import tqdm
from _utils import *
logger = logging.getLogger(__name__)
def load_and_cache_gen_data(args, filename, pool, tokenizer, split_tag, only_src=False, is_sample=False):
#... |
the-stack_0_12689 | import os
from conans import CMake, ConanFile, tools
class QtXlsxWriterConan(ConanFile):
name = "qtxlsxwriter"
license = "MIT"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/dbzhang800/QtXlsxWriter"
description = ".xlsx file reader and writer for Qt5"
top... |
the-stack_0_12690 | """Viessmann ViCare climate device."""
import logging
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
PRESET_ECO,
PRESET_COMFORT,
HVAC_MODE_OFF,
HVAC_MODE_HEAT,
HVAC_MODE_AUTO,
)... |
the-stack_0_12691 | #!/usr/bin/env python3
import argparse
import curses
import sys
import threading
import traceback
from .source_handler import CandumpHandler, InvalidFrame, SerialHandler
should_redraw = threading.Event()
stop_reading = threading.Event()
can_messages = {}
can_messages_lock = threading.Lock()
thread_exception = Non... |
the-stack_0_12692 | # -*- coding: utf-8 -*-
"""
Class definition of YOLO_v3 style detection model on image and video
"""
import os
import time
import logging
import colorsys
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Input
from tensorflow.ker... |
the-stack_0_12694 | import pygame
pygame.init()
def drawGrid(window, cell_width):
for i in range(1,9):
if i%3 == 0:
stroke = 3
else:
stroke = 1
pygame.draw.line(window, (60,113,210), (0, i*cell_width), (WIDTH, i*cell_width), stroke)
pygame.draw.line(window, (69,113,... |
the-stack_0_12695 | # QR Code Reader
# Author: Johnjimy Som
# Created: June 3, 2021
import math
# Initialising hex string
ini_string = "11109D6B2700A000200000E000000000" #sample
#ini_string = input('Please insert a hexcode: ')#import the hex here
# Printing initial string
# Step 1 Step1 QR code(16進数)を読み取る
print (... |
the-stack_0_12696 | # Copyright 2015 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_0_12698 | import os
from bootstrapbase import BootstrapBase
from common.const import Constants
from common.mapr_logger.log import Log
from operations.operationsbase import OperationsBase
from operations.shared import SharedSystem
from operations.csi import CSI
from operations.csinfs import CSINFS
from operations.dataplatform im... |
the-stack_0_12700 | # Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import TestCase
from prereq_map.models.course_title import CourseTitle
from prereq_map.utils.typeahead import get_course_typeahead
import pandas as pd
class TestCourseTitle(TestCase):
def test_titles(self):
... |
the-stack_0_12702 | import random
from perf_load.perf_req_gen import RequestGenerator
class RGSeqReqs(RequestGenerator):
def __init__(self, *args, reqs=list(), next_random: bool=False, **kwargs):
super().__init__(*args, **kwargs)
self._req_idx = -1
self._next_idx = self._rand_idx if next_random else self._seq... |
the-stack_0_12703 | """Tests that the config singleton is working properly
"""
from os.path import expanduser
from os.path import join
from unittest import TestCase
from mock import patch
from testfixtures import TempDirectory
from nose.tools import eq_
from nose.tools import raises
from ..config import get_config_files
from ..config im... |
the-stack_0_12705 | from azureml.core.webservice import AciWebservice
from azureml.core.webservice import Webservice
from azureml.core.image import Image
from azureml.core import Workspace
import sys
import json
# Get workspace
ws = Workspace.from_config()
# Get the Image to deploy details
try:
with open("aml_config/image.json") as ... |
the-stack_0_12706 | #! /usr/bin/env python
"""
Module with contrast curve generation function.
"""
__author__ = 'C. Gomez, O. Absil @ ULg'
__all__ = ['contrast_curve',
'noise_per_annulus',
'throughput',
'aperture_flux']
import numpy as np
import pandas as pd
import photutils
import inspect
from scipy.in... |
the-stack_0_12707 | import tensorflow as tf
from keras.utils.np_utils import to_categorical
from models import Models
from utils import plot
from parameters import batch_size, epochs, batch_size, validation_split, verbose
def main():
# load data
# in the first time, it will be downloaded.
fashion_mnist = tf.keras... |
the-stack_0_12710 | """Methods based on Newton's method."""
import numpy as np
from optimus.types import DirectionMethod
from optimus.types import Function
class Newton(DirectionMethod):
"""Classic Netwon's method. Direction is the inverse hessian times gradient."""
def __call__(
self, parameters: np.ndarray, objective... |
the-stack_0_12711 | import torch
from tvl_backends.nvdec import nv12_to_rgb
def test_nv12_to_rgb():
w = 3840
h = 2160
nv12 = torch.empty(int(w * h * 1.5), device='cuda:0', dtype=torch.uint8)
for i in range(100):
nv12.random_(0, 256)
rgb = nv12_to_rgb(nv12, h, w)
assert rgb.shape == (3, h, w)
|
the-stack_0_12713 | # Copyright 2014 Cloudbase Solutions Srl
#
# 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 l... |
the-stack_0_12714 | import repoInfo
from filechange import ischanged
from colors import logcolors
import pyfiglet
import logger
from utils import initCommands
def init():
info = repoInfo.checkinfoInDir()
url, branch = info
logger.checkdata(url , branch)
if('n' in info):
initCommands(info)
else:
print(f'... |
the-stack_0_12718 | # -*- coding: utf-8 -*-
# Upside Travel, Inc.
#
# 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... |
the-stack_0_12719 | """Config flow for OpenWeatherMap."""
import logging
from pyowm import OWM
from pyowm.exceptions.api_call_error import APICallError
from pyowm.exceptions.api_response_error import UnauthorizedError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_API_KEY,
... |
the-stack_0_12724 | # Copyright 2016 Quantopian, Inc.
#
# 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 writ... |
the-stack_0_12725 | # coding: utf-8
import copy
import random
from models.judge import Judge
from logger.log import logger
from protocol.serialize import send
from common.roomConfig import roomCfg
from common.constDefine import *
class Room:
room_id = -1 # 房间ID
master_id = -1 # 房主ID
room_type = -... |
the-stack_0_12726 | from abc import abstractmethod
from typing import AsyncContextManager, Collection, Container, ContextManager
from eth_typing import BLSPubkey, BLSSignature
from eth2.beacon.types.attestations import Attestation
from eth2.beacon.types.blocks import BeaconBlock
from eth2.beacon.typing import CommitteeIndex, Epoch, Oper... |
the-stack_0_12728 | # Copyright The PyTorch Lightning team.
#
# 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 i... |
the-stack_0_12729 | # Copyright (c) 2022 PaddlePaddle 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 appli... |
the-stack_0_12730 | """Trains a ResNet on the CIFAR10 dataset.
ResNet v1
[a] Deep Residual Learning for Image Recognition
https://arxiv.org/pdf/1512.03385.pdf
ResNet v2
[b] Identity Mappings in Deep Residual Networks
https://arxiv.org/pdf/1603.05027.pdf
"""
from __future__ import print_function
import keras
from keras.layers import Den... |
the-stack_0_12735 | import sqlite3
import csv
import os
os.chdir('C:\OLGA\Python CS50\import_csv_db')
#currentDir = os.getcwd()
#currentFileCSV = currentDir +"\\" + csvFilename
#print(currentFileCSV)
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
c.execute("delete from auth_user_customuser")
c.execute("delete from api_title")... |
the-stack_0_12738 | # For example if user wants to input two equations like
# x1 + 2x2 = 3
# 2x1 + x2 = 3
# it will return a list like [[1,2,3],[2,1,3]]
def get_coefficients_as_list(no_of_unknowns):
all_coefficients = []
for i in range(1,no_of_unknowns+1):
coefficient = []
print("Enter the coefficients for equation ",i)
fo... |
the-stack_0_12739 | from dcmrtstruct2nii.adapters.convert.rtstructcontour2mask import DcmPatientCoords2Mask
from dcmrtstruct2nii.adapters.convert.filenameconverter import FilenameConverter
from dcmrtstruct2nii.adapters.input.contours.rtstructinputadapter import RtStructInputAdapter
from dcmrtstruct2nii.adapters.input.image.dcminputadapter... |
the-stack_0_12742 | # Copyright 2022 Aprendizaje Profundo, All rights reserved.
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# Unless required by applicable law or agreed to in writing, software... |
the-stack_0_12743 | #!/usr/bin/env python2
# test case courtesy of William Schaub (wschaub@steubentech.com)
import os, sys
from socket import *
UNIXSOCKET = sys.argv[1]
server = socket(AF_UNIX,SOCK_STREAM)
server.connect(UNIXSOCKET)
while 1:
data = sys.stdin.readline()
if not data: break
server.sendall(data)
server.close()
|
the-stack_0_12746 | """
dxagent.py
This file contains the core of dxagent
@author: K.Edeline
"""
import sched
import time
import signal
import importlib
from .constants import AGENT_INPUT_PERIOD
from .core.ios import IOManager
from .core.daemon import Daemon
from .input.sysinfo import SysInfo
from .input.bm_input import BMWatcher
... |
the-stack_0_12748 | from googlesearch import search
from pyppeteer import launch
from wplay.utils.helpers import chatbot_image_folder_path
async def Bot(last_Message):
"""
Function to perform instruction as instructed to bot.
"""
print('\n Bot activated')
first_last_Message = "".join(last_Message.split())
simple_... |
the-stack_0_12749 | import copy
import pytest
from ckan_api_client.exceptions import HTTPError
from ckan_api_client.objects import CkanDataset
from ckan_api_client.tests.utils.diff import diff_mappings
from ckan_api_client.tests.utils.generate import generate_dataset
from ckan_api_client.tests.utils.validation import MutableCheckpoint
... |
the-stack_0_12753 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2015 Cristian van Ee <cristian at cvee.org>
# Copyright 2015 Igor Gnatenko <i.gnatenko.brain@gmail.com>
# Copyright 2018 Adam Miller <admiller@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future_... |
the-stack_0_12754 | # -*- coding: utf-8 -*-
"""Defines several tools for monitoring net activity."""
# pylint: disable=F0401, E1101, too-many-lines, wrong-import-order
import logging as _logging
import os as _os
import subprocess as _subprocess
import collections as _collections
import numpy as _np
# pylint: disable=no-name-in-module
from... |
the-stack_0_12755 | from nets.segnet import convnet_segnet
from PIL import Image
import numpy as np
import random
import copy
import os
class_colors = [[0,0,0],[0,255,0]]
NCLASSES = 2
HEIGHT = 416
WIDTH = 416
model = convnet_segnet(n_classes=NCLASSES,input_height=HEIGHT, input_width=WIDTH)
model.load_weights("logs/ep021... |
the-stack_0_12756 | rhacm_versions = [
('1.0', '7'),
('2.0', '7'),
('2.1', '7'),
('2.2', '7'),
('2.3', '7'),
('1.0', '8'),
('2.0', '8'),
('2.1', '8'),
('2.2', '8'),
('2.3', '8'),
]
def test_rhacm_product_version_count(rhacm_product):
assert len(rhacm_product.product_versions()) == 10
def tes... |
the-stack_0_12757 | # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import awkward as ak
np = ak.nplike.NumpyMetadata.instance()
def flatten(array, axis=1, highlevel=True, behavior=None):
"""
Args:
array: Data containing nested lists to flatten.
axis (None or int): If Non... |
the-stack_0_12758 | '''
@Author: Kai Song, ks838 _at_ cam.ac.uk
@Notes : This part gives the constants and parameters.
'''
import numpy as np
# parameters for the system
#the inverse temperature
beta = 0.05 # a.u.
mass = 1.0
# ------ params for propagation ------
dt = 2 * pow(10,-3) # time step
# F is displacement of harmonic o... |
the-stack_0_12759 | import os,time,math,sys,json,re,string,json
import importlib
import get_dataflow
import pandas as pd
import joblib
import json
import requests
import bs4
import lxml
from sklearn.ensemble import RandomForestClassifier
from nltk.tokenize import word_tokenize
stdlib=['string','re','difflib','textwrap','unicodedata','st... |
the-stack_0_12760 | """
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
the-stack_0_12761 | # coding=utf8
"""
Test that the expression parser returns proper Unicode strings.
"""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
# this test case fails because of rdar://129... |
the-stack_0_12762 | from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe:ingredient-list')
class PublicIngredients... |
the-stack_0_12763 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
the-stack_0_12764 | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... |
the-stack_0_12768 | #!/usr/bin/env python3
"""Combine logs from multiple compchain nodes as well as the test_framework log.
This streams the combined log output to stdout. Use combine_logs.py > outputfile
to write to an outputfile."""
import argparse
from collections import defaultdict, namedtuple
import heapq
import itertools
import os... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.