text
string
size
int64
token_count
int64
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnheider' import csv import matplotlib.pyplot as plt import utilities as U # print(plt.style.available) plot_style = 'fivethirtyeight' # plot_style='bmh' # plot_style='ggplot' plt.style.use('seaborn-poster') plt.style.use(plot_style) plt.rcParams['axes.e...
1,657
632
print("I will now count my chickens:") print ("Hens",25+30/6) print ("Roosters",100-25*3%4) print("How I will count the eggs:") print(3+2+1-5+4%2-1/4+6) print("Is it true that 3+2<5-7?") print(3+2<5-7) print("What is 3+2?", 3+2) print("What is 5-7?", 5-7) print("Oh,that's why it's false") print("How about some...
435
214
import pickle # modify validation data _few_shot_pickle_file = 'few_shot_test_data.pkl' _few_shot_file = open(_few_shot_pickle_file, 'rb') data_few_shot = pickle.load(_few_shot_file) _few_shot_pickle_file = 'few_shot_val_data.pkl' _few_shot_file = open(_few_shot_pickle_file, 'rb') data_val = pickle.load(_few_shot_...
2,385
893
import numpy as np class Node: def __init__(self, gini: float, num_samples_per_class: np.ndarray, ) -> None: self.gini: float = gini self.num_samples_per_class: np.ndarray = num_samples_per_class self.predicted_class: int = np.argmax(num_s...
473
150
# ============================================================================= # Copyright 2020 NVIDIA. 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://ww...
5,654
1,748
from datetime import datetime import pytz from .constants import TIMEZONE timezone = pytz.timezone(TIMEZONE) def get_ist_now(): """Returns Indian Standard Time datetime object. Returns: object -- Datetime object """ return datetime.now(timezone)
276
85
""" LibriParty Dataset creation by using official metadata. Author ------ Samuele Cornell, 2020 Mirco Ravanelli, 2020 """ import os import sys import speechbrain as sb from hyperpyyaml import load_hyperpyyaml from speechbrain.utils.data_utils import download_file from local.create_mixtures_from_metadata import create...
1,357
474
import subprocess from pathlib import Path import pytest # from py4gh import __version__ from py4gh.utility import decrypt_files, encrypt_files, get_files # def test_version(): # assert __version__ == "0.1.0" @pytest.fixture(scope="session") def keys(tmpdir_factory): test_pub1 = tmpdir_factory.mktemp("data...
3,440
1,294
from unittest import TestCase from parameterized import parameterized from pyecsca.ec.context import local from pyecsca.ec.mult import LTRMultiplier, BinaryNAFMultiplier, WindowNAFMultiplier, LadderMultiplier, \ DifferentialLadderMultiplier from pyecsca.ec.params import get_params from pyecsca.sca.re.rpa import M...
2,885
1,188
import unittest # time complexity O(n**2) # space complexity O(1) def selection_sort(arr): n = len(arr) while n >= 2: value_max = arr[0] index_max = 0 for i in range(1, n): if arr[i] > value_max: value_max = arr[i] index_max = i arr[...
624
250
# !/usr/bin/python3 # -*- coding: utf-8 -*- # *****************************************************************************/ # * Authors: Daniel Garces, Joseph Tarango # *****************************************************************************/ import os, datetime, traceback, optparse, shutil import PyInstall...
2,930
867
from app1.models import * from app1.util.utils import * def updateTeachPlan(request): ''' get: http://127.0.0.1:8000/app4/updateTeachPlan?tpno=001&credit=7.0&teach_date=2019-08-22&evaluation_method=考查 调用参数: tpno:计划编号 credit:学分 teach_date:开课日期 ...
1,395
489
import lw.sources.tradera def test_valid_query(): results = lw.sources.tradera.TraderaSource().query('a') assert len(list(results)) > 0 def test_invalid_query(): results = lw.sources.tradera.TraderaSource().query('abc123') assert len(list(results)) == 0
274
102
from .database import db_session, init_db from .models import User, Book, BookRental from sqlalchemy import func import datetime import logging init_db() def get_tables(db_table): """ @author : TAEYONG LEE :param db_table: database table in model.py :type db_table: database model Object ...
3,973
1,340
# -*- coding:utf-8 -*- from django.db import models import django.utils.timezone as timezone # 用户登录信息表(服务器、虚拟机) class ConnectionInfo(models.Model): # 用户连接相关信息 ssh_username = models.CharField(max_length=10, default='', verbose_name=u'ssh用户名', null=True) ssh_userpasswd = models.CharField(max_length=40, defa...
6,511
2,880
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, unicode_literals, print_function) # flake8: noqa (unused import and line too long due to links) import os import random import string import struct import wave try: import unittest except ImportError: import u...
10,370
4,172
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
5,707
1,775
"""Test app.routes.build.""" import responses mock_product_data = { "bucket_name": "lsst-the-docs", "doc_repo": "https://github.com/lsst-sqre/test-059.git", "domain": "test-059.lsst.io", "fastly_domain": "n.global-ssl.fastly.net", "published_url": "https://test-059.lsst.io", "root_domain": "l...
5,855
2,358
from sklearn import tree from matplotlib import pyplot as plt from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn import model_selection from sklearn import metrics import numpy as np import pandas as pd import seaborn as sns from sklearn.neighbors impor...
2,650
1,032
# Generated by Django 3.2 on 2021-05-17 12:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='Pavilhao', fiel...
1,202
365
__author__ = 'Chetan' from abc import ABCMeta, abstractmethod class AbstractClass(metaclass=ABCMeta): def __init__(self): pass @abstractmethod def operation1(self): pass @abstractmethod def operation2(self): pass def template_method(self): print("Defining the...
740
212
"""Tests for Nexia Home.""" import json import os from os.path import dirname import unittest import pytest from nexia.home import NexiaHome def load_fixture(filename): """Load a fixture.""" test_dir = dirname(__file__) path = os.path.join(test_dir, "fixtures", filename) with open(path) as fptr: ...
27,687
10,127
import re import time import aiohttp CHANGE_CLOTHES = True # Use swap gear ACCOUNT_ID = 'b8dd6d09-0bf1-4455-99c5-4cec41b3a789' # account id goes here class DuelsAPI: def __init__(self, account_id, **kwargs): self.account_id = account_id self.API_ENTRY = kwargs.get('api_entry_url', ...
6,217
1,857
import os for filename in os.listdir("rasters"): print filename f = filename.replace(".tiff", "") tiff = "rasters/" + filename out = "shapefiles/" + f + ".shp" cmd = "gdal_polygonize.py " + tiff + " -f 'ESRI Shapefile' " + out os.system(cmd)
268
102
import numpy as np import sys import utils import os from collections import defaultdict from nltk.corpus import wordnet as wn from scipy.spatial.distance import cosine from scipy.spatial.distance import correlation from numpy.linalg import norm from scipy.stats import spearmanr, pearsonr from utils import trim import...
3,758
1,347
"""Implementations of calendaring abstract base class queries.""" # pylint: disable=invalid-name # Method names comply with OSID specification. # pylint: disable=no-init # Abstract classes do not define __init__. # pylint: disable=too-few-public-methods # Some interfaces are specified as 'markers' and inclu...
138,423
39,521
#!/usr/bin/env python from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import json import requests import sys import os from boto.s3.connection impor...
2,373
803
# First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n' \ 'You should consider updating to Python 3.4.0 or ' \ 'higher as the libraries built for this course ' \ 'have only been tested in Python 3.4 and higher.\n'...
5,550
1,961
import os import logging from logging import Formatter, FileHandler from flask import Flask def create_app(test_config=False): app = Flask(__name__, instance_relative_config=True) if test_config: app.config.from_object('config.TestingConfig') else: app.config.from_object(os.environ['APP_SET...
1,786
556
import torch from torch import nn import torch.nn.functional as F #from helper_functions import process_image class DeepNetworkClassifier(nn.Module): def __init__(self, input_units, output_units, hidden_units,p_drop=0.2): ''' Builds a classifier for a pretrained deep neural network for the flower d...
7,421
1,995
from flask import Blueprint, redirect, url_for, g from ..utils.utils import make_cache_key from ..internals.cache.redis import get_conn from ..internals.cache.flask_cache import cache from ..internals.database.database import get_cursor from ..lib.artist import get_artist, get_random_artist_keys from ..lib.po...
1,327
448
from functools import partial from typing import List import haiku as hk import jax import jax.numpy as jnp import numpy as np from rljax.algorithm.sac import SAC from rljax.network import ContinuousQuantileFunction, StateDependentGaussianPolicy from rljax.util import quantile_loss class TQC(SAC): name = "TQC" ...
4,258
1,507
import os from .FileNormalizer import FileNormalizer class ContactSelectFileNormalizer(FileNormalizer): '''ContactSelectFileNormalizer creates a pymol script that selects residues which have contacts to asymmetric units. ''' def __init__(self): pass def normalize_one_file(self, path, crystal_con...
917
306
import os import nibabel as nb import numpy as np from django.test import TestCase from neurovault.apps.statmaps.models import BaseStatisticMap from neurovault.apps.statmaps.utils import is_thresholded, infer_map_type class QATest(TestCase): def setUp(self): this_path = os.path.abspath(os.path.dirname(...
1,919
715
# -*- coding: utf-8 -*- import scrapy class BitcointalkSpider(scrapy.Spider): name = 'bitcointalk' allowed_domains = ['bitcointalk.org'] start_urls = [ 'https://bitcointalk.org/index.php?board=1.0', ] def parse(self, response): topics = response.css('div.tborder table.bordercolor'...
1,758
541
from typing import Any, Optional import pyarrow as pa from fugue.column.expressions import ( ColumnExpr, _FuncExpr, _to_col, function, ) from triad import Schema def coalesce(*args: Any) -> ColumnExpr: """SQL ``COALESCE`` function :param args: If a value is not :class:`~fugue.column.expressi...
9,770
3,130
# biglittle.entity.user # tell python where to find module source code import os,sys sys.path.append(os.path.realpath('../../../src')) from biglittle.entity.base import Base class Name(Base) : formFieldPrefix = 'name_' fields = { 'title' : '', 'first' : '', 'middle' : '', 'la...
1,968
623
# enabled testing relative paths
32
6
from functools import reduce from itertools import groupby from operator import add, itemgetter def merge_records_by(key, combine): return lambda first, second: { k: first[k] if k == key else combine(first[k], second[k]) for k in first } def merge_list_of_records_by(key, combine): keypr...
497
160
class Cpf: def __init__(self, documento): documento = str(documento) if self.cpf_eh_valido(documento): self.cpf = documento else: raise ValueError("CPF inválido!") def cpf_eh_valido(self, documento): if len(documento) == 11: return True ...
704
236
from selenium import webdriver from config import Config from db import cursor def get_venues(): driver = webdriver.Chrome() try: driver.get("https://tickets.edfringe.com/venues") while True: venues_container = driver.find_element_by_class_name("venues") for venue in ...
1,484
455
#!/usr/bin/env python # -*- coding: utf-8 -*- """This program prompts for a password.""" import authentication import getpass def login(username, maxattempts=3): """This function takes input from a user and checks the password. Arg: username(str): String input from user. maxattempts...
1,437
364
import unittest import logging import xml.etree.ElementTree as et import dscraper.utils as utils logger = logging.getLogger(__name__) class TestUtils(unittest.TestCase): XML_FILES = ( 'tests/resources/1.xml', ) def setUp(self): pass
267
90
import numpy as np import cv2 import glob from matplotlib import pyplot as plt class CameraCalibration(): def __init__(self): pass # =========================================================== # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @staticmethod def find_chess(frame...
7,491
2,313
from app.database.base_class import Base from app.models.place import Place
75
20
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. import torch import torch.nn as nn from .sdc_darknet import SDCCSPDarknet # from .simo_darknet import SIMOCSPDarknet from .network_blocks import BaseConv, CSPLayer, DWConv from .network_blocks import get_activatio...
3,499
1,256
from benchmark.benchmark import Benchmark from mysqlutils.mysqladapter import MySQLAdapter class MysqlBenchmark(Benchmark): """Abstract parent class for mysql benchmarks""" def __init__(self, adapter, title, repeat_count=7): super().__init__(title, repeat_count=repeat_count) self.adapter = ad...
326
87
import unittest from minos.common import ( MinosException, ) from minos.networks import ( MinosNetworkException, ) class TestExceptions(unittest.TestCase): def test_type(self): self.assertTrue(issubclass(MinosNetworkException, MinosException)) if __name__ == "__main__": unittest.main()
316
103
from .Weltantschauung import Weltantschauung
45
14
__author__ = 'Vincent' from protorpc import messages class CsvFile(messages.Message): file = messages.BytesField(1, required=True) name = messages.StringField(2, required=False)
187
59
import os import numpy as np import tensorflow as tf from models.config import Config from models.memory_gan import MemoryGAN from models.test_generation import test_generation from models.train import train from utils import pp, visualize, to_json os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' flags = tf.app.flags flags....
1,510
525
from django.views import View from django.http import HttpResponseRedirect from add2cal import Add2Cal from pytz import timezone import datetime from django.http import ( JsonResponse, HttpResponse ) ADD2CAL_DATE_FORMAT = "%Y%m%dT%H%M%S" CALENDAR_CONTENT_TYPE = 'text/calendar' OUTLOOK_LINK_TYPE = 'outlook' GOO...
2,164
641
""" Slixmpp: The Slick XMPP Library Copyright (C) 2020 "Maxime “pep” Buquet <pep@bouah.net>" This file is part of Slixmpp. See the file LICENSE for copying permission. """ from slixmpp.xmlstream import ElementBase NS = 'urn:xmpp:occupant-id:0' class OccupantId(ElementBase): ''' An Occupant...
1,174
419
"""Traffic counts _jobs file.""" import pandas as pd import logging from subprocess import Popen, PIPE from trident.util import general conf = general.config fy = general.get_FY_year() def get_traffic_counts(out_fname='traffic_counts_file'): """Get traffic counts file from shared drive.""" logging.info(f'Ret...
3,458
1,141
import os import subprocess import json from metaquantome.util.utils import BASE_DIR from metaquantome.classes.SampleGroups import SampleGroups def run_viz(plottype, img, infile, strip=None, mode=None, meancol=None, nterms='5', target_rank=None, barcol=6, # barplot, stacked_bar textannot=Non...
2,624
911
import json import multiprocessing import os import requests from requests_oauthlib import OAuth1 from time import sleep import tweepy def get_users_single(x,auth,output_folder): while(True): url=f"https://api.twitter.com/1.1/users/lookup.json?user_id={','.join([str(i) for i in x])}" if(type...
7,173
2,405
# -*- coding: utf-8 -*- """ Utilities for reading and writing USID datasets that are highly model-dependent (with or without N-dimensional form) Created on Tue Nov 3 21:14:25 2015 @author: Suhas Somnath, Chris Smith """ from __future__ import division, print_function, absolute_import, unicode_literals from warnings ...
49,924
14,934
#!/usr/bin/python import json import timeit import re import TaxPy.db_management.db_wrap as TaxDb from itertools import izip def retrieveReads(userName,fileName,fileId,parentTaxId,query): time1 = timeit.default_timer() taxTree = loadTaxTree(userName,fileName) time2 = timeit.default_timer() print str...
3,110
1,006
# Copyright (c) 2020-20201, Lawrence Livermore National Security, LLC. # See top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import setuptools from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with ope...
1,209
405
#! /usr/bin/env python """ Learning Series: Network Programmability Basics Module: Programming Fundamentals Lesson: Python Part 2 Author: Hank Preston <hapresto@cisco.com> common_vars.py Illustrate the following concepts: - Code reuse imported into other examples """ shapes = ["square", "triangle", "circle"] books =...
774
223
from flask_wtf import Form from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange from wtforms.widgets import SubmitInput class SignUp(Form): username = TextFie...
4,118
1,249
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1,137
293
import torch from shape_utils import Shape, load_shape_pair, scatter_shape_pair from torch_geometric.nn import knn from param import * from arap_potential import arap_vert def load_multiscale_shapes(folder_path, file_name, scales, offset=0.5*torch.ones([3], device=device, dtype=torch.float32)): """Like 'load_shap...
4,657
1,704
import numpy as np import scipy import scipy.linalg as linalg import scipy.spatial import scipy.special import scipy.optimize import sklearn def bases(name): if name == 'linear': f = lambda x: x elif name == 'cubic': f = lambda x: x**3 elif name == 'multiquadric': f = lambda x, s: ...
7,919
2,746
from django.contrib import admin from .models import * class ProductAdmin(admin.ModelAdmin): list_display=['name','category','price_is'] prepopulated_fields = {"slug": ("name",)} class CartAdmin(admin.ModelAdmin): list_display=['item','user','created'] class OrderAdmin(admin.ModelAdmin): list_displ...
523
162
""" Test of the cancellation of terms in the calculation of tidal energy flux. This will follow Mofjeld's notation. F is proportional to the energy flux of the original signal, and FF is proportional to the sum of the energy fluxes of the incident and reflected waves. RESULT: The two net fluxes are only equal for ze...
1,063
447
from recipe_compiler.recipe import Recipe from recipe_compiler.recipe_category import RecipeCategory def test_recipe_slug(): # Given name = "Thomas Eckert" residence = "Seattle, WA" category = RecipeCategory("dessert") recipe_name = '"Pie" Shell Script' quote = "Hello, World" ingredients =...
552
176
from flask_restplus import Namespace, fields class UserDataModel(object): """Represents the user data transfer object.""" api = Namespace( 'user', description='user authentication and signup resources' ) this_user = api.model('Register input data', { 'username': fields.String( ...
2,140
538
# -*- coding: utf-8 -*- """ Created on Wed May 27 18:48:24 2020 @author: Christopher Cheng """ class Stack(object): def __init__ (self): self.stack = [] def get_stack_elements(self): return self.stack.copy() def add_one(self, item): self.stack.append(item) def add_many(self,ite...
1,409
479
""" The script declares functions used in 'data_analysis.py' """ import os import yaml from logzero import logger import matplotlib.pyplot as plt import seaborn as sns from matplotlib.patches import Patch import plotly.graph_objects as go from utility import parse_config config_path = "config/config.yaml" con...
2,657
1,058
from django.contrib import admin from crawller.models import User # Register your models here. admin.site.register(User)
122
34
"""Configuration is a base class that has default values that you can change during the instance of the client class""" from typing import Callable BASE_URL = "https://config.feature-flags.uat.harness.io/api/1.0" MINUTE = 60 PULL_INTERVAL = 1 * MINUTE class Config(object): def __init__(self, base_url: str = BA...
987
297
from django.core.management.base import BaseCommand from users.models import Major, Minor, Course from django.db import IntegrityError from os import path import json class Command(BaseCommand): def _create_majors(self): base_path = path.dirname(__file__) majors_path = path.abspath(path.join(base_...
1,705
493
#!/usr/bin/env python3 import isce from isceobj.Sensor import createSensor import shelve import argparse import os from isceobj.Util import Poly1D from isceobj.Planet.AstronomicalHandbook import Const from mroipac.dopiq.DopIQ import DopIQ import copy def cmdLineParse(): ''' Command line parser. ''' ...
2,041
753
"""Tests for qr.py.""" from jax import lax import jax.numpy as jnp import numpy as np import pytest import tempfile from distla_core.linalg.utils import testutils from distla_core.linalg.qr import qr_ooc from distla_core.utils import pops DTYPE = jnp.float32 seeds = [0, 1] flags = [True, False] def _dephase_qr(R,...
2,794
1,187
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # Copyright 2015 and onwards Google, 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/license...
7,940
2,601
import wpilib import constants import swerve import lift import winch import sys from teleop import Teleop from autonomous.baseline_simple import Autonomous from sensors.imu import IMU def log(src, msg): try: full_msg = "[{:.3f}] [{}] {}".format( wpilib.Timer.getMatchTime(), str(src), str(msg)...
7,735
2,402
import requests text = "0123456789abcdefghijklmnopqrstuvwxyz_}" flag = "hsctf{" for _ in range(30): time = [0.1 for _ in range(38)] for _ in range(5): for i in range(38): payload = {"password": flag + text[i]} r = requests.post( "https://networked-password.we...
593
206
r"""This module contains the essential classes for the "Cover-tree with friends" algorithm, namely: - :class:`CoverTree` - :class:`CoverLevel` This module also defines the constants - :code:`ratio_Ag` :math:`=\sqrt{2} - 1=0.414\ldots`, the inverse of the silver ratio - :code:`ratio_Au` :math:`=\frac{...
47,367
14,792
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """This mo...
3,936
1,086
import pandas import requests with open('avengers.csv', 'w') as file: file_url = 'https://raw.githubusercontent.com/fivethirtyeight/data/master/avengers/avengers.csv' response = requests.get(file_url) file.write(response.text) with open('avengers.csv', 'r') as file: data_frame = pandas.read_csv(file)
320
111
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'custominvocationcutdurationdialog.ui' # # Created by: PyQt4 UI code generator 4.11.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeErro...
3,997
1,164
import json import time import torch import urllib import sys if __name__ == "__main__": start = time.time() model = torch.hub.load('pytorch/vision:v0.6.0', 'alexnet', pretrained=True) # assert time.time() - start < 3, "looks like we just did the first-time download, run this benchmark again to get a clean...
1,393
507
# class Circle(object): # pi = 3.14 # # O círculo é instanciado com um raio (o padrão é 1) # def __init__(self, radius=1): # self.radius = radius # # Método de cálculo da área. Observe o uso de si mesmo. # def area(self): # return self.radius * self.radius * Circle.pi # # Mét...
2,885
1,152
#!/usr/bin/env python try: from typing import Any, Dict, Union, Optional except: pass import time import string import boto3 import random import zstd import sys def rand_str(l): # type: (int) -> str return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in ran...
1,126
402
#!/usr/bin/env python3 import requests, json, threading, sys import collections, os, time from bot.lib.economy import EconomyInit from bot.lib.core.benchmark import Benchmark from bot.lib.core.log import Log from bot.helpers.color_helper import ColorHelper from bot.helpers.rybot_helper import RyBotHelper fr...
2,773
825
def wordPower(word): num = dict(zip(string.ascii_lowercase, range(1,27))) return sum([num[ch] for ch in word])
120
46
import sys import math def contiguous_mapper(mpi_rank, mpi_size, num_endpoints): group_size = math.ceil(mpi_size/num_endpoints) # round up local_id = mpi_rank % group_size group_id = mpi_rank // group_size return (group_id, local_id) def generate_endpoint_file(endpoint_list, mpi_size, mapper_func): ...
827
305
from keras.preprocessing import image from keras.applications import vgg16 from keras.applications.vgg16 import VGG16 from keras.applications import inception_v3, mobilenet, xception from keras.models import load_model import matplotlib.pyplot as plt import csv import argparse import os import numpy as np from utils...
7,079
2,488
from __future__ import absolute_import import argparse import logging import multiprocessing import os import sys import uuid from os.path import join, exists import yaml from phigaro.context import Context from phigaro.batch.runner import run_tasks_chain from phigaro.batch.task.path import sample_name from phigaro....
8,924
2,781
import math RangeType = 'Range' BinaryType = 'Binary' class Hipothesis: def __init__(self, id, name, p): self.id = id self.name = name self.p = p class Attribute: def __init__(self, id, name, question, _type): self.id = id self.name = name self.question = quest...
1,551
561
import unittest from ape.load_bin_log import LoadBinLog class LoadBinTestCase(unittest.TestCase): def test_LoadBinLogAll(self): data = LoadBinLog("../tests/log_0_2020-5-1-14-53-42.bin") self.assertGreater(len(data), 0, "no data") def test_LoadBinLogString(self): data = LoadBinLog(".....
926
399
import json import logging from .errors import MaxRetriesExceededException, DecoratorApplyException MAX_ATTEMPTS = 6 class KinesisClient(object): def __init__(self, writer, reader): """ Writes and reads messages to and from Kinesis streams :param writer: handles writing of payloads to K...
4,997
1,253
''' 剑指 Offer 10- II. 青蛙跳台阶问题 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 提示: 0 <= n <= 100 ''' ''' 思路:递归 ''' class Solution: def numWays(self, n: int) -> int: if n == 0: return 1 if n == 1: return 1 if n ...
516
345
from conans import ConanFile, tools, AutoToolsBuildEnvironment from conans.errors import ConanInvalidConfiguration import os class LibmountConan(ConanFile): name = "libmount" description = "The libmount library is used to parse /etc/fstab, /etc/mtab and /proc/self/mountinfo files, manage the mtab file, evalua...
2,624
829
"""An NNTP client class based on: - RFC 977: Network News Transfer Protocol - RFC 2980: Common NNTP Extensions - RFC 3977: Network News Transfer Protocol (version 2) Example: >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print('Group', name, 'ha...
36,246
10,549
from src.spotlight.errors import REQUIRED_WITH_ERROR from .validator_test import ValidatorTest class RequiredWithTest(ValidatorTest): def setUp(self): self.other_field = "test1" self.field = "test2" self.required_with_error = REQUIRED_WITH_ERROR.format( field=self.field, other=...
3,463
1,117
BASE_URL="https://harpers.org/sections/readings/page/" N_ARTICLE_LINK_PAGES = 50 OUTPUT_FILE = 'harpers-later-urls.json' WORKER_THREADS = 32 import json import datetime import dateutil.parser from dataclasses import dataclass from dataclasses_json import dataclass_json from datetime import datetime from newspaper imp...
3,194
943
from typing import Dict import numpy as np import torch from torch.nn.functional import linear, log_softmax, embedding from torch.nn import Dropout, LogSoftmax, NLLLoss from allennlp.common import Params from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary, DEFAULT_PADDING_TOKEN from...
8,711
2,621
from api.cases.models import Case class Query(Case): """ Base query class """ pass
102
33