text
string
size
int64
token_count
int64
# Copyright 2019 The Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
32,867
11,174
"""empty message Revision ID: b846613b404e Revises: fc25bf71d841 Create Date: 2020-01-06 21:43:28.958558 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'b846613b404e' down_revision = 'fc25bf71d841' branch_labels = None...
2,088
769
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.EnergyExtRequest import EnergyExtRequest class AlipayEcoCityserviceIndustryEnergySendModel(object): def __init__(self): self._ext_info = None self._outer_no =...
2,010
653
from django.urls import path from receipt import views urlpatterns = [ path('', views.ReceiptList.as_view(), name='home'), path('receipt/', views.ReceiptList.as_view(), name='receipt_list'), path('receipt/create', views.ReceiptCreate.as_view(), name='receipt_create'), path('receipt/<int:pk>/edit', vie...
1,657
554
from functools import partial from itertools import chain from collections import UserList import logging import traceback from django import forms from django.db.models import Model from django.core.validators import validate_comma_separated_integer_list from django.core.serializers.json import DjangoJSONEncoder from...
4,216
1,791
from django.urls import path from landingpage.views import * urlpatterns = [ path('',landingpage,name="landingpage"), ]
127
42
from common import sshClient import time import eventlet from .gol import * import requests from common.uploadMirror import login from common.sqlquery import Query #import pytest import json def check_login_response_headers(response): result = False if "cloud0" in response.headers.get("Set-Cookie"): r...
31,509
10,836
# --------------------- from bs4 import BeautifulSoup as bs import requests import urllib3 import urllib from urllib.parse import unquote import re import os import sys import json import time from colorama import Fore, init from pprint import pprint from datetime import datetime import uuid import threading # --------...
15,777
5,536
import unittest from alfpy import word_pattern from alfpy import word_vector from alfpy import word_distance from alfpy.utils import distmatrix from . import utils class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*ar...
10,504
4,521
from functools import partial class Features: @staticmethod def __emit_word_features(rel_pos, word): features = {} for f in Features.__word_feature_functions().items(): features.update({str(rel_pos) + ":" + f[0]: f[1](word)}) return features @staticmethod def get_w...
3,092
941
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * # NOQA @UnusedWildImport import unittest from obspy.core import AttribDict class AttribDictTestCase(unittest.TestCase): """ Test suite for obspy...
10,631
3,414
from cifar10 import CIFAR10 from mnist import MNIST class DatasetFactory: factories = {} def addFactory(id, dftory): DatasetFactory.factories.put[id] = dftory addFactory = staticmethod(addFactory) def getDataset(id): if id not in DatasetFactory.factories: DatasetFa...
458
148
# -*- coding: utf-8 -*- """ JSON Resume Validator ~~~~~~ JSON Resume Validator helps validate python dictionaries to ensure they are valid representation of a JSON Resume. """ from jsonresume.resume import Resume __all__ = ['Resume']
253
81
import glob import os import sys import re savedlines = [] def startreading(): if os.path.isdir(sys.argv[1]): os.chdir(sys.argv[1]) target = sys.argv[2] # TODO: Multiple lines. for file in glob.glob("*.srt"): read(sys.argv[1], file, target) savelines() print("...
936
303
# !/usr/bin/env python # -*- coding: utf-8 -*- # created by restran on 2016/1/2 from __future__ import unicode_literals, absolute_import import traceback from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_protect from django.db import transaction from cerberu...
19,712
5,767
# -*- coding: utf-8 -*- # filename: WX_BG.py import prices import glob import prediction import os import time import random #预测数据文件 prices_file_pattern = "Output\\prices\\*.csv" #预测数据文件 predict_file_pattern = "Output\\predict\\*.csv" #预测数据文件 prices_file_second_pattern = "Output\\prices_second\\*.csv" #预测数据文件 predict_...
2,209
861
import numpy as np import pytest from numpy.testing import assert_almost_equal from ...tools import linear, power from .. import dHsic # type: ignore class TestdHsicStat: @pytest.mark.parametrize("n, obs_stat", [(100, 0.04561), (200, 0.03911)]) @pytest.mark.parametrize("obs_pvalue", [1 / 1000]) def test...
929
375
from tkinter import * from PIL import ImageTk, Image import pymysql from tkinter import messagebox from tkinter import ttk from datetime import datetime, timedelta import decimal class ATLzooShowHistory: def __init__(self): self.createShowHistoryWindow() self.buildShowHistoryWindow(self.showHistory...
2,844
887
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: sample-weight-model-param.proto import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message ...
6,061
2,100
""" :author: Nicolas Strike :date: Early 2019 This file is mostly a definition of Cases. Each case is defined in the following format using python dictionaries (values surrounded with < > must have the < > removed to be valid). .. code-block:: python :linenos: CASENAME = {'name': 'casename', 'descrip...
63,679
23,611
from abc import ABC, ABCMeta, abstractmethod from domain.models.datase_information import DatasetInformation class AbstractDatasetValidatorService(ABC): __metaclass__ = ABCMeta @abstractmethod def validate_dataset(self, dataset_info: DatasetInformation) -> None: raise NotImplementedError
305
81
"""The setup script.""" from setuptools import find_packages, setup with open('README.md') as readme_file: readme = readme_file.read() with open('docs/release-notes.md') as history_file: history = history_file.read() requirements = [] dev_requirements = [ # lint and tools 'black', 'flake8', ...
1,683
559
# -*- coding: utf-8 -*- """Base data handler. Copyright 2021, Gradient Zero All rights reserved """ import logging import dq0.sdk from dq0.sdk.estimators.data_handler.base import BasicDataHandler import pandas as pd from sklearn.model_selection import train_test_split logger = logging.getLogger(__name__) class ...
3,109
979
class Solution: def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: range_iter = lower num_iter = 0 ranges = [] while range_iter < upper and num_iter < len(nums): if range_iter < nums[num_iter]: if nums[num_iter] - 1...
808
244
import os from django.conf import settings from git import Repo def update_vulnerability_templates(): template_dir = os.path.join( settings.BASE_DIR, "resources/vuln_templates") if os.path.isdir(template_dir): repo = Repo(template_dir) origin = repo.remotes.origin origin.pull()...
407
134
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ return map(s.index,s)==map(t.index,t)#相同格式都可以用
209
78
from .base_page import BasePage from .locators import BasketPageLocators class BasketPage(BasePage): def should_be_empty_basket_message(self): assert self.is_element_present(*BasketPageLocators.BASKET_EMPTY_MESSAGE), \ "Empty basket message element not found on page" assert self.brows...
656
207
import factory from api.collaboration.models import TeamMember class TeamMemberFactory(factory.django.DjangoModelFactory): class Meta: model = TeamMember
169
45
""" aiohttp モジュールのサンプルです 基本的な使い方について REFERENCES:: http://bit.ly/2O2lmeU http://bit.ly/2O08oy3 """ import asyncio from asyncio import Future from typing import List, Dict import aiohttp from trypython.common.commoncls import SampleBase async def fetch_async(index: int, url: str) -> Dict: async wit...
1,454
520
from sqlalchemy import Column, String, Boolean, ForeignKey, Integer from sqlalchemy.orm import relationship from database import Base from string import ascii_letters from random import choice class Playlist(Base): __tablename__ = "playlists" id = Column(String, primary_key=True) name = Column(String) ...
1,860
550
__________________________________________________________________________________________________ sample 24 ms submission class Solution: def countOfAtoms(self, formula: str) -> str: stack, atom, dic, count, coeff, c = [], '', collections.defaultdict(int), 0, 1, 0 for i in formula...
3,270
833
#!/usr/bin/env python3 import sys import numpy as np if len(sys.argv) == 1 or sys.argv[1] == "-h" or sys.argv[1] == "--help": print( """ Remove line indices (0-based) specified in 'index.txt' usage: program [-k] index.txt inFile -k Keep line indices in 'index.txt' instead of removing ...
932
328
#!/usr/bin/env python import arm_control_utils DURATION = 30000 TRAJ_POLY1 = [1000, 100, 100] TORQUE_POLY1 = [1000, 100, 100] MODE = 3 arm_control_utils.initialize_motors() arm_control_utils.enable_state_torque() arm_control_utils.set_debug(1, ...
538
225
#!/usr/bin/python # coding=utf-8 # # 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 appli...
5,758
1,893
# Estimators are partially based on the "estimators.py" from the following repositories: # https://github.com/agadetsky/pytorch-pl-variance-reduction # https://github.com/sdrobert/pydrobert-pytorch import torch def uniform_to_exp(logits, uniform=None, enable_grad=False): ''' Converts a tensor of independent u...
5,978
2,093
#Martina O'Brien 10/3/2019 #Problem Set 7 - squareroots #Programming Code to determining the squareroots of positive floating point numbers ## Reference for try and expect https://www.w3schools.com/python/python_try_except.asp while True: # this loop will run to allow the user to input a value again if they do ...
1,332
380
import requests import json token = '' email_token = '' print("######## Pass ########") target = 'http://127.0.0.1:5000/login' headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} data = {'username': 'jon@aaxus.com', 'password': 'password125'} r = requests.post(target, data=json.dumps(data), headers...
2,843
1,097
# (C) Copyright 2021 Inova Development Inc. # 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 appl...
5,578
1,543
#!/usr/bin/env python """ This module contains the base xml Node and Period classes """ from xml.dom.minidom import getDOMImplementation from date import Period from constants import START, END class XmlNode(object): """ the name of the class will define the name of the node by default. classes inherit...
1,704
495
"""Define the schema for the court summary report.""" import datetime from dataclasses import dataclass, field, fields from typing import Any, Iterator, List, Optional, Union import desert import marshmallow import pandas as pd from ..utils import DataclassSchema __all__ = ["CourtSummary", "Docket", "Charge", "Sent...
9,441
2,797
# Title : Json Module Module # Author : Kiran Raj R. # Date : 26/11/2020 python_json = {"name":"kiran", "email":"kiran@gmail.com", "isHappy": "Yes"} import json string_j = json.dumps(python_json) print(string_j)
216
88
import asyncio from asyncio import sleep from random import choice from userbot.events import register T_R_D = [ "@PrajjuS", "@Vin02vin", "@Iamsaisharan", "@venomsamurai", ] @register(outgoing=True, pattern="^.trd$") async def truthrdare(trd): """Truth or Dare""" await trd.edit("`Choosing Name...
573
228
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import zipfile import logging import requests import tempfile import contextlib from .parser import parse_record from .. import base logger = logg...
2,384
805
from os import path import json from bigcode_fetcher.project import Project FIXTURES_DIR = path.dirname(__file__) PROJECTS_PATH = path.join(FIXTURES_DIR, "projects.json") with open(PROJECTS_PATH, "r") as f: JSON_PROJECTS = json.load(f) PROJECTS = [Project(p) for p in JSON_PROJECTS]
292
112
from rx.subjects import Subject from rx.concurrency import QtScheduler import sys try: from PyQt4 import QtCore from PyQt4.QtGui import QWidget, QLabel from PyQt4.QtGui import QApplication except ImportError: try: from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication, QWidge...
1,465
480
import numpy as np import matplotlib.pyplot as plt from sklearn.manifold import Isomap from scipy.spatial.distance import pdist from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score, LeaveOneOut RANDOM_STATE = 42 def calculate_pairwise_distances(df_for_Box_Plot_featu...
6,116
2,048
def swap(p,j,k,n): a = p[j] b = [] for m in range(n): b.append(p[m][k]) for m in range(n): p[m][k] = a[m] p[j] = b for i in range(int(input())): n = int(input()) p,q = [],[] for j in range(n): p.append([int(k) for k in input().split()]) for j in range(n): ...
849
340
import tensorflow as tf default_params = tf.contrib.training.HParams( # Encoder encoder_num_hiddens=128, encoder_num_residual_hiddens=32, encoder_num_residual_layers=2, # Decoder decoder_num_hiddens=128, decoder_num_residual_hiddens=32, decoder_num_residual_layers=2, embedding_di...
1,110
450
""" File to demonstrate the coroutines api in python """ import asyncio async def coroutine(caller): print(f'entering ${caller}') await asyncio.sleep(1) print(f'exited {caller}') """ asyncio.run takes a coroutine and A RuntimeWarning is generated if the coroutine is not awaited Eg: coroutine('withou...
1,080
381
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu from tord.handlers import (block_test, gocron, index, media, upload) url_patterns = [ (r"/", index.IndexHandler), (r"/books", upload.BooksHandler), (r"/images", media.ImageHandler), (r"/videos", media.VideoHandler), # (r"/async/t...
494
190
statusEmojis = {'yes':'✅', 'no':'❌'} numEmojis = {1:'1️⃣', 2:'2️⃣', 3:'3️⃣', 4:'4️⃣', 5:'5️⃣', 6:'6️⃣', 7:'7️⃣', 8:'8️⃣', 9:'9️⃣', 0:'0️⃣'}
140
115
from .crawler import Crawler
28
10
# Copyright 2018 - 2020 Alexey Stepanov aka penguinolog. # # 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 requi...
12,048
3,930
import pickle import os from constant_variable import * # class Message class Message: def __init__(self,device, id, type, body): # constructor # message will consist: type of message,content - body,device to send self.id = id self.type = type self.body = body self.device ...
1,943
607
from featureMan.otSingleSubFeatures import * from featureMan.otNumberFeatures import * from featureMan.otLanguages import * from featureMan.otLocalized import * from featureMan.otLigatureFeatures import * from featureMan.otMark import mark from featureMan.otSyntax import fontDic, GDEF from featureMan.otKern import kern...
4,732
1,562
""" The MIT License Copyright (c) 2021 MatNet 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, copy, modify, merge, publish, d...
15,265
5,282
import os import numpy as np import mindspore from mindspore import Tensor from mindspore import load_checkpoint, load_param_into_net from src.model import RNNModel, RNNModelInfer from src.utils import process_poems start_token = 'B' end_token = 'E' model_dir = './ckpt/' corpus_file = './data/poems.txt' def to_word(p...
1,697
645
import os import sys from pychemia import HAS_PYMATGEN, pcm_log from .structure import Structure from pychemia.code.vasp import read_poscar from pychemia.code.abinit import AbinitInput def structure_from_file(structure_file): """ Attempts to reconstruct a PyChemia Structure from the contents of any given file...
1,523
468
from os import listdir import os.path import pandas as pd from .count_variants_per_gene import process_vcf from .genetree import make_gene_tree def make_variant_count_matrix(input_directory, output_filename): gene_tree = make_gene_tree() locus_names = sorted([ interval.data['locus'] for interval in gene_tree ...
992
305
from deepmerge import Merger def list_merge(config, path, base, nxt): for k in range(0, min(len(base), len(nxt))): if isinstance(base[k], (dict, list, tuple)): draft_merger.merge(base[k], nxt[k]) else: base[k] = nxt[k] for k in range(len(base), len(nxt)): base.a...
481
176
import os import numpy as np import pandas as pd from tqdm import tqdm from PIL import Image from lib.img2_coord_ica import img2_coord_iter, coord2_img from lib.log import Logger # ref: https://www.kaggle.com/paulorzp/run-length-encode-and-decode def rle_decode(mask_rle, shape=(768, 768)): """ Args: ...
4,951
1,784
from src.main import sample_function def test_addition(): test = sample_function(4) print('test') assert 8 == test
127
40
import numpy as np import re import json import xarray as xr import pandas as pd def read_train_loss(epoch, fname, variables=['test_loss', 'train_loss']): """Read the loss.json file for the current epochs test and train loss""" df = pd.read_json(fname) epoch_means = df.groupby('epoch')...
1,598
552
import pytest from selenium.common.exceptions import TimeoutException from selene.browser import * from selene.support.conditions import have from selene.support.jquery_style_selectors import ss from tests.acceptance.helpers.helper import get_test_driver from tests.acceptance.helpers.todomvc import given_active def ...
705
243
from genomics_data_index.storage.service import SQLQueryInBatcherDict, SQLQueryInBatcherList def test_sql_query_in_batcher_dict(): in_data = ['A', 'B', 'C', 'D', 'E'] # Test batch size 1 batcher = SQLQueryInBatcherDict(in_data=in_data, batch_size=1) results = batcher.process(lambda in_batch: {x: True...
2,422
852
class Constants: METER_2_NANOMETER= 1e9 APP_NAME= "inaf.arcetri.ao.tipico_server" APP_AUTHOR= "INAF Arcetri Adaptive Optics" THIS_PACKAGE= 'tipico_server' PROCESS_MONITOR_CONFIG_SECTION= 'processMonitor' SERVER_1_CONFIG_SECTION= 'serverOfAnInstrument' SERVER_2_CONFIG_SECTION= 'serverOfAn...
609
255
import db_transfer import config import logging from musdk.client import Client class MuApiTransfer(db_transfer.TransferBase): client = None users = [] def __init__(self): super(MuApiTransfer, self).__init__() self.pull_ok = False self.port_uid_table = {} self.init_mu_clie...
1,611
491
# Standard Library import json # Third Party Library import pytest from jsonpath_rw.lexer import JsonPathLexerError # First Party Library from data_extractor.exceptions import ExprError, ExtractError from data_extractor.json import JSONExtractor @pytest.fixture(scope="module") def text(): return """ { ...
2,001
670
import numpy as np from PIL import Image import os npy_file1 = './prediction/1110_1.npy' npy_file2 = './prediction/1110_2.npy' npy_file3 = './prediction/1110_3.npy' npy_file4 = './prediction/1110_4.npy' npy_file5 = './prediction/1110_5.npy' arr1 = np.load(npy_file1) arr2 = np.load(npy_file2) arr3 = np.load(npy_file3)...
938
452
# -*- coding: utf-8 -*- """ @Author: tushushu @Date: 2018-08-21 14:33:11 @Last Modified by: tushushu @Last Modified time: 2019-05-22 15:41:11 """ import os os.chdir(os.path.split(os.path.realpath(__file__))[0]) import sys sys.path.append(os.path.abspath("..")) from imylu.ensemble.gbdt_classifier import GradientBoos...
1,125
432
"""CoinGecko view""" __docformat__ = "numpy" import argparse from typing import List, Tuple import pandas as pd from pandas.plotting import register_matplotlib_converters import matplotlib.pyplot as plt from tabulate import tabulate import mplfinance as mpf from gamestonk_terminal.helper_funcs import ( parse_know...
16,658
4,800
""" Data loaders based on tensorpack """ import numpy as np from utilities import nparrays as arrtools def get_pancreas_generator(sample_name, volumes_path, references_path): sample_vol_name = volumes_path + sample_name[0] reference_vol_name = references_path + sample_name[1] volume = np.load(sample_vol...
701
228
# from django.core.management import BaseCommand # import pandas as pd # # from stages.models import Category, Stage # # # class Command(BaseCommand): # help = 'Import a list of stage in the database' # # def add_arguments(self, parser): # super(Command, self).add_arguments(parser) # parser.add_...
1,199
353
import os import io import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure from keras.applications.imagenet_utils import preprocess_input from keras.backend.tensorflow_backend import set_session from kera...
3,137
1,231
class BaseExceptions(Exception): pass class AuthException(BaseException): """Raised when an api method requires authentication""" pass class DeleteException(BaseException): """Raised when the delete of an object fails""" pass class UpsertException(BaseException): """Raised when the combi...
469
131
from . import BaseAPITestCase class TestArticleFilters(BaseAPITestCase): def setUp(self): super().setUp() self.authenticate() def test_it_filters_articles_by_article_title(self): self.create_article() self.create_article(title="Some article with another title") respo...
2,255
668
#!/usr/bin/python3 import subprocess import time from prometheus_client import start_http_server, Gauge def getstat(): s=subprocess.getoutput('ss -i -at \'( dport = :x11 or sport = :x11 )\' | awk \'FNR == 3 { print $4}\'') if s == "": return(0.0,"") else: rtt=s.lstrip("rtt:") r=rtt....
720
298
from behave import * use_step_matcher("re") @given("user inputs (?P<number>.+) and (?P<guess>.+)") def step_impl(context, number, guess): context.number = int(number) context.user_guess = guess @when("we run the converter") def step_impl(context): try: context.res = context.roman.check_guess(con...
516
174
import functions import Aspirobot import time import os import Manoir import Capteur import Etat import threading import Case from threading import Thread manor_size = 5 gameIsRunning = True clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear') manoir = Manoir.Manoir(manor_size, manor_size...
1,266
460
import numpy as np from scipy import sparse as sp from rlscore.utilities import multiclass def load_newsgroups(): T = np.loadtxt("train.data") #map indices from 1...n to 0...n-1 rows = T[:,0] -1 cols = T[:,1] -1 vals = T[:,2] X_train = sp.coo_matrix((vals, (rows, cols))) X_train = X_train....
1,169
475
print(3 ** int(input()))
25
10
# como los hash de ruby, guarda "clave" "valor" # al igual que un diccionario, esta la Palabra, que es la clave y la definción que seria el valor. # las claves tienen que ser unicas nombre_de_diccionario = {} #curly brackets. monthConversions = { "Jan": "January", "Feb": "February", "Mar": "March", "Apr": "A...
1,245
489
from click.testing import CliRunner from dothub.cli import dothub base_args = ["--user=xxx", "--token=yyy"] def test_dothub_help(): runner = CliRunner() result = runner.invoke(dothub, ['--help'], obj={}) assert result.exit_code == 0 def test_dothub_pull_help(): runner = CliRunner() result = ru...
578
210
import matplotlib matplotlib.use('Agg') import statsmodels.api as sm import statsmodels.formula.api as smf import numpy as np from scipy.stats import linregress import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc def hist_prebin(filename, values, width=1, x_title='', y_title='', title=None): ...
6,985
2,798
from thicket import finders def test_import(): assert finders
68
21
__all__ = ["ComponentTestCase"] import os import sys import yaml import unittest from gada import component from test.utils import TestCaseBase class ComponentTestCase(TestCaseBase): def test_load(self): """Test loading the testnodes package that is in PYTHONPATH.""" # Load component configuration...
2,251
639
import time import random from multiprocessing import pool from playsound import playsound from threading import Thread i = -1 l = 0 count = 0 class loops: def loop(self): print(" ", end="") def A(self): global i global l global i for j in range(i, 5): ...
17,820
6,051
import pytest from src.app import create_app @pytest.fixture def app(): app = create_app() app.config['TESTING'] = True ctx = app.app_context() ctx.push() yield app ctx.pop() @pytest.fixture def client(app): return app.test_client()
273
101
# This file implements the PMON firmware's LEON2 boot setup. It does not # implement the serial port boot loading, only the initial setup. # The PMON firmware for the LEON2 comes with a number of preprocessor defines # that the user typically changes to match the hardware configuration. # The PMON emulation function t...
2,533
1,159
import wpath from web3 import Web3 from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider def get_web3_by_http_rpc(): address = "http://47.243.92.131:8545" print("===>address:", address) p = HTTPProvider(address) web3 = Web3(p) return web3 w3 = get_web3_by_http_rpc() eth = w3.eth ...
395
190
from sklearn import svm from sklearn import ensemble from sklearn import linear_model class Model(object): def __init__(self): self.model_dict = { "SGDRegressor": linear_model.SGDRegressor(max_iter=1000), "HuberRegressor": linear_model.HuberRegressor(), "LinearRegressio...
834
253
shiboken_library_soversion = str(5.15) version = "5.15.2.1" version_info = (5, 15, 2.1, "", "") __build_date__ = '2022-01-07T13:13:47+00:00' __setup_py_package_version__ = '5.15.2.1'
189
111
""" list元素的排序 sort() 默认无参数是从小到大 reversed(list) 整个列表直接反过来,返回值是一个新的list """ import random a_list = [] for i in range(10): a_list.append(random.randint(0, 200)) print(a_list) a_list.sort() print(a_list) a_list.sort(reverse=True) # 降序,从大到小 print(a_list) new_list = reversed(a_list) # [12,10,7,9] -> ...
1,023
607
#!/usr/bin/env python # pylint: disable=no-value-for-parameter import click import os import sys import requests import json UNLOCK_SERVICE_DEFAULT_HOSTS = {"test": "https://testnet.threefold.io", "public": "https://tokenservices.threefold.io"} @click.command() @click.option("--source", default="export_data", help=...
1,643
485
from PgDiffUtils import PgDiffUtils class PgDiffConstraints(object): @staticmethod def createConstraints(writer, oldSchema, newSchema, primaryKey, searchPathHelper): for newTableName, newTable in newSchema.tables.items(): oldTable = None if (oldSchema is not None): ...
4,984
1,142
import inspect import logging import os from itertools import product import numpy as np import pandas as pd from skopt import load, dump from csrank.constants import OBJECT_RANKING from csrank.util import files_with_same_name, create_dir_recursively, rename_file_if_exist from experiments.util import dataset_options_...
7,715
2,316
from .. import schema, App, QueryCache, batcher, grouper, insert_ignore, export, lookup, persist, lookup_or_persist, ABCArgumentGroup, WorkOrderArgs, filter_widgets, temptable_scope, FeatureCache from ..ObjectStore import ABCObjectStore from sqlalchemy import Column, Integer, String, Float, ForeignKey, UnicodeText, Uni...
13,108
3,832
""" AIO -- All Trains in One """ from trains.baselines import * from trains.missingTask import * __all__ = ['ATIO'] class ATIO(): def __init__(self): self.TRAIN_MAP = { # single-task 'tfn': TFN, 'mult': MULT, 'misa': MISA, # missing-task ...
450
157
import os from .baseMethod import BaseMethod # BoardInfo class BoardInfo(BaseMethod): def method(self, payload): info = [ "boardInfo", {"name": os.name, "type": "dancer", "OK": True, "msg": "Success"}, ] return info
271
81
import os import cv2 import random import shutil import numpy as np def split_img(input_path): split_ratio = 0.8 for dir_name in xrange(10): dir_name += 1 dir_name = str(dir_name) dir_path = os.path.join(input_path, dir_name) img_in_class = os.listdir(dir_path) rand_tr...
4,928
1,854