text
string
size
int64
token_count
int64
""" The getObjectDistance (angle_min, angle_max) function will get the distance of LIDAR points between angle_min and angle_max. Then it takes the median of distances and return it. This function is used as a supporting method for the ADAS system after bounding box detection of objects. The x_min and x_max of boundi...
8,816
3,070
import hashlib from panda3d.core import (VirtualFileSystem, Multifile, Filename) def md5_sum(filename, blocksize=65536): hash = hashlib.md5() with open(filename, "rb") as f: for block in iter(lambda: f.read(blocksize), b""): hash.update(b...
683
238
""" Python Interchangeable Virtual Instrument Library philipsPM2830.py Copyright (c) 2017 Coburn Wightman Derived from rigolDP800.py Copyright (c) 2013-2017 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software...
3,142
1,040
import logging import discord from discord.ext import commands, tasks from settings import BOT_TOKEN, LOGGER_NAME, LOG_FILE, UPDATE_INTERVAL from reddit import RedditConnection class NotificationCog(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot = bot self.reddit: RedditCo...
2,397
795
from enum import Enum class ExitCodes(Enum): SHUTDOWN = 0 CRITICAL = 1 RESTART = 26
98
43
#!/usr/bin/env python # coding=utf-8 import tensorflow as tf import numpy as np # 加载动态库 model = tf.load_op_library('/Users/jiaofuzhang/morse-stf/cops/_stf_int64conv2D_macos.so') p_model = tf.load_op_library('/Users/jiaofuzhang/morse-stf/cops/_stf_int64pooling_macos.so') # ST_model = tf.load_op_library('/Users/jiaofuzha...
8,402
3,633
import sys import time import requests from selenium.common.exceptions import WebDriverException from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By import config from core import browser from utils import console class Captcha: def _get_captcha(self): time.sleep(0.5)...
3,749
1,456
"""Engine-Level Classes and Utilities. @see: Cake Build System (http://sourceforge.net/projects/cake-build) @copyright: Copyright (c) 2010 Lewis Baker, Stuart McMahon. @license: Licensed under the MIT license. """ import codecs import threading import traceback import sys import os import os.path import time import ...
36,233
10,167
#!/usr/local/bin/python2.7 import Image from numpy import * import sys def usage(): print >> sys.stderr, 'Usage:', sys.argv[0], 'path/to/image1 path/to/image2 [... path/to/imageN] path/to/output' sys.exit(-1) if len( sys.argv ) < 4: usage() filenames = sys.argv[1:-1] outname = sys.argv[-1] num = 0 avg...
953
378
# coding=utf-8 # Copyright 2019 The SEED Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
4,588
1,609
c = get_config() c.CourseDirectory.root = '/home/grader-techprog/techprog' c.CourseDirectory.course_id = "techprog"
116
44
#!/usr/bin/env python3 import sys sys.path.append('lib') from validators import validate_file_list from sys import exit, argv if __name__ == '__main__': try: if len(argv) < 3: raise ValueError('Not enough arguments!') schema, infiles = argv[1], argv[2:] except Exception as e: ...
453
148
from django.http.response import Http404 from django.shortcuts import render,reverse from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import ( CreateView, ListView, DetailView, ...
4,643
1,335
# Copyright 2020 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 agreed to in writing, ...
20,325
6,922
import os import subprocess from xia2.Driver.DefaultDriver import DefaultDriver from xia2.Driver.DriverHelper import script_writer class ScriptDriver(DefaultDriver): def __init__(self): super(ScriptDriver, self).__init__() self._script_command_line = [] self._script_standard_input = [] ...
3,033
833
from arm.logicnode.arm_nodes import * class GetFirstContactNode(ArmLogicTreeNode): """Returns the first object that is colliding with the given object. @seeNode Get Contacts """ bl_idname = 'LNGetFirstContactNode' bl_label = 'Get RB First Contact' arm_section = 'contact' arm_version = 1 ...
469
148
#!/usr/bin/env python # coding: utf8 # We will use the inkex module with the predefined Effect base class. import inkex # The simplestyle module provides functions for style parsing. import simplestyle import math objStyle = simplestyle.formatStyle( {'stroke': '#000000', 'stroke-width': 0.1, 'fill': 'none...
24,490
8,901
#!/usr/bin/env python3 # # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause import sys from nmigen import * from apollo_fpga import create_ila_frontend from luna import top_l...
1,825
613
# import all functions from the tkinter from tkinter import * # import messagebox class from tkinter from tkinter import messagebox # Function for clearing the # contents of all text entry boxes def clearAll() : # deleting the content from the entry box dayField.delete(0, END) monthField.delete(0, END) yearField...
5,439
2,048
whereData = "../OpenAire/publication/" # where to store and access OpenAire data # MUST end with a slash!!!! download = False # if True, download OpenAire data, else use existing data from whereData extract = True # if True, extract the ta...
18,704
7,124
#-*- coding: utf-8 -*- import six import unittest import tensorflow as tf from ..utils import logger from .scope_utils import under_name_scope class ScopeUtilsTest(unittest.TestCase): @under_name_scope(name_scope='s') def _f(self, check=True): if check: assert tf.get_default_graph().get...
888
298
"""Test Hunter Lab.""" import unittest from . import util from coloraide_extras import Color import pytest class TestHunterLab(util.ColorAssertsPyTest): """Test Hunter Lab.""" COLORS = [ ('red', 'color(--hunter-lab 46.113 82.672 28.408)'), ('orange', 'color(--hunter-lab 69.407 23.266 40.946)'...
1,970
899
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from sys import stdin, stderr import re import numpy as np from pymongo import MongoClient __author__ = 'litleleprikon' HASHTAG_RE = re.compile(r'#[-a-z0-9+&@#/%?=~_()|!:,.;]+', re.IGNORECASE) FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)') ALL_CAP_RE = re.compile('([a-z0-...
2,697
1,070
#!/usr/bin/env python2 ''' Unit tests for oc route ''' # To run: # ./oc_serviceaccount.py # # . # Ran 1 test in 0.002s # # OK import os import six import sys import unittest import mock # Removing invalid variable names for tests so that I can # keep them brief # pylint: disable=invalid-name,no-name-in-module # Disa...
12,367
3,884
import spn_codes.spatialpooling as spatialpooling import torch.nn as nn import torch import torchvision.models as models from spn.modules import SoftProposal class SPNetWSL(nn.Module): def __init__(self, num_classes=20, num_maps=1024): super(SPNetWSL, self).__init__() model = models.vgg16(pretrain...
1,789
639
from mock import patch, Mock from unittest import TestCase from devicehive import connectDeviceHive, reactor class ConnectDeviceHiveTestCase(TestCase): def setUp(self): self.factory = Mock() def test_calls_http(self): with patch('twisted.internet.reactor.connectTCP') as f: connec...
591
180
#!/usr/bin/env python import mediapipe as mp import cv2 import os, glob import sys # Utils def detect_hand(path): image = cv2.imread(path, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) mp_hands = mp.solutions.hands hands = mp_hands.Hands(min_detection_confidence=0.5, min_trackin...
1,461
613
""" Generalized Transport Velocity Formulation ########################################## Some notes on the paper, - In the viscosity term of equation (17) a factor of '2' is missing. - A negative sign is missing from equation (22) i.e, either put a negative sign in equation (22) or at the integrator step equation(...
21,609
8,233
#!/usr/bin/python3 import json from src.model.amazonItem import AmazonItem import requests import urllib.parse from bs4 import BeautifulSoup from price_parser import Price from decimal import Decimal import random import re import time # TODO Add an header randomizer to generate a wider variety of headers class Amazo...
6,343
1,941
import itertools from typing import List from unittest import TestCase import numpy as np def main(input_file): """Solve puzzle and connect part 1 with part 2 if needed.""" # part 1 inp = read_input(input_file) p1 = part_1(inp) print(f"Solution to part 1: {p1}") # part 2 inp = read_input...
5,450
2,035
from typing import Pattern import re from .utils import validator md5_regex: Pattern = re.compile( r"^[0-9a-f]{32}$", re.IGNORECASE ) sha1_regex: Pattern = re.compile( r"^[0-9a-f]{40}$", re.IGNORECASE ) sha224_regex: Pattern = re.compile( r"^[0-9a-f]{56}$", re.IGNORECASE ) sha256_regex: Patter...
2,666
1,215
#-*- coding: utf-8 -*- from aiida.parsers.parser import Parser from aiida.orm.data.parameter import ParameterData from aiida_kkr.calculations.voro import VoronoiCalculation from aiida.common.exceptions import InputValidationError from aiida_kkr.tools.voroparser_functions import parse_voronoi_output __copyright__ = ...
5,323
1,502
""" predicates.py: This file contains basic predicates as well as event and telemetry predicates used by the gds_test_api.py. The predicates are organized by type and can be used to search histories. :author: koran """ from inspect import signature from fprime_gds.common.data_types.ch_data import ChData from fprime_...
19,146
4,916
from django.shortcuts import render from insaatWeb import models from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render from django.contrib import messages from datetime import datetime,date import random,os,filetype from insaatWeb.models import Projeler,Bloklar,Daireler,Satis,Ari...
11,579
4,240
# -*- coding: utf-8 -*- import unittest import numpy as np import turret import turret.layers as L from util import execute_inference class ReshapeTest(unittest.TestCase): def test_default(self): N = 5 C_in, H_in, W_in = 3, 20, 30 C_out, H_out, W_out = 6, 5, 60 input = np.random....
897
331
""" .. module:: operations :platform: Unix, Windows :synopsis: Provides geometric operations for spline geometry classes .. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com> """ import math import copy import warnings from . import abstract, helpers, linalg, compatibility from . import _operations as ops ...
67,807
22,048
import sys def format_tb(tb, limit): return ["traceback.format_tb() not implemented\n"] def format_exception_only(type, value): return [repr(value) + "\n"] def format_exception(etype, value, tb, limit=None, chain=True): return format_exception_only(etype, value) def print_exception(t, e, tb, limit=None,...
671
233
#!/usr/bin/python # -*- coding: utf-8 -*- """Logout functionality""" from mini_project_1.common import ShellArgumentParser def get_logout_parser() -> ShellArgumentParser: """Argparser for the :class:`.shell.MiniProjectShell` ``logout`` command""" parser = ShellArgumentParser( prog="logout", ...
392
124
"""Day 6: Universal Orbit Map""" import math from collections import defaultdict, deque from copy import deepcopy from typing import DefaultDict, Iterator, List, NamedTuple, Tuple import aoc DAY = 6 OrbitGraph = DefaultDict[str, List[str]] def parse_input(input_text: str) -> OrbitGraph: orbits: OrbitGraph = de...
4,272
1,407
import datetime import os from itertools import chain, starmap def dict_compare(old_dict, new_dict, nested=None): """ Compare two dictionaries Only 1 level, ignoring attributes starting with '_' """ key_prefix = nested + '|' if nested else '' intersect_keys = old_dict.keys() & new_dict.keys() ...
9,691
2,743
import numpy as np import math extraNumber = 4 * math.pi * pow(10,-7) def timeConstant(): henry = float(input('Input Henry: ')) ohms = float(input('Output Ohms: ')) ohms = ohms / 1000 timeConstant = henry/ohms print(timeConstant) timeConstant()
280
105
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout This file is part of SleekXMPP. See the file LICENSE for copying permission. """ import logging from sleekxmpp import Iq from sleekxmpp.plugins import BasePlugin from sleekxmpp.xmlstream.handler import Callb...
2,520
879
# Copyright 2018 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 the "l...
7,985
2,373
import sys # input N = int(sys.stdin.readline().rstrip()) numbers = list(map(int, sys.stdin.readline().split())) operators = list(map(int, sys.stdin.readline().split())) MIN = 1000000000 MAX = -1000000000 # 완전탐색 def search(picked, result): global MIN, MAX, numbers, operators if picked == N: if MIN >...
880
313
"""Parse HTML pages. """ from bs4 import BeautifulSoup # type: ignore import nltk_utils # type: ignore import parser_types as PT # type: ignore import re # type: ignore from typing import List, Tuple # type: ignore ################################################################################ # Parse Pages other t...
2,066
675
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2019 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/l...
5,187
1,679
# 023 # Ask the user to type in the first line of a nursery rhyme and display # the length of the string. Ask for a starting number and an # ending number and then display just that section of the text # (remember Python starts counting from 0 and not 1). rhyme = list() while True: try: if not rhyme: ...
858
254
from datetime import date, datetime, timedelta from django.conf import settings import logging from collections import OrderedDict import psycopg2 import pytz import titlecase TZ = pytz.timezone(settings.TIME_ZONE) LOGGER = logging.getLogger('sync_tasks') ALESCO_DB_FIELDS = ( 'employee_id', 'surname', 'initials', ...
10,015
3,232
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="synthetic_data", version="1.0.0", author="Karan Bhanot", author_email="bhanotkaran22@gmail.com", description="Package that enables generation of synthetic data", long_description=long_...
946
360
from unittest.mock import patch from indicoio.client import RequestProxy from indicoio.api.base import ObjectProxy @patch.object(RequestProxy, "_make_request") def test_object_proxy_in(mock_request_proxy): obj_proxy = ObjectProxy(mock_arg="mock_arg_value") assert "mock_arg" in obj_proxy, obj_proxy @patch.o...
1,267
434
def _find_separator_positions(separator_oracle, c): separator_positions = [] c = bytearray(c) for i in range(len(c)): c[i] ^= 1 valid = separator_oracle(c) c[i] ^= 1 if not valid: c[i] ^= 2 valid = separator_oracle(c) c[i] ^= 2 ...
1,417
432
from setuptools import setup, find_packages setup ( name = "testapp", version = "0.1", description = "Example application to be deployed.", packages = find_packages(), install_requires = ["pymisp","pandas","requests"], )
277
76
#!/usr/bin/env python3 import functools import torch import torch.nn as nn from .attack import attack def _fgsm(model, X, y, epsilon): X.requires_grad = True out = model(X) _, predicted = torch.max(out.data, 1) acc = (predicted == y.data).float().sum().item() / X.size(0) model.zero_grad() loss...
822
346
import numpy as np import tensorflow as tf import matplotlib.pyplot as pl import tensorsim as ts """ Model dX = (a*X - B*X*Y)dt #Prey dY = (B*X*Y - mu*Y)dt #Predator """ n_reps = 100 X_t0, Y_t0 = 300., 300. a, B, mu = 0.1, 0.0005, 0.2 with tf.Graph().as_default(): # initial conditions ics = tf.const...
989
485
# tools.py ''' Helpers for serialization. ''' # Things to fix ''' ''' # Importing dependencies import numpy as np # Code def array2json(data, lib={}): lib['shape'] = np.shape(data) #print('np2json_array shape: ' + str(lib['shape'])) lib['array'] = [float(element) for element in np.reshape(data, (np.produ...
438
154
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 # noqa: E501 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class OrderPaymentCreditCard(o...
14,692
4,543
""" bos_csm_component.py Created by NWTC Systems Engineering Sub-Task on 2012-08-01. Copyright (c) NREL. All rights reserved. """ from openmdao.main.api import Component, Assembly, VariableTree from openmdao.main.datatypes.api import Int, Bool, Float, Array, VarTree from fusedwind.plant_cost.fused_bos_costs import B...
20,747
7,777
from copy import deepcopy from unittest import TestCase from unittest.mock import patch, Mock from pony.orm import db_session, rollback from vk_api.bot_longpoll import VkBotMessageEvent from bot import Bot from chatbot import settings from chatbot.generate_ticket import generate_ticket def isolate_db(test_func): ...
3,595
1,181
# Copyright (c) 2018 UAVCAN Consortium # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel@uavcan.org> # pylint: disable=consider-using-in,protected-access,too-many-statements import fractions from . import _any, _primitive, _container, _operator # noinspection PyUnres...
4,558
1,701
# Copyright 2018 SAS Project 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 requ...
2,730
921
"""Provide configuration end points for Z-Wave.""" import asyncio from homeassistant.components.config import EditKeyBasedConfigView from homeassistant.components.zwave import DEVICE_CONFIG_SCHEMA_ENTRY import homeassistant.helpers.config_validation as cv CONFIG_PATH = 'zwave_device_config.yaml' @asyncio.coroutine...
555
185
# Copyright (c) 2021-2022, 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 ...
2,166
636
import os import warnings from tempfile import TemporaryDirectory import numpy as np import pytest from aptl3.db import Database from aptl3.scripts.load_coco import load_coco coco_dir = './coco/annotations/' @pytest.mark.skipif(not os.path.isdir(coco_dir), reason='test_coco would not find the coco annotations json....
3,124
995
""" Tests for performance comparison functions. Copyright (c) 2016 Marshall Farrier license http://opensource.org/licenses/MIT """ import unittest import numpy as np import pandas as pd import pynance as pn class TestCompare(unittest.TestCase): def test_compare(self): rng = pd.date_range('2016-03-28',...
943
369
import numpy as np import scipy import scipy.signal import scipy.interpolate #import Akima1DInterpolator, Rbf, InterpolatedUnivariateSpline, BSpline def emd(x, order,method = 'cubic', max_itter = 100, tol = 0.1): ''' Emperical Mode Decomposition (EMD). The emperical mode deocomposition method is th...
6,192
2,101
# Go ahead and replace db_names with how you named your dumps. Make sure it's in the same order # Each dump should still start with osu_ ex. osu_random_2019_11_01 from curve_analysis.bin.config import * import mysql.connector from tqdm import tqdm class OsuDB: password = SQL_PASSWORD host = SQL_HOST user...
1,622
503
# Copyright 2015-2017 Yelp 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 writing,...
1,913
607
import sys sys.path.append('/home/vibhatha/github/bio/PythonMPI') from comms import Communication import numpy as np class ISendIRecvExample: comms = Communication.Communication() def example(self): rank = self.comms.comm.Get_rank() if (rank == 0): input = np.array([0,1,2,3,4]) ...
722
257
#!/usr/bin/env python # Copyright (c) 2009, South African Astronomical Observatory (SAAO) # # All rights reserved. See LICENSE for more details # """ AutoIDENTIFY is a program to automatically identify spectral lines in an arc image. Author Version Date -----------------------------...
10,637
3,430
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import time from datetime import datetime, timedelta from functools import wraps from optparse import AmbiguousOptionError, BadOptionError, OptionParser from pysassc import main as pysassc_main from watchdog.events import PatternMatchingEventHandler fr...
4,236
1,265
from pyzotero import zotero def fetch_list(library_id, library_type, collection_key, api_key, csl): zot = zotero.Zotero(library_id, library_type, api_key) collections = zot.collections_top() data = {} if collection_key: data = {'ref_list': zot.collection_items_top( collection_key, ...
1,830
473
# -*- coding:utf-8 -*- # author: szy # time: 2017/11/8 15:57 # email: shizhenyu96@gmail.com import redis from config import SETTINGS, REDIS_KEY import GeneralHashFunctions class BloomFilterRedis(object): hash_list = ["RSHash", "JSHash", "PJWHash", "ELFHash", "BKDRHash", "SDBMHash", "DJBHash", "...
3,507
1,246
class Match: raw_matches = [] def __init__(self, data, playlist_filter): self.map = data["gameMetadata"]["map"] self.time = data["gameMetadata"]["time"] self.guid = data["gameMetadata"]["matchGuid"] self.playlist = data["gameMetadata"]["playlist"] self.valid_match_create...
1,247
378
import json import os import sys import singer from google.api_core import exceptions from google.cloud import bigquery from google.cloud.bigquery import Dataset logger = singer.get_logger() def emit_state(state): """ Given a state, writes the state to a state file (e.g., state.json.tmp) :param state, ...
1,908
563
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010-2011 OpenStack, LLC # 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...
4,876
1,427
# -*- coding: utf-8 -*- # @Time : 17-11-22 上午11:17 # @Author : Fei Xue # @Email : feixue@pku.edu.cn # @File : visualize.py # @Software: PyCharm Community Edition import numpy as np import matplotlib.pyplot as plt import os def load_data(fn): with open(fn, "r") as f: data = f.readlines() ret...
878
361
# coding:utf-8 import random import gzip import StringIO """ using gzip to enable stream smaller """ USER_AGENTS = [ 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1', 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0', 'Mozil...
1,910
913
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # ./noc dump-crashinfo # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # -----------------------------------------------------------...
1,260
391
from flask import Blueprint, render_template from flask_login import login_required, current_user views = Blueprint('views', __name__) @views.route('/', methods=['GET', 'POST']) def home(): return render_template("/base/index.html") @views.route('/add-data', methods=['GET', 'POST']) @login_required def addData...
394
122
from collections import Sequence import numpy as np from PIL import Image class CoOccur: """ Class used to compute all Co-occurrence matrices of an image for a set of distances and angles and some related parameters: the inertia, the average, the spread. An instance of the CoOccur class holds a tenso...
7,338
2,137
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 16 14:47:33 2019 @author: Matteo Papini """ import torch import gym import potion.envs from potion.actors.continuous_policies import ShallowGaussianPolicy from potion.actors.discrete_policies import ShallowGibbsPolicy from potion.common.logger impor...
4,647
1,487
class Solution: def getSmallestString(self, n: int, k: int) -> str: # len = n, numerical value = k d = {i: ch for i, ch in enumerate(string.ascii_lowercase, 1)} d[0] = 'z' ans = [] for i in range(n): left = n - i if 1 + 26 * (left - 1) >= k: ...
501
170
import argparse import glob import os import sys from pathlib import Path # from fortran_apis import which_api from soilapis.fortran_apis import which_api import gdal import osr import pandas as pd import numpy as np # Paths script_dir = os.getcwd() outputs = '' parent_dir = "" layers_dir = "" country_dir = "" globe_...
21,591
7,371
import pytest import json from mock import MagicMock from collections import OrderedDict from werkzeug.wsgi import DispatcherMiddleware from flaskdemo.webapi import create_app from flaskdemo.webapi.v1 import view from common import conf URL_TEST_INDEX = '/api/v1/' URL_TEST_POLICY = '/api/v1/policy' URL_TEST_RESULT = ...
2,154
776
import numpy as np __all__ = ['PVSModeling'] __docformat__ = "restructuredtext en" class PVSModeling(object): """Class containing a collection of methods needed for seismic inversion using postiv vectorized signal methods. Attributes ---------- """
286
84
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import socket import unittest import pyrfc from decimal import Decimal from tests.config import PARAMS as params, CONFIG_SECTIONS as config_sections, get_error class TestConnection: def setup_method(self, test_method): self.conn = pyrfc.Conne...
3,964
1,252
# -*- coding: utf-8 -*- # # Imports and early Python version check. # packageName = "benzina" githubURL = "https://github.com/obilaniu/Benzina" import os, sys if sys.version_info[:2] < (3, 5): sys.stdout.write(packageName+" is Python 3.5+ only!\n") sys.exit(1) from setuptools import setup, find_packages, Ex...
3,690
1,089
#!/usr/bin/env python import os import glob import shutil import subprocess import warnings import configparser class Parfile(dict): def __init__(self, infile, section): super(Parfile, self).__init__() parser = configparser.ConfigParser() parser.optionxform = str result = parser.rea...
13,547
4,212
class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) class Graph: ...
4,136
1,304
import pandas as pd import random import datasets import torch from transformers import AutoTokenizer class CustomQGDataset(torch.utils.data.Dataset): def __int__(self, tokenizer: AutoTokenizer, data: datasets.Dataset, max_length: int, pad_mask_id: i...
1,395
419
import requests from datetime import date, timedelta, datetime from django.core.management.base import BaseCommand from core.models import Drug, Route, MOA class Command(BaseCommand): """Django command to load the database""" def build_moa_table(self, data_list): self.stdout.write(f'{str(datetime.n...
5,073
1,432
import unittest from pyvirtualdisplay import Display # noinspection PyUnresolvedReferences from labs_web.test import (TestServiceIsUp, TestLogin, TestTutorMenu) if __name__ == "__main__": display = Display(visible=0, size=(1366, 768)) display.start() u...
354
106
#!/usr/bin/python """ Process EOS Fisher matrices and plot P(k). """ import numpy as np import pylab as P from rfwrapper import rf import matplotlib.patches import matplotlib.cm from units import * from mpi4py import MPI import os import euclid cosmo = rf.experiments.cosmo #names = ["GBT", "BINGO", "WSRT", "APERTIF...
4,880
2,350
import pytest from udb_py.common import FieldRequiredError, required, type_formatter_iter from udb_py.udb_index import UdbIndex def test_should_get_cover_key_on_full_covered_data(): i = UdbIndex(['a', 'b', 'c']) d = {'a': 1, 'b': 2, 'c': 3} assert i.get_cover_key(d) == ''.join(type_formatter_iter([1, 2,...
2,765
1,213
from __future__ import annotations import math from typing import Optional, Tuple, List, Union from lark import Lark from .tools import ( get_measure_divisor, convert_to_fragment, get_rest, parallel_parse_fragments, ) from ..event import NoteType from .simainote import TapNote, HoldNote, SlideNote, To...
26,185
7,260
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from accounts.serializers import UserSerializer # Create your views here. class UserView(A...
1,885
480
# # Copyright 2016 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); """ 该模块原设计是从网络读取数据,存储在本地文件。 现更改为直接从本地sql数据库中读取,去掉相应辅助函数。 """ import os import logbook import pandas as pd # # 读取本地指数作为基准收益率 #from .benchmarks import get_benchmark_returns from .benchmarks_cn import get_benchmark_re...
5,504
1,893
# -*- coding: utf-8 -*- # # Copyright (C) 2022 Northwestern University. # # Invenio-Communities is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """Invitation request type permission policy.""" from elasticsearch_dsl.query import Q fro...
4,333
1,172
import torch from torch.distributions import Normal from Cytof import Cytof from simdata import simdata def mixLz(i, n, j, etaz, muz, sig, y): Lz = muz.size(2) assert(Lz == etaz.size(2)) out = torch.empty(Lz) for l in range(Lz): out[l] = torch.log(etaz[i, j, l, 0]) + Normal(muz[0, 0, l, 0], si...
2,072
962
# %% [code] {"execution":{"iopub.status.busy":"2021-09-03T06:39:28.427498Z","iopub.execute_input":"2021-09-03T06:39:28.427884Z","iopub.status.idle":"2021-09-03T06:39:35.295609Z","shell.execute_reply.started":"2021-09-03T06:39:28.427802Z","shell.execute_reply":"2021-09-03T06:39:35.294682Z"},"jupyter":{"outputs_hidden":f...
12,751
6,729