filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_30530 | """
Runtime: 44 ms, faster than 92.75% of Python3 online submissions for Count and Say.
Memory Usage: 14.1 MB, less than 36.67% of Python3 online submissions for Count and Say.
"""
from typing import List
from typing import Optional
class Solution:
def countAndSay(self, n: int) -> str:
if n==1:
... |
the-stack_106_30532 | import sys
import argparse
import numpy as np
import cv2
import time
#from edgetpu.detection.engine import DetectionEngine
from edgetpu.basic.basic_engine import BasicEngine
keypointsMapping = ['Nose', 'Neck', 'R-Sho', 'R-Elb', 'R-Wr', 'L-Sho', 'L-Elb', 'L-Wr', 'R-Hip', 'R-Knee', 'R-Ank', 'L-Hip', 'L-Knee', 'L-Ank', ... |
the-stack_106_30533 | import os
import logging
import base64
import argparse
import asyncio
import sys
# Import server.anchor from the path relative to where the scripts are being executed.
sys.path.insert(1, './server')
from anchor import AnchorHandle
logging.getLogger().setLevel(logging.ERROR)
async def generate_did(seed):
TRUST_ANC... |
the-stack_106_30534 | from __future__ import absolute_import
#
# Partnerbox E2
#
# $Id$
#
# Coded by Dr.Best (c) 2009
# Support: www.dreambox-tools.info
#
# 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... |
the-stack_106_30536 | from django.urls import path
from . import views
urlpatterns = [
path("book/", views.BookViewSet.as_view({'get': 'list'})),
path("book/<int:pk>/", views.BookViewSet.as_view({'get': 'retrieve'})),
path("book/create", views.BookViewSet.as_view({'post': 'create'})),
path("book/<int:pk>/delete", vie... |
the-stack_106_30538 | from statistics import mean
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from collections import deque
import os
import csv
import numpy as np
NUMBER_RUNS = 17
class ScoreAnalyst:
def __init__(self, nb_runs):
self.nb_runs = nb_runs
self.score_csv_root_path = "scores_"
... |
the-stack_106_30540 | import copy
import numpy as np
import random as r
import training
params = {}
# settings related to dataset
params['data_name'] = 'SIR'
params['len_time'] = 257
n = 3 # dimension of system (and input layer)
num_initial_conditions = 5000 # per training file
params['delta_t'] = 0.02
# settings related to saving re... |
the-stack_106_30543 | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
from pathlib import Path
from textwrap import dedent
from pex.resolver import resolve
from pants.backend.codegen.thrift.lib.thrift import Thrift
from pants.ba... |
the-stack_106_30547 | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Batch',
fields=[
(... |
the-stack_106_30550 | from __future__ import print_function, absolute_import, division
import numpy as np
from .cube_utils import iterator_strategy
from .np_compat import allbadtonan
"""
Functions to compute moment maps in a variety of ways
"""
def _moment_shp(cube, axis):
"""
Return the shape of the moment map
Parameters
... |
the-stack_106_30552 | """
=============================================================
Gaussian process regression (GPR) with noise-level estimation
=============================================================
This example shows the ability of the
:class:`~sklearn.gaussian_process.kernels.WhiteKernel` to estimate the noise
level in the d... |
the-stack_106_30553 | # Program to draw Spider Web using Turtle
import turtle
t = turtle.Pen()
colors=['red', 'blue', 'yellow', 'green', 'cyan', 'magenta']
turtle.bgcolor('black')
for i in range(190):
t.pencolor(colors[i%6])
t.width(2)
t.forward(i)
t.right(30)
|
the-stack_106_30554 | # code.py for PiPicoUSBSegaController - https://github.com/thinghacker/PiPicoUSBSegaController
#
# This is a very simple project to take a Raspbery Pi Pico and turn it USB joystick adapter for a 3 or 6 Button Sega Genesis/Megadrive Controller using CircuitPython.
#
# References used while developing this:
# Circuit Py... |
the-stack_106_30557 | # _*_ encoding:utf-8 _*_
from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
import json
from django.contrib.auth.mixins import LoginRequiredMixin
from pure_pagination import Paginator, PageNotAnInteger
from .models import CourseOrg, CityDict, Teacher
from o... |
the-stack_106_30559 | # 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
# distributed under t... |
the-stack_106_30562 | import os
import re
import subprocess
import sys
from datetime import date
from pathlib import Path
from docutils import nodes
from sphinx import addnodes
from sphinx.util import logging
import tox
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.extlinks",
"sphinx.ext.intersphinx",
"sphinx.ext.viewc... |
the-stack_106_30563 | """SCons.Tool.Packaging.tarbz2
The tarbz2 SRC packager.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the righ... |
the-stack_106_30564 | # Karen Byrne 29th April 2018
#https://stackoverflow.com/questions/45862223/use-different-colors-in-scatterplot-for-iris-dataset?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
# I found this code which returns a scatter plot showing the clusters in the data
#I could not get the file to run ... |
the-stack_106_30565 | from contextlib import contextmanager
from itertools import chain
from rdflib.graph import (
ReadOnlyGraphAggregate, Dataset, Graph, ConjunctiveGraph)
from rdflib.paths import Path
from .globals import _dataset_ctx_stack
class DatasetGraphAggregation(ReadOnlyGraphAggregate):
def __init__(self, graphs, stor... |
the-stack_106_30566 | import torch
dependencies = ['torch']
def highres2dnet(*args, **kwargs):
"""
HighRes2DNet in the style of
HighRes3DNet by Li et al. 2017 for T1-MRI brain parcellation
"""
from highresnet import HighRes2DNet
model = HighRes2DNet(*args, **kwargs)
return model
def highres3dnet(*args, pretr... |
the-stack_106_30567 | import numpy
import sys
from Algorithms.Logistic.Executor.logistic_executor import LogisticExecutor
from Utils.conjugate_gradient_method import conjugate_solver
home_dir = '../../../'
sys.path.append(home_dir)
eta_list = [1, 0.1, 0.001, 0.0001, 0.000001]
class DANELogisticExecutor(LogisticExecutor):
def __init_... |
the-stack_106_30568 | # Copyright (c) 2008-2016 Szczepan Faber, Serhiy Oplakanets, Herr Kaste
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use... |
the-stack_106_30573 | from setuptools import setup, find_packages
import platform
from pathlib import Path
import subprocess
import sys
import warnings
assert platform.system() == 'Windows', "Sorry, this module is only compatible with Windows so far."
archstr = platform.machine()
if archstr.endswith('64'):
arch = "x64"
elif archstr.en... |
the-stack_106_30574 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libnetworkit(CMakePackage):
"""NetworKit is a growing open-source toolkit for large-scale ... |
the-stack_106_30575 | #
# Copyright (C) 2001 greg Landrum
#
""" unit testing code for the descriptor COM server
"""
from __future__ import print_function
from rdkit import RDConfig
import unittest
import Parser
from win32com.client import Dispatch
from Numeric import *
class TestCase(unittest.TestCase):
def setUp(self):
print('\n... |
the-stack_106_30579 | import unittest
from checkov.terraform.parser import Parser
from checkov.terraform.evaluation.evaluation_methods.const_variable_evaluation import ConstVariableEvaluation
from checkov.terraform.context_parsers.registry import parser_registry
import dpath.util
import os
class TestConstVariableEvaluation(unittest.TestCa... |
the-stack_106_30581 | import io, os, csv, random, logging
from jacks.infer import LOG
from jacks.jacks_io import createGeneSpec, createSampleSpec, getJacksParser, collateTestControlSamples, writeJacksWResults
from jacks.preprocess import loadDataAndPreprocess
import scipy as SP
def infer_JACKS_meanfc(gene_index, testdata, ctrldata):
re... |
the-stack_106_30584 | """Constants for the Ruckus Unleashed integration."""
import logging
DOMAIN = "ruckus_unleashed"
PLATFORMS = ["device_tracker"]
SCAN_INTERVAL = 180
_LOGGER = logging.getLogger(__name__)
COORDINATOR = "coordinator"
UNDO_UPDATE_LISTENERS = "undo_update_listeners"
CLIENTS = "clients"
|
the-stack_106_30585 | import argparse
import os
from kalasanty.data import prepare_dataset
from tfbio.data import Featurizer
from tqdm import tqdm
def input_path(path):
"""Check if input exists."""
path = os.path.abspath(path)
if not os.path.exists(path):
raise IOError('%s does not exist.' % path)
return path
... |
the-stack_106_30586 | """This module implements an operator acts like a IMU driver when
using the simulator.
The operator attaches an IMU sensor to the ego vehicle, receives
IMU measurements from the simulator, and sends them on its output stream.
"""
import threading
import erdos
from pylot.localization.messages import IMUMessage
from ... |
the-stack_106_30587 | from future import standard_library
standard_library.install_aliases()
import os
import sys
import subprocess
try:
from configparser import ConfigParser
except ImportError:
from configparser import ConfigParser # python 3
COMMIT_INFO_FNAME = 'COMMIT_INFO.txt'
def pkg_commit_hash(pkg_path):
''' Get sho... |
the-stack_106_30589 | # ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018-2021 www.open3d.org
#
# Permission i... |
the-stack_106_30592 | from setuptools import find_packages, setup
import sys
CORE_REQUIREMENTS = [
'numpy>=1.18.0, <1.18.99',
'six>=1.14, <1.14.99',
'future>=0.18.0, <0.18.99'
]
if sys.version_info < (3, 7):
REQUIRES = CORE_REQUIREMENTS + ["dataclasses"]
else:
REQUIRES = CORE_REQUIREMENTS
with open('README... |
the-stack_106_30594 | #!/usr/bin/env python
#
# Copyright (2021) The Delta Lake Project 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 ... |
the-stack_106_30596 | SHIFT = 10
def parse_init(line):
return [c == '#' for c in line[15:].strip()]
def parse_rules(lines):
rules = []
for line in lines:
if line[9] == '#':
rules.append([c == '#' for c in line[:5]])
return rules
def calculate_next_state(state, rules):
# experimentally we never n... |
the-stack_106_30597 | from flask import Flask, jsonify
from gevent.wsgi import WSGIServer
from collections import deque
import logging
import binascii
import decimal
class Logger(object):
""" A dummy file object to allow using a logger to log requests instead
of sending to stderr like the default WSGI logger """
logger = None... |
the-stack_106_30598 | def calculate(operation, first, second):
if operation == '+':
return first + second
elif operation == '-':
return first - second
elif operation == 'x':
return int(first) * second
elif operation == '/':
return first / second
else:
return 'Invalid operation'
de... |
the-stack_106_30600 | # Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
import glob
import json
import logging
import os
from typing import Optional
import click
import click_spinner
from tabulate import tabulate
from taurus_datajob_api import ApiException
from taurus_datajob_api import DataJob
from taurus_datajob_api imp... |
the-stack_106_30601 | from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from . import models, serializers
from jin2gram.users import models as user_models
from jin2gram.users import serializers as user_serializers
from jin2gram.notifications import views as notification_v... |
the-stack_106_30602 | from djcelery_transactions import task
from celery.registry import tasks
from django.db import transaction
from django.test import TransactionTestCase
my_global = []
marker = object()
@task
def my_task():
my_global.append(marker)
tasks.register(my_task)
class SpecificException(Exception):
pass
class Djang... |
the-stack_106_30605 | class Solution(object):
def majorityElement(self, nums): # majority element more than n/2
"""
:type nums: List[int]
:rtype: int
"""
count = 1
major = nums[0] # one other elements kills one major , but major num is bigger than the sum of the others.
for i in r... |
the-stack_106_30606 | from collections import defaultdict
import commonmark
import commonmark.blocks
import commonmark.node
# Mokey-patch the reMaybeSpecial regex to add our table symbol |.
# This regex is apparently just an optimization so this should not
# affect CommonMark parser instances that do not recognize tables.
import re
commo... |
the-stack_106_30608 | from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permis... |
the-stack_106_30610 | # Copyright (c) 2020, NVIDIA CORPORATION. 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_106_30612 | import os
import json
import time
import datetime
import logging
import subprocess
import yaml
import joblib
import numpy as np
import esutil as eu
import fitsio
import ngmix
import healpy as hp
from esutil.pbar import PBar
from metadetect.metadetect import do_metadetect
from metadetect.masking import apply_apodizati... |
the-stack_106_30613 | import jwt
import aiohttp
from datetime import datetime, timedelta, timezone
from jwt.utils import get_int_from_datetime
from auth import GITHUB_PEM_FILE, GITHUB_APP_ID
instance = jwt.JWT()
def new_jwt():
"""Generate a new JSON Web Token signed by RSA private key."""
with open(GITHUB_PEM_FILE, 'rb') as fp:... |
the-stack_106_30617 | import json
import os
import shutil
import tempfile
from notebook.config_manager import BaseJSONConfigManager
def test_json():
tmpdir = tempfile.mkdtemp()
try:
with open(os.path.join(tmpdir, 'foo.json'), 'w') as f:
json.dump(dict(a=1), f)
# also make a foo.d/ directory with multip... |
the-stack_106_30620 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 10:17:03 2017
@author: fella
"""
from numpy import genfromtxt, array
def compute_error_for_given_points(b,m,points):
totalError = 0
for i in range(0, len(points)):
x = points[i,0]
y = points[i,1]
totalError += (y - (m * x + b)) **2
... |
the-stack_106_30621 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
the-stack_106_30622 | import rogue
import pyrogue
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from collections import defaultdict
from collections import Counter
import ctypes
#import line_profiler
import pprint
pp = pprint.PrettyPrinter(indent=2)
nesteddict = lambda:defaultdict(nesteddict)
c_uint = ct... |
the-stack_106_30624 | #!/usr/bin/env python
def main():
np_hidden = 0
np_input = 1
np_output = 2
np_bias = 3
nt_neuron = 0
nt_sensor = 1
num_inputs = 19 + 18 + 0
num_outputs = 12
nodes = []
genes = []
# next_node_id = 1
# def get_next_node_id()
# nonlocal next_node_id
# a = n... |
the-stack_106_30625 | from subprocess import DEVNULL, PIPE, Popen
DEFAULT_FPS = 24
DEFAULT_OUTPUT_PATH = "video.mkv"
class VideoWriter:
def __init__(self, fps=DEFAULT_FPS, output_path=DEFAULT_OUTPUT_PATH):
args = [
"ffmpeg",
"-y",
"-f",
"image2pipe",
"-vcodec",
... |
the-stack_106_30626 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Title '''
__author__ = 'Hiroshi Kajino <KAJINO@jp.ibm.com>'
__copyright__ = 'Copyright IBM Corp. 2020, 2021'
from copy import deepcopy
from .base import POMultivariatePointProcess
from .thinning import MultivariateThinningAlgorithmForPOMixin
from ..pp.snn import SNNBa... |
the-stack_106_30628 | from __future__ import print_function
import sys
import os
import pickle
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import numpy as np
from torch.autograd import Variable
from data import *
from ssd import build_ssd
# from data imp... |
the-stack_106_30630 | from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
from django.template.defaultfilters import pluralize
from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ..... |
the-stack_106_30633 | from ..base import set_base_parser
from ..helper import _chf
def set_hub_push_parser(parser=None):
"""Set the parser for the hub push
:param parser: an optional existing parser to build upon
:return: the parser
"""
if not parser:
parser = set_base_parser()
from .push import mixin_hub_... |
the-stack_106_30634 |
from .imports import *
class AudioPlayer(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self,parent)
layout = QHBoxLayout()
if AUDIO_ENABLED:
self.player = QMediaPlayer()
self.player.setNotifyInterval(10)
self.player.positionChanged.connect... |
the-stack_106_30635 | """
VAE encoder + Classifier
"""
import torch
from torch import nn
import torch.nn.init as init
class View(nn.Module):
def __init__(self, size):
super(View, self).__init__()
self.size = size
def forward(self, tensor):
return tensor.view(self.size)
class Encoder(nn... |
the-stack_106_30637 | import re
import shutil
import subprocess
from libqtile import bar, confreader, images
from libqtile.log_utils import logger
from libqtile.widget import base
RE_VOL = re.compile(r"Playback\s[0-9]+\s\[([0-9]+)%\]\s\[(on|off)\]")
class ALSAWidget(base._Widget, base.PaddingMixin, base.MarginMixin):
"""
The wid... |
the-stack_106_30638 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__doc__ = """\
A collection of functions for obfuscating code.
"""
import os
import sys
import tokenize
import keyword
import sys
import unicodedata
from random import shuffle, choice
from itertools import permutations
# Import our own modules
from . import analyze
from ... |
the-stack_106_30639 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
一些有用的class和function: 所有路径为绝对路径
+ stream_tee(object): 日志记录
+ get_subdir(): 获取子文件夹列表
+ decode_imgurl(url, cookie): 解析微博imgref url
+ download_image_from_list: 从图片链接列表下载图片, 储存在user_id/images/fromlist/
+ repair_image_list(imglist_file): 修复图片链接列表中未解析链接
"... |
the-stack_106_30644 | import torch
import torch.nn.functional as F
from torch import nn
import torch.distributed as dist
import numpy as np
@torch.no_grad()
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
if target.numel() == 0:
return [torch.zeros([], device=output.devi... |
the-stack_106_30645 | import json
import _pickle as pickle
from wordclasses import Verb
from grammarconstants import PAST,PRESENT,FUTURE,MALE,FEMALE,NEUTER,SINGULAR,PLURAL,FIRST,SECOND,THIRD,PERFECT,IMPERFECT
def inputS(s):
st = input(s)
if st == 'x':
sys.exit()
with open('verbs.pkl','rb+') as f:
obj = pickle.load(f)
... |
the-stack_106_30647 | import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import zipfile
import cv2
from mss import mss
import pyautogui
import time
import PySimpleGUI as sg
from collections import defaultdict
from io import StringIO
from matplot... |
the-stack_106_30648 | # coding: utf-8
"""
@Topic:
@Date: 2021/1/29
@Author: other.z
@Copyright(C): 2020-2023 other.z Inc. All rights reserved.
"""
import json
import ply.lex
class LexerError(Exception):
pass
class Lexer:
def tokenize(self, string, debug=False):
"""
Maps a string to an iterator over to... |
the-stack_106_30649 | import logging
import click
from pathlib import Path
import pandas as pd
import numpy as np
import geopy.distance
import datetime
import pytz
from src.filename import BOOKING_PREPROCESSED, PARTICIPANT_PREPROCESSED, TEST_PREPROCESSED, TRAIN_TRANSFORMED, TRAIN, TEST
def cal_dist(row):
lat_x, long_x, lat_y, long_y ... |
the-stack_106_30651 | import os
import sys
import requests
from tqdm import tqdm
if len(sys.argv) != 2:
print('You must enter the model name as a parameter, e.g.: download_model.py 124M')
sys.exit(1)
model = sys.argv[1]
subdir = os.path.join('models', model)
if not os.path.exists(subdir):
os.makedirs(subdir)
subdir = subdir.r... |
the-stack_106_30652 | # Contain plan headers for testing of queue execution for BMM beamline
# Plans: mv, xafs, change_edge, shb_close_plan, set_slot
from ophyd.sim import hw
from bluesky.plans import count, scan
from bluesky.plan_stubs import mv # noqa: F401
from bluesky_queueserver.manager.profile_tools import set_user_ns
det1, det2,... |
the-stack_106_30654 | import sys
import yaml
import argparse
import re
import pandas as pd
import subprocess
import shlex
from pathlib import Path
from collections import defaultdict
from collections import namedtuple
sys.path.append(str(Path.home().joinpath('wrmXpress/modules')))
from get_wells import get_wells
from get_image_paths impor... |
the-stack_106_30655 | from time import perf_counter as tpc
import nevergrad as ng
from opt import Opt
class OptNB(Opt):
"""Minimizer based on the NoisyBandit method from "nevergrad" package."""
name = 'NB'
def prep(self, evals=1.E+7):
self.evals = int(evals)
return self
def solve(self):
t = tpc... |
the-stack_106_30658 | """
Classes to handle scopeout's interactions with the filesystem,
particularly data export/import.
"""
import logging
import os
from csv import *
from datetime import datetime
from collections import Iterable
from scopeout.models import Waveform
FILE_HEADER = 'Waveforms generated by ScopeOut Data Acquisition Tool.... |
the-stack_106_30659 | """
A script to derive a national PV site list.
- First Authored 2018-11-22
- Owen Huxley <othuxley1@sheffield.ac.uk
"""
import pandas as pd
import numpy as np
import time as TIME
from datetime import datetime
import picklecache
import os
import re
import io
import codecs
import pickle
import sys
from configparser im... |
the-stack_106_30660 | # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
from datadog_api_client.v1.model_uti... |
the-stack_106_30661 | # Python 4chan Downloader
import argparse
import os
import re
import time
import wget
from straight.plugin import load
from plugins.ChanParserInterface import ChanParserInterface
from datetime import datetime
class PFourChanDL(object):
def __init__(self):
self.params = None
def main(self):
... |
the-stack_106_30662 | import discord
from discord.ext import commands
#import youtube_dl
import os
from pytube import YouTube
token = open("token.txt", "r").read()
mainaccid=open("mainaccid.txt", "r").read()
bot = commands.Bot(command_prefix='!joker ')
@bot.event
async def on_ready():
print('We have logged in as {0.user}... |
the-stack_106_30663 | '''
Created on Nov 1, 2014
@author: ehenneken
'''
from __future__ import absolute_import
# general module imports
import sys
import os
import operator
from itertools import groupby
from flask import current_app
from .utils import get_data
from .utils import get_meta_data
__all__ = ['get_suggestions']
def get_sugge... |
the-stack_106_30666 | #!/usr/bin/env python
"""
Goal:
* Interact with XMR.to.
xmrto_wrapper create-order --destination 3K1jSVxYqzqj7c9oLKXC7uJnwgACuTEZrY --btc-amount 0.001
How to:
* General usage
- `xmrto_wrapper create-order --destination 3K1jSVxYqzqj7c9oLKXC7uJnwgACuTEZrY --btc-amount 0.001`
- `xmrto_wrapper create-order --... |
the-stack_106_30667 | import asyncio
import threading
from .evaluator import _ConfigEvaluation, _Evaluator
from .statsig_network import _StatsigNetwork
from .statsig_logger import _StatsigLogger
from .dynamic_config import DynamicConfig
from .statsig_options import StatsigOptions
from .version import __version__
RULESETS_SYNC_INTERVAL = 10... |
the-stack_106_30669 | # -*- coding: utf-8 -*-
'''
Test utility methods that communicate with SMB shares.
'''
from __future__ import absolute_import
import getpass
import logging
import os
import signal
import subprocess
import tempfile
import time
import salt.utils.files
import salt.utils.path
import salt.utils.smb
from tests.support.unit... |
the-stack_106_30674 | # Import modules
import subprocess
import urllib
import numpy as np
import pytest
import yaml
# Import oceanspy
from oceanspy.open_oceandataset import _find_entries, from_catalog, from_netcdf
# SCISERVER DATASETS
url = (
"https://raw.githubusercontent.com/hainegroup/oceanspy/"
"master/sciserver_catalogs/data... |
the-stack_106_30676 | ##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
## Implementing backward SFS on simulated process data
## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% read data
import numpy as np
VSdata = np.loadtxt('VSdata.csv', delimiter=',')
#%%... |
the-stack_106_30677 | #
# Copyright 2019 The FATE 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_106_30679 | # -*- coding: utf-8 -*-
# @File : PostMulitMsfBypassUAC.py
# @Date : 2019/3/15
# @Desc :
from Lib.ModuleAPI import *
class PostModule(PostMSFRawModule):
NAME_ZH = "Windows计划任务持久化"
DESC_ZH = "模块注册计划任务实现持久化,当前Session所在用户登录系统时执行载荷\n" \
"使用模块时请勿关闭对应监听,Loader启动需要回连监听获取核心库文件."
NAME_EN = "Win... |
the-stack_106_30682 | from __future__ import print_function, division
import string
import numpy as np
class GeneticAlgorithm():
"""An implementation of a Genetic Algorithm which will try to produce the user
specified target string.
Parameters:
-----------
target_string: string
The string which the GA should tr... |
the-stack_106_30683 | from __future__ import print_function
import os
import shutil
import subprocess
import logging
import pyhhi.build.common.ver as ver
import pyhhi.build.common.bldtools as bldtools
from pyhhi.build.common.system import SystemInfo
class BjamBuilder(object):
"""The BjamBuilder class supports building a new bjam exe... |
the-stack_106_30684 | from typing import List
from unittest.mock import AsyncMock
from urllib.parse import ParseResult, parse_qs, urlencode, urlparse
import pytest
from box import Box # type: ignore
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic.dataclasses import dataclass
from requests import Respons... |
the-stack_106_30685 | """
This command is used to add an Institution to the database.
Execution: python manage.py add_institution <name> <cas_server_url>
"""
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.core.validators import URLValidator
from django.utils... |
the-stack_106_30686 | from setuptools import setup, find_packages
install_requires = [line.rstrip() for line in open("requirements/requirements.txt", "r")]
setup(
name="inhandpy",
version="0.0.1",
description="PatchGraph: In-hand tactile tracking with learned surface normals",
url="",
author="Paloma Sodhi",
author_... |
the-stack_106_30687 | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
Tests for the HTTP challenge authentication implementation. These tests aren't parallelizable, because
the challenge cache is global to the process.
"""
try:
fr... |
the-stack_106_30689 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def deleteNode(self, key):
... |
the-stack_106_30692 | """Webbot URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
the-stack_106_30693 | import discord
from discord.ext import commands
from discord.ext.commands import Bot
import random
import asyncio
import aiohttp
print("Online")
bot = commands.Bot(command_prefix="~")
listDebugState = False
dataFiles = {"help":"C:\\Users\\Reese\\Desktop\\nohelp.txt",
"faq":"C:\\Users\\Reese\\Deskt... |
the-stack_106_30694 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sfquery",
version="1.0.0",
author="Antonio Menarde, Shalabh Mohan Shrivastava",
author_email="amenarde@gmail.com",
description="A package to query reliable collections using python or jupy... |
the-stack_106_30697 | #
# Compare lithium-ion battery models with and without particle size distibution
#
import numpy as np
import pybamm
pybamm.set_logging_level("INFO")
# load models
models = [
pybamm.lithium_ion.DFN(name="standard DFN"),
pybamm.lithium_ion.DFN(name="particle DFN"),
]
# load parameter values
params = [models[0... |
the-stack_106_30700 | import itertools
from ray import tune
from collections import OrderedDict
num_seeds = 5
var_env_configs = OrderedDict(
{
"delay": [0] + [2 ** i for i in range(4)],
"dummy_seed": [i for i in range(num_seeds)],
}
)
var_configs = OrderedDict({"env": var_env_configs})
env_config = {
"env": "G... |
the-stack_106_30701 | from view import View
from PIL import Image # type: ignore
class Canvas:
def __init__(self, view: View) -> None:
self.view = view
self.image_number = 0
def paint(self) -> Image:
image = Image.new("RGB", (self.view.width, self.view.height))
self.view.paint(image)
retur... |
the-stack_106_30702 | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url('^$' , views.get_image, name ='homepage'),
url('^user/' , views.userpage , name='username'),
url('^image/(?P<id>[0-9]+)$' , views.image_details , name ='image... |
the-stack_106_30704 | from collections import namedtuple
import networkx as nx
from fud.errors import UndefinedStage, MultiplePaths
Edge = namedtuple("Edge", ["dest", "stage"])
class Registry:
"""
Defines all the stages and how they transform files from one stage to
another.
"""
def __init__(self, config):
s... |
the-stack_106_30705 | #!/pxrpythonsubst
#
# Copyright 2018 Pixar
#
# 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_30708 | import zqtflearn
import unittest
import numpy as np
import tensorflow as tf
class TestMetrics(unittest.TestCase):
"""
Testing metric functions from zqtflearn/metrics
"""
def test_binary_accuracy(self):
with tf.Graph().as_default():
input_data = tf.placeholder(shape=[None, 1], dtyp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.