filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_18334 | from construct import *
from .common import *
"""
Formats: wpm
Version: 0
The path map file describes the pathing in a map.
"""
PathPoint = FlagsEnum(Byte,
can_walk = 0x02,
can_fly = 0x04,
can_build = 0x08,
is_blight = 0x20,
is_ground = 0x40, # or water
is_unknown = 0x80
)
PathMapFile = St... |
the-stack_106_18336 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Factory the instantiates and return the valid (dynamic) module/class
from a machine names.
"""
from models.ModelFactory import ModelFactory
from executor.Execute import Execute
class MachineFactory(ModelFactory):
"""Identify and return the correct machine ... |
the-stack_106_18339 | import os
import string
import random
import json
def store_cpp_format(parsed_json):
file_name = "backend/data/"+''.join(random.choices(string.ascii_letters + string.digits, k=8)) + ".data"
f = open(file_name, "w+")
#load major grade-model
json_file = open("assets/informatik.json")
model = json.lo... |
the-stack_106_18346 | #!/usr/bin/env python3
"""
CPAchecker is a tool for configurable software verification.
This file is part of CPAchecker.
Copyright (C) 2007-2014 Dirk Beyer
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 ob... |
the-stack_106_18348 | #
# 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... |
the-stack_106_18350 | # pylint: disable=protected-access
import hashlib
import logging
import os
import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, Union, List, Tuple
from uuid import UUID, uuid4
from pydantic import BaseModel
from . import protocol
from .file_reader import AsyncFil... |
the-stack_106_18351 | import json
import logging
import random
import string
import requests
import hmac
from jwkest.jwk import rsa_load, RSAKey
from jwkest.jws import JWS
from satosa.internal import InternalData
from ..micro_services.base import ResponseMicroService
from ..response import Redirect
import time
logger = logging.getLogger(_... |
the-stack_106_18353 | from __future__ import print_function
from builtins import input
from builtins import str
from builtins import range
from builtins import object
from future.utils import string_types
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBServerError, InfluxDBClientError
from ast import literal_eval... |
the-stack_106_18355 | import tkinter as tk
import tk_tools
def add_row():
row = [1, 2, 3]
label_grid.add_row(row)
def remove_row():
label_grid.remove_row(0)
if __name__ == '__main__':
root = tk.Tk()
label_grid = tk_tools.LabelGrid(root, 3, ['Column0', 'Column1', 'Column2'])
label_grid.grid(row=0, column=0)
... |
the-stack_106_18357 | from __future__ import absolute_import
from __future__ import print_function
import sys
import requests
import myoperator
import Parameters, DictServer, XMLParser
from PannzerFunctions import Cleaner
class Runner:
def __init__(self, glob, operator_name=None, CHUNK=100, liveData=None, MAXRES=64000, PACKETSIZE=1... |
the-stack_106_18360 | # 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_106_18361 | # coding=utf-8
# 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 writing, software
# dist... |
the-stack_106_18362 | import torch
from torch import nn
from torch.nn import DataParallel
from torch.nn.parallel import DistributedDataParallel
import torch.backends.cudnn as cudnn
# from torchvision import models
import numpy as np
from FastAutoAugment.networks.resnet import ResNet
from FastAutoAugment.networks.pyramidnet import PyramidN... |
the-stack_106_18363 | import pytest
from abi.ERC20 import ERC20
@pytest.fixture(scope="module")
def burner(UniswapLPBurner, alice, receiver):
yield UniswapLPBurner.deploy(receiver, receiver, alice, alice, {"from": alice})
UNISWAP_LP_DAI_ETH = "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11"
UNISWAP_LP_ETH_USDT = "0x0d4a11d5eeaac28ec3f6... |
the-stack_106_18364 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
import unittest
from random import choice
import datetime
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
from frappe.utils import random_string
f... |
the-stack_106_18368 | import discord
import asyncio
from packages.get_server_status import get_server_status, format_dict
from packages.get_news import get_news, format_news
from packages.format_op import format_op
from unidecode import unidecode
from packages.player_info import get_player_info, format_player_info
from packages.live import ... |
the-stack_106_18370 | """
IDE: PyCharm
Project: social-media-bot
Author: Robin
Filename: analyze_tweets.py
Date: 25.01.2020
"""
import json
import os
from collections import defaultdict
from datetime import datetime
import dotenv
import numpy as np
import pandas as pd
import spacy
from matplotlib import pyplot
from term_document_matrix ... |
the-stack_106_18371 | """project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
the-stack_106_18372 | # -*- coding: utf-8 -*-
# Copyright 2018-2019 Streamlit 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 applicabl... |
the-stack_106_18373 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
the-stack_106_18374 | import time
from spaceone.inventory.libs.manager import AWSPowerStateManager
from spaceone.inventory.libs.schema.base import ReferenceModel
from spaceone.inventory.connector.auto_scaling import AutoScalingConnector
from spaceone.inventory.model.auto_scaling import *
class AutoScalingManager(AWSPowerStateManager):
... |
the-stack_106_18375 | def quadrado(b):
return f'{b}^2 = {b**2}'
def eh_par(n):
if n < 2:
return ''
if n % 2 != 0:
n -= 1
print(quadrado(n))
return eh_par(n-2)
def quadrado_de_pares():
x = 1
while x != 0:
x = int(input())
eh_par(x)
quadrado_de_pares()
|
the-stack_106_18376 | # Copyright 2018-2019 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://www.apache.org/licenses/LICENSE-2.0
#
# or in t... |
the-stack_106_18377 | _base_ = './retinanet_r50_fpn_1x_coco.py'
model = dict(
backbone=dict(
norm_cfg=dict(requires_grad=False),
norm_eval=True,
style='caffe',
init_cfg=dict(
type='Pretrained',
checkpoint='open-mmlab://detectron2/resnet50_caffe')))
# use caffe img_norm
img_norm_cfg... |
the-stack_106_18379 | import scipy.ndimage.filters
import pyredner
import numpy as np
import torch
pyredner.set_use_gpu(torch.cuda.is_available())
scene = pyredner.load_mitsuba('scenes/bunny_box.xml')
scene.shapes[-1].vertices += torch.tensor([0, 0.01, 0], device = pyredner.get_device())
args=pyredner.RenderFunction.serialize_scene(\
... |
the-stack_106_18382 | #! -*- coding: utf-8 -*-
# 自定义层
import tensorflow as tf
from bert4keras.backend import keras, K, is_string
from bert4keras.backend import get_all_attributes
# 等价于 from keras.layers import *
locals().update(get_all_attributes(keras.layers))
initializers = keras.initializers
activations = keras.activations
def seque... |
the-stack_106_18383 |
from tensorflow.keras import backend
def get_center_crop_location(source, destination):
"""
Returns the center crop area of source which matches
with the destination size
Returns:
((top_crop, bottom_crop), (left_crop, right_crop))
"""
src_shape = backend.int_shape(source)
... |
the-stack_106_18386 | # -*- coding: utf8 -*-
from __future__ import unicode_literals, division, absolute_import
from __builtin__ import object
import logging
import mock
import pytest
from flexget.plugins.api_t411 import T411RestClient, T411ObjectMapper, T411Proxy, FriendlySearchQuery, ApiError
from flexget.utils.qualities import Requirem... |
the-stack_106_18388 | import os
import base64
import logging
import binascii
import datetime
import traceback
import urllib.request
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.x509.oid import ExtensionOID, NameOID, A... |
the-stack_106_18389 | from __future__ import absolute_import, division, print_function
try:
import boost_adaptbx.boost.python as bp
except Exception:
ext = None
else:
ext = bp.import_ext("fable_ext", optional=True)
from six.moves import range
# compare with fem/utils/string.hpp
def py_fem_utils_unsigned_integer_scan(code, start=0, st... |
the-stack_106_18392 | from spotify_api import API
token = open('token.txt', 'r').read()
api = API(token)
targetUser = api.get_user(input("Enter User ID: "))
playlists = targetUser.get_playlists()
print(f'Playlist Analysis for "{targetUser.name}":\n')
tot = []
for playlist in playlists:
exp = []
for track in playlist.get_tracks():... |
the-stack_106_18393 | import math
import numpy as np
import scipy.interpolate
# motion parameter
L = 1.0 # wheel base
ds = 0.1 # course distanse
v = 1 # (5.4 / 3.6) # velocity [m/s] | [km/h]/3.6 = [m/s]
# MoCap room
# [x_min, x_max, y_min, y_max]
# play_area=[-2.2, 2.3, -1.97, 1.58]
class State:
def __init__(self, x=0.0... |
the-stack_106_18396 | # -*- coding: utf-8 -*-
#
# Copyright © 2011-2013 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""
Spyder base configuration management
As opposed to spyderlib/config.py, this configuration script deals
exclusively with non-GUI features configuratio... |
the-stack_106_18397 | """
Support for information about the German train system.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.deutsche_bahn/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as... |
the-stack_106_18398 | from SBAgent import SBAgent
from SBEnvironment.SBEnvironmentWrapper import SBEnvironmentWrapper
# for using reward as score and 50 times faster game play
env = SBEnvironmentWrapper(reward_type="score", speed=50)
level_list = [1, 2, 3] # level list for the agent to play
dummy_agent = SBAgent(env=env, level_list=level_... |
the-stack_106_18399 | """
SE-ResNet for CIFAR/SVHN, implemented in TensorFlow.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['CIFARSEResNet', 'seresnet20_cifar10', 'seresnet20_cifar100', 'seresnet20_svhn',
'seresnet56_cifar10', 'seresnet56_cifar100', 'seresnet56_svhn'... |
the-stack_106_18401 | """ PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb
This optimizer code was adapted from the following (starting with latest)
* https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py
* https://github.com/NVIDIA/DeepLearningExamples... |
the-stack_106_18404 | import os
from typing import List
import numpy as np
from pathlib import Path
from alchemy.db.fs import raw_data_dir
from alchemy.db.model import (
ClassificationAnnotation,
EntityTypeEnum,
Task,
User,
majority_vote_annotations_query,
)
from alchemy.shared.utils import load_json, load_jsonl, save_... |
the-stack_106_18406 | from collections import namedtuple
import enum
class BlockType(enum.Enum):
# Frames describing CLB features, interconnect, clocks and IOs.
CLB_IO_CLK = 'CLB_IO_CLK'
# Frames describing block RAM initialization.
BLOCK_RAM = 'BLOCK_RAM'
GridLoc = namedtuple('GridLoc', 'grid_x grid_y')
GridInfo = name... |
the-stack_106_18408 | import RPi.GPIO as GPIO
import time
from constants import *
def setInput(pin):
try:
GPIO.setup(pin, GPIO.IN) # set pin as an input pin
except:
GPIO.cleanup()
GPIO.setmode(GPIO.BCM) # BCM pin-numbering scheme from Raspberry Pi
GPIO.setup(pin, GPIO.IN) # set pin as an input p... |
the-stack_106_18409 | # Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/Python/Advanced/remove_geometry.py
import open3d as o3d
import numpy as np
import time
import copy
def visualize_non_blocking(vis):
vis.update_geometry()
vis.poll_events()
vis.update_render... |
the-stack_106_18410 | from unittest import mock
import pytest
from servicex_databinder import configuration
@mock.patch("servicex_databinder.configuration._validate_config")
def test_load_config(mock_validation):
conf = configuration._load_config("config_example_uproot.yml")
assert isinstance(conf, dict)
mock_validation.assert... |
the-stack_106_18411 | # For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from os.path import abspath, join
from flask import Flask
# main application
app = None
log = None
def create_app( cfgfile ):
'''
Create main app object, while ingesting the settings from... |
the-stack_106_18413 | from collections import OrderedDict
import contextlib
from datetime import date, datetime, time, timedelta
from distutils.version import LooseVersion
from functools import partial
import os
import warnings
import numpy as np
from numpy import nan
import pytest
from pandas.compat import PY36, BytesIO, iteritems, map, ... |
the-stack_106_18414 | import sys
import os
import logging
import codecs
from ConfigParser import SafeConfigParser
import ConfigParser
class monitor_configuration():
def __init__(self, configuration_file):
self.folder_localinbox = None
self.folder_localoutbox = None
self.folder_remoteinbox = None
self.fo... |
the-stack_106_18415 | import bme280
from smbus2 import SMBus
import time
import config#config file
import RPi.GPIO as GPIO# this is used for the ligts
from datetime import datetime
if config.ParticulateStatus==1:#we'll only import the sps30 stuff if it is selected in the config file.
from sps30 import SPS30
'''
The Sensors_Functions.py... |
the-stack_106_18417 | from GB_model import *
#Paths to images of real, fake (phantom), and 'no signs' in npy format (each dir contains subdirectories, one for each expert)
# (provide the parent directory to the dataset generator's output for real, fake, and nosign)
real_path = 'data/real'
fake_path = 'data/fake'
nosign_path = 'data... |
the-stack_106_18418 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def unshift(self, value):
node = Node(value)
node.next = self.head
self.head = node
def create_linked_list():
llist = Lin... |
the-stack_106_18419 | """kinto_mpd - A kinto plugin to start/stop playing a playlist in MPD"""
from kinto.core.events import ResourceChanged
from mpd import MPDClient
client = MPDClient()
__version__ = '0.1.0'
__author__ = 'Mathieu Agopian <mathieu@agopian.info>'
__all__ = []
def includeme(config):
print("I am the ElasticSearch MPD... |
the-stack_106_18421 | import json
import re
from collections import OrderedDict
from redash.query_runner import *
# TODO: make this more general and move into __init__.py
class ResultSet(object):
def __init__(self):
self.columns = OrderedDict()
self.rows = []
def add_row(self, row):
for key in row.keys()... |
the-stack_106_18422 | # (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from codecs import open # To use a consistent encoding
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
# Get version info
ABOUT = {}
with open(path.join(HER... |
the-stack_106_18424 | import os
import random
import socket
import subprocess
from contextlib import closing
import six
from dagster_graphql.client.util import parse_raw_log_lines
from dagster_k8s.utils import get_pod_names_in_job, retrieve_pod_logs, wait_for_job_success
from dagster import check
IS_BUILDKITE = os.getenv('BUILDKITE') is ... |
the-stack_106_18425 | from __future__ import annotations
import warnings
import weakref
from collections import defaultdict
from dataclasses import dataclass
from inspect import signature
from typing import TYPE_CHECKING, Callable, Dict, List, Set, Union
from .interactions import Shortcut
from .key_bindings import KeymapProvider
from .tra... |
the-stack_106_18427 | #
# Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
#
# 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/LICE... |
the-stack_106_18429 | """Pytorch based computation backend."""
import math
from collections.abc import Iterable
from functools import wraps
import numpy as _np
import torch
from torch import angle, arange, arccos, arccosh, arcsin, arctanh, argmin
from torch import atan2 as arctan2 # NOQA
from torch import bool as t_bool
from torch import... |
the-stack_106_18430 | from sharpy.plans.acts import ActBase
from sharpy.plans.acts.morph_building import MorphBuilding
from sc2 import UnitTypeId, AbilityId
class MorphUnit(ActBase):
def __init__(self, unit_type: UnitTypeId, ability_type: AbilityId, result_type: UnitTypeId,
cocoon_type: UnitTypeId, target_count: int):
... |
the-stack_106_18433 | """
This script implements an incremental merge strategy, where there is a largeDB,
and a smallDB. In general new PCL dataset files are merged into the smallDB (in
order to speed up the merge). When the smallDB grows to some threshold, say 10%
of the size of the largeDB, then the small and largeDB are merged together.
... |
the-stack_106_18435 | #!/usr/bin/env python3
#
# Copyright (c) 2017, Pivotal Software Inc.
#
from gppylib.commands import base
from gppylib.commands.unix import *
from gppylib.commands.gp import *
from gppylib.gparray import GpArray
from gppylib.gplog import get_default_logger
class GpResGroup(object):
def __init__(self):
sel... |
the-stack_106_18436 |
import os
import cv2
import torch
import datetime
import numpy as np
from torchvision.utils import save_image
import torch.nn.functional as F
from cnn_raccoon import input_images_dict
from cnn_raccoon import images_top_dir, img_relative_path
def tensor_image_converter(tensor):
"""
Converts PyTorch Tensor t... |
the-stack_106_18437 | """
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
the-stack_106_18438 | #
# 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 us... |
the-stack_106_18440 | import json
import re
from ProxyPool.Utls import getPage
from pyquery import PyQuery as pq
class ProxyMetaClass(type):
def __new__(cls, name, bases, attrs):
count = 0
attrs['__CrawlFunc__'] = []
for k, v in attrs.items():
if 'crawl' in k:
attrs['__CrawlFunc__'].a... |
the-stack_106_18443 | import pandas as pd
from .helpers import pandas_to_json
from .consts import profile_col_names
pd.set_option('display.max_columns', 40)
import sys
# data processing
def process_data(inf_dict, friends_dict, profile_dict, lk_dict, final_data_dict):
# convert dicts to pandas dfs
inf_df = pd.DataFrame(inf_dict, ind... |
the-stack_106_18447 | # --------------------------------------------------------
# Pytorch multi-GPU Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Jiasen Lu, Jianwei Yang, based on code from Ross Girshick
# --------------------------------------------------------
from __future__ import absolute_import
... |
the-stack_106_18448 | from __future__ import print_function
import os
import re
import sys
import json
import time
import argparse
import threading
import subprocess
import traceback
from time import sleep
import datetime
from distutils.version import LooseVersion
import pytz
from google.cloud import storage
from google.api_core.exception... |
the-stack_106_18449 | ##
# File: ObjectTransformerTests.py
# Author: J. Westbrook
# Date: 25-Apr-2019
#
# Updates:
#
##
"""
Tests for extractor and updater or selected values from collections (limited tests from mock-data repos)
"""
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__lice... |
the-stack_106_18450 | import torch.nn as nn
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from mm_modules.DCN.modules.deform_conv2d import DeformConv2dPack
class PatchEmbed(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super... |
the-stack_106_18451 | # Copyright 2012 by Wibowo Arindrarto. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Bio.SearchIO pars... |
the-stack_106_18453 | # main.py - makes it possible to run the program from terminal with
# python3 -m sudokusolver
# from sudokusolver import solver
# put solver.run() in main to run
# Run to solve the board
def solve():
rec_solve()
# Recusive function that solves the board
def rec_solve(row=0, col=0):
next_row, next_col = get_... |
the-stack_106_18455 | import random
# Tool Commands
def UserInput () :
UserIn = int(input("Enter your 4 digit guess: "))
return UserIn
def ListToString(s):
str1 = " "
return (str1.join(s))
# Inialize Variables
MasterCode = list(str(random.randrange(1000,9999)))
x = 1
# Inital User Interface
print("You have 10 guesses to... |
the-stack_106_18457 | '''
实验名称:2.4寸LCD液晶显示屏
版本:v1.0
日期:2021.9
作者:01Studio
实验平台:pyWiFi-ESP32-S2P
说明:通过编程实现LCD的各种显示功能,包括填充、画点、线、矩形、圆形、显示英文、显示图片等。
'''
#导入相关模块
from tftlcd import LCD24
import time
#定义常用颜色
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
########################
# 构建2.4寸LCD对象并初始化
######... |
the-stack_106_18459 | import torch
from configs.experiment_config import FNNConfig as experiment_config
from experiments.deep_experiment import DeepExperiment
# Regression task of one-dimensional data
class D_1_2_1_Experiment(DeepExperiment):
def __init__(self):
super(D_1_2_1_Experiment, self).__init__()
def before_test(... |
the-stack_106_18460 | import itertools
import multiprocessing
import runpy
import sys
from os import path as osp
import pytest
def run_main(*args):
# patch sys.args
sys.argv = list(args)
target = args[0]
# run_path has one difference with invoking Python from command-line:
# if the target is a file (rather than a dire... |
the-stack_106_18465 | import abc
import os
import pygame
class Plot(abc.ABC):
def draw(self, game:"Game", surface:"pygame.Surface", plot_dir:str,
update:bool) -> None:
# Make the temporary image file path
file_path = os.path.join(plot_dir, f"{self.__class__.__name__}.png")
# Plot the data
if... |
the-stack_106_18466 | import ee
import time
import sys
ee.Initialize()
STATUS = "Status: {}"
def wait_for_completion(task_descripsion, widget_alert):
"""Wait until the selected process is finished. Display some output information
Args:
task_descripsion (str) : name of the running task
widget_alert (v.Alert) : ale... |
the-stack_106_18467 | pkgname = "pcre"
pkgver = "8.45"
pkgrel = 0
build_style = "gnu_configure"
configure_args = [
"--with-pic",
"--enable-utf8",
"--enable-unicode-properties",
"--enable-pcretest-libedit",
"--enable-pcregrep-libz",
"--enable-pcregrep-libbz2",
"--enable-newline-is-anycrlf",
"--enable-jit",
... |
the-stack_106_18468 | import copy
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
import warnings
import numpy as np
import optuna
from optuna import distributions
from optuna import samplers
from optuna._imports import try_import
from ... |
the-stack_106_18469 | import sys
from sqlalchemy import MetaData, Column, Table, Integer, String, Text, \
Numeric, CHAR, ForeignKey, INTEGER, Index, UniqueConstraint, \
TypeDecorator, CheckConstraint, text, PrimaryKeyConstraint, \
ForeignKeyConstraint, VARCHAR, DECIMAL, DateTime, BigInteger, BIGINT, \
SmallInteger
from sqla... |
the-stack_106_18470 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import time
import shutil
import os
import math
import matplotlib.pyplot as plt
import skimage.io as skio
import skimage.transform as sktf
import skimage.exposure as skexp
import numpy as np
import keras
from keras.layers import Conv2D, UpSampling2D, \
Fl... |
the-stack_106_18471 | """
References:
* https://arxiv.org/abs/2104.13963
* https://github.com/facebookresearch/suncet/blob/master/src/losses.py
Majority of the code comes from here:
https://github.com/facebookresearch/suncet/blob/master/src/losses.py
"""
from . import config
from copy import deepcopy
import tensorflow as tf
def ... |
the-stack_106_18472 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from xnas.search_algorithm.utils import Categorical
from xnas.core.utils import index_to_one_hot, one_hot_to_index
import copy
# SNG + DDPNAS
class MIGO:
"""
Stochastic Natural Gradient for Categorical Distribution
"""
def __init__(sel... |
the-stack_106_18473 | # -*- coding: utf-8 -*-
import scrapy
class scrapykmbab08Spider(scrapy.Spider):
name = "scrapykmbab08"
allowed_domains = ["ganjoor.net"]
if 2 == 1:
start_urls = ["https://ganjoor.net/hojviri/kashfol-mahjoob/kmbab08/sh"]
else:
start_urls = ["https://ganjoor.net/hojviri/kashfol-mahjoob/km... |
the-stack_106_18475 | import json
import sys
import asyncio
from typing import Dict
class DataController(object):
def __init__(self):
self.dataFile: str = "data.json"
self.settingsFile: str = "settings.json"
async def get_data(self) -> Dict[str, any]:
try:
with open(self.dataFile, 'r')... |
the-stack_106_18476 | # from layout2 import Layout
# import layout2
from layout2 import Layout, UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER,\
HORIZONTAL_BAR, VERTICAL_BAR, LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER,\
RTL, RTLPOP
import curses
def test_layout_creation():
board = Layout('src/English.csv')
assert board
def test_layout... |
the-stack_106_18477 | __author__ = "saeedamen" # Saeed Amen
#
# Copyright 2016 Cuemacro
#
# 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 applicabl... |
the-stack_106_18478 | from __future__ import absolute_import
import logging
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django import forms
from .jira import JIRAClient, JIRAError
log = logging.getLogger(__name__)
class JIRAFormUtils(object):
@staticmethod
def ... |
the-stack_106_18479 | # -*- coding: utf-8 -*-
"""
Functions for audio featurization.
"""
import os
import math
import logging
import numpy as np
import soundfile as sf
import librosa
SIGMA_EPS = 1e-12
def stft(frame, _sr, wind, _hop, nfft, synth=False, zphase=False):
if not zphase:
return np.fft.rfft(frame... |
the-stack_106_18480 | #!/usr/bin/env python3
# Copyright 2019 Google 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... |
the-stack_106_18481 | #!/usr/bin/env python
from __future__ import print_function
import logging
import os
import signal
import sys
import uuid
import zipfile
import errno
from buck_logging import setup_logging
from buck_tool import ExecuteTarget, install_signal_handlers, \
BuckStatusReporter
from buck_project import BuckProject, NoBuc... |
the-stack_106_18484 | from chainer_chemistry.dataset.preprocessors.common \
import construct_atomic_number_array
from chainer_chemistry.dataset.preprocessors.common import type_check_num_atoms
from chainer_chemistry.dataset.preprocessors.mol_preprocessor import MolPreprocessor
class AtomicNumberPreprocessor(MolPreprocessor):
"""At... |
the-stack_106_18485 | ######################################################################
# #
# Copyright 2009-2018 Lucas Heitzmann Gabrielli. #
# This file is part of gdspy, distributed under the terms of the #
# Boost Software License - Version ... |
the-stack_106_18486 | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import sys
import unittest
# noinspection PyProtectedMember
from numpy.testing import (assert_allclose, assert_array_less, assert_equal,
assert_raises)
from pyod.models.kde import KDE
from pyod.utils.data impo... |
the-stack_106_18487 | import torch
import torchvision
def yoloParseOutput(model_output, nr_bbox=2):
"""Parses the dense ouput to the predicted values"""
# Get outputs
x_norm_rel = model_output[..., 0:nr_bbox] # Center x
y_norm_rel = model_output[..., nr_bbox:nr_bbox*2] # Center y
h_norm_sqrt = model_output[..., nr_bb... |
the-stack_106_18488 | from __future__ import unicode_literals
import pytest
from prompt_toolkit_dev.application import Application
from prompt_toolkit_dev.application.current import set_app
from prompt_toolkit_dev.input.defaults import create_pipe_input
from prompt_toolkit_dev.key_binding.key_bindings import KeyBindings
from prompt_toolki... |
the-stack_106_18489 | import datetime
import logging
import pytz
import os
import random
import re
import time
from pathlib import Path
import logzero
import pandas as pd
import torch
import torch.nn as nn
import numpy as np
from sklearn.metrics import roc_auc_score
from torch.utils.data import DataLoader
from logzero import logger
from ... |
the-stack_106_18490 | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackernews.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.si... |
the-stack_106_18491 | # -*- coding: utf-8 -*-
from mamonsu.plugins.pgsql.plugin import PgsqlPlugin as Plugin
from .pool import Pooler
class Oldest(Plugin):
OldestXidSql = """
select
greatest(max(age(backend_xmin)), max(age(backend_xid)))
from pg_catalog.pg_stat_activity;
"""
OldestXidSql_bootstrap = """
select public.mamons... |
the-stack_106_18493 | import numpy as np
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
# NOTE: Make sure that the class is labeled 'class' in the data file
tpot_data = np.recfromcsv('PATH/TO/DATA/FILE', delimiter='COLUMN_SEPARATOR', dtype=np.float64)
features = np.delete(tpot_data.view(np.float64).... |
the-stack_106_18494 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import random
import numpy as np
from functools import reduce
from activators import SigmoidActivator, IdentityActivator
# 全连接层实现类
class FullConnectedLayer(object):
def __init__(self, input_size, output_size,
activator):
'''
构造函数
... |
the-stack_106_18495 | from scipy.optimize import fsolve
from matplotlib import cm, rcParams
from shapely import geometry
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math, csv, os
""" ToDo : check if this is equivalent to the G-function for weak coupling """
c = ['#aa3863', '#d97020', '#ef9f07', '#449775',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.