text
string
size
int64
token_count
int64
#!/usr/bin/env python from implementations import MallardDuck, WildTurkey, TurkeyAdapter if __name__ == '__main__': d = MallardDuck() print '\nThe Duck says...' d.quack() d.fly() t = WildTurkey() print '\nThe Turkey says...' t.gobble() t.fly() # Now we use the adapter to show how...
523
179
CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_IMPORTS=('app.users.tasks')
134
69
# -*- coding: utf-8 -*- from PIL import Image from numpy import array import sqlite3 import tkMessageBox import matplotlib.pyplot as plt from pybrain.tools.shortcuts import buildNetwork from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure.module...
5,697
2,106
import colander from datetime import datetime from grano.core import app, db, celery from grano.logic.validation import database_name from grano.logic.references import AccountRef from grano.plugins import notify_plugins from grano.model import Project def validate(data, project): same_project = lambda s: Projec...
2,966
792
N,K=map(int,input().split()) print("YES" if N>=2*K-1 else "NO")
63
30
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns from provider import PivotalTrackerProvider urlpatterns = default_urlpatterns(PivotalTrackerProvider)
180
52
from odoo import fields, models, api, _ from odoo.exceptions import UserError class SaleOrderPopup(models.TransientModel): _name = 'sale.order.popup' @api.multi def popup_button(self): for rec in self.env['sale.order'].browse(self._context.get('active_id')): if rec._get_forbidden_stat...
2,944
841
"""UDP hole punching server.""" from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import sys DEFAULT_PORT = 4000 class ServerProtocol(DatagramProtocol): def datagramReceived(self, datagram, address): """Handle incoming datagram messages.""" print(datagram...
830
268
from typing import Any, List, Literal, TypedDict from .FHIR_Address import FHIR_Address from .FHIR_Age import FHIR_Age from .FHIR_Annotation import FHIR_Annotation from .FHIR_Attachment import FHIR_Attachment from .FHIR_CodeableConcept import FHIR_CodeableConcept from .FHIR_Coding import FHIR_Coding from .FHIR_Contact...
12,972
3,450
from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import * from .forms import address_form from django.http import JsonResponse from .utils import cartData,guestobj import json,datetime def store(request): items = item.objects.all() data = cartData(reque...
2,484
735
import os from ecogdata.util import Bunch __all__ = ['Parameter', 'TypedParam', 'BoolOrNum', 'NSequence', 'NoneOrStr', 'Path', 'parse_param', 'uniform_bunch_case'] class Parameter: "A pass-thru parameter whose value is the command (a string)" def __init__(self, command, default=''): self...
2,899
881
"""FILE lgt_createinput.main.py This script creates condensed LPJ netcdf files for landforms and soil properties landforms.nc: - lfcnt (landid) number of landforms in cell - frac (landid, lfid/ standid) area fraction this landform represents - slope (landid, lfid/ standid) - elevation (landid, lfid/ standid) avg...
29,897
11,255
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """Скрипт проверяет дату обновления прайса на сайте http://www.dns-shop.ru/""" # # Основа взята из http://stackoverflow.com/a/37755811/5909792 # def get_html(url, check_content_func=None): # # from PyQt5.QtCore import QUrl # # from PyQt...
4,379
1,469
import pytest from dnaio import Sequence from cutadapt.adapters import ( RemoveAfterMatch, RemoveBeforeMatch, FrontAdapter, BackAdapter, PrefixAdapter, SuffixAdapter, LinkedAdapter, MultipleAdapters, IndexedPrefixAdapters, IndexedSuffixAdapters, ) def test_back_adapter_absolut...
12,918
4,775
import copy import random from .parameters import Parameters class EventModel: """Defines an event model, also called "activity" An event model is defined by these parameters: * Activity name: :obj:`str` * Schedule: :obj:`list` of :obj:`tuple` (in minutes :obj:`int`) * Repetitions range: min...
7,561
2,376
""" test photokit.py methods """ import os import pathlib import tempfile import pytest from osxphotos.photokit import ( LivePhotoAsset, PhotoAsset, PhotoLibrary, VideoAsset, PHOTOS_VERSION_CURRENT, PHOTOS_VERSION_ORIGINAL, PHOTOS_VERSION_UNADJUSTED, ) skip_test = "OSXPHOTOS_TEST_EXPORT"...
13,297
4,749
import os import sys import json def detail_base_item_list(): return [ 'distance', 'elevation', 'floors', 'heart', 'minutesFairlyActive', 'minutesLightlyActive', 'minutesSedentary', 'minutesVeryActive', 'steps' ] def read_json_file(filename): if not os.path.isfile(filename):...
2,764
1,067
import tensorflow as tf import tensorflow_datasets as tfds import numpy as np import random from utils.dataset_processing import grasp, image import matplotlib.pyplot as plt dataset_path = './tfds/' train_data, meta = tfds.load('Jacquard', split='train', with_info=True, shuffle_files=False) BATCH_SIZE = 1 number_trai...
4,251
1,732
import pytest from scylla.scheduler import Scheduler, cron_schedule @pytest.fixture def scheduler(): return Scheduler() def test_start(mocker, scheduler): process_start = mocker.patch('multiprocessing.Process.start') thread_start = mocker.patch('threading.Thread.start') scheduler.start() proc...
836
282
class Time: '''Represents the time of day. attributes: hour, minute, second ''' def print_time(t): print ('(%.2d:%.2d:%.2d)' % (t.hour, t.minute, t.second)) def is_after(t1, t2): return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second) def mul_time(t, n): '''Multiple time t by n n: int ...
2,063
867
# -*- coding: utf-8 -*- """Provider package.""" from __future__ import unicode_literals from .enzyme import EnzymeProvider from .ffmpeg import FFmpegProvider from .mediainfo import MediaInfoProvider
200
61
list = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO') for p in list: print(f'\nNa palavra {p} temos: ', end='') for l in p: if l.lower() in 'aeiou': print(l.lower(), end=' ')
304
138
from sqlalchemy import * from sqlalchemy.orm import relationship from base import Base from unit import Unit class Variable(Base): __tablename__ = 'Variables' id = Column('VariableID', Integer, primary_key=True) code = Column('VariableCode', String(255), nullable=False) name = Column('VariableName',...
1,449
455
""" Custom excel types for pandas objects (eg dataframes). For information about custom types in PyXLL see: https://www.pyxll.com/docs/udfs.html#custom-types For information about pandas see: http://pandas.pydata.org/ Including this module in your pyxll config adds the following custom types that can be used as retu...
7,751
2,438
from django.shortcuts import render import requests from bs4 import BeautifulSoup import re from collections import defaultdict as dfd from .models import * from datetime import date from datetime import timedelta from django.db.models import Sum from django.db.models import Count from django.db.models.functions impor...
10,912
4,989
from django.http import HttpResponse def health(request): return HttpResponse("OK")
89
24
from src.core import Basic import networkx as nx class RandomP(Basic): def __init__(self, server_list, network_dataset, node_list): super().__init__() self.server_list = server_list self.network_dataset = network_dataset self.node_list = node_list def add_new_primary_node(self...
11,829
3,862
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-11-28 05:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('heathen', '0002_member_gender'), ] operations = [ ...
1,336
416
from gym import spaces import numpy as np from bark.models.dynamic import StateDefinition from modules.runtime.commons.parameters import ParameterServer import math import operator from src.commons.spaces import BoundedContinuous, Discrete from src.observers.observer import StateObserver class SimpleObserver(StateO...
2,437
726
import altair as alt import pandas as pd def scatterplot(x, y, data, hue=None, color=None, opacity=1., x_autoscale=True, y_autoscale=True): """Display a basic scatterplot. Parameters ---------- x : str Column in data to be used for x-axis y : str Column in data to be used ...
9,610
3,113
import gym from gym import spaces from itertools import cycle import random import sys import os import pygame from pygame.locals import * import flappy import numpy as np import cv2 # GLOBALS FPS = 30 SCREENWIDTH = 288 SCREENHEIGHT = 512 PIPEGAPSIZE = 100 # gap between upper and lower part of pipe BASEY ...
12,103
5,145
from typing import AsyncGenerator, List, Union, Any from aiohttp.client import ClientSession from vkmini.utils import AbstractLogger from vkmini.request import longpoll_get, default_session from vkmini.exceptions import TokenInvalid from vkmini import VkApi class Update: # TODO ну тут без комментариев class...
4,587
1,414
import tarfile import pandas as pd import sqlalchemy as db from aswan import AswanConfig, ProdConfig, Project from aswan.migrate import pull, push from aswan.models import Base from aswan.object_store import get_object_store def test_push_pull(tmp_path): conf = ProdConfig.from_dir(tmp_path / "cfg") Base.me...
1,162
436
from django.apps import AppConfig class TestConfig(AppConfig): name = 'test'
82
25
import datetime as dt class Booking: def __init__(self): self.user_id = '' self.name ='' self.pet_name = '' self.time_slot = 0 self.id = '' self.phone_number = '' def to_dict(self): return { 'name' : self.name, 'petname' : self.pe...
1,055
347
## Incorrect division method ## 8 kyu ## https://www.codewars.com/kata/54d1c59aba326343c80000e7 def divide_numbers(x,y): return x / y
148
76
#!/usr/bin/env python3 import subprocess import sys from pathlib import Path import os pythonpath = sys.executable curdir = Path(__file__).parent.resolve() parentdir = curdir.parent # If openvino_env is already activated, launch jupyter lab # This will also start if openvino_env_2 is activated instead of openvino_env...
1,927
543
import os.path, os, time from datetime import datetime def getLastUpdatedTime(file: str): return datetime.fromtimestamp(os.path.getmtime(file)).isoformat() def updatePost(postUrl: str) -> None: lastUpdatedTime = getLastUpdatedTime(postUrl) prefix = "last_modified_at" string = f"{prefix}: {lastUpdated...
1,143
348
from brownie import (accounts, web3) def test_eth_to_token_swap(HAY_token, hay_token_exchange): HAY_token.approve(hay_token_exchange, 10 * 10**18, {"from": accounts[0]}) # step 1: initialize exchange hay_token_exchange.initializeExchange(10 * 10**18, {"from": accounts[0], "amount": 5 * 10**18}) # th...
4,032
1,981
from helper import greetings greetings("hi!")
49
19
from setuptools import setup setup( name="manzip", version='1.0.0', py_modules=['manzip'], install_requires=[ 'Click', ], entry_points=''' [console_scripts] manzip=app:main ''', )
232
82
from mmhelloworld import say_hello def test_say_hello_no_params(): assert say_hello() == "Hello! World" def test_say_hello_with_param(): assert say_hello("Everyone") == "Hello! Everyone"
199
69
# -*- coding: utf-8 -*- """.. moduleauthor:: Artur Lissin""" from typing import TypeVar from bann.b_container.states.general.interface.init_state import InitState from bann.b_container.states.general.interface.net_state import NetState from bann.b_container.functions.dict_str_repr import dict_string_repr from rewowr.p...
1,167
396
import numpy as np import matplotlib.pyplot as plt plt.style.use('science') import os, sys, time sys.path.insert(0,"/import/freenas-m-03-geodynamics/jhayek/petsc-3.12.5/lib/petsc/bin/") sys.path.insert(0,"/import/freenas-m-03-geodynamics/jhayek/TEAR/se2wave/utils/python") sys.path.insert(0,"/import/freenas-m-03-geod...
4,578
1,890
# coding=utf-8 # # ROSREPO # Manage ROS workspaces with multiple Gitlab repositories # # Author: Timo Röhling # # Copyright 2016 Fraunhofer FKIE # # 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 a...
3,560
1,114
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Date : 2020/8/30 # @Author : Bruce Liu /Lin Luo # @Mail : 15869300264@163.com class Card(object): """ 卡片类 """ def __init__(self, name: str, limited: bool = False, limited_num: int = 100000, surplus: int = 0): """ 初始化一张卡 :param li...
2,948
1,302
import subprocess from sys import exit result = subprocess.check_output(["ciphey", "-q", "-t 'hello'"]) if "hello" in result: exit(0) else: exit(1)
158
59
import math import os import tensorflow as tf import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import ops import utils import model_fctd import data import config import visualizations as vis FLAGS = tf.app.flags.FLAGS def test_encode_decode_synth_data(): batch_size = 50...
13,057
5,175
""" Copyright 2018 Matthew Aynalem 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...
1,432
433
# Copyright 2021 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, ...
39,732
12,597
"""Get status for split or move completed percentage of a given file duplicate volume.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting @click.command(cls=SoftLayer.CLI.command.SLCommand, epilog="...
1,007
275
from django import forms #from pagedown.widgets import PagedownWidget from apps.saas.models import Offer class OfferForm(forms.ModelForm): #content= forms.CharField(widget=PagedownWidget(show_preview=False)) #publish= forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Offer fields= [ "tipo_...
392
150
#library import os #string aphoto print(" _ _ _ _ __ __ _ _ .____ .__ ") print("| | | | ___| | | __\\ \\ / /__ _ __| | __| | | | |__| ____ __ _____ _____ __ ") print("| |_| |/ _ \\ | |/ _ \\ \\ /\\ / / _ \\|...
5,491
1,200
from options import TestOptions import torch from models import TETGAN from utils import load_image, to_data, to_var, visualize, save_image import os #os.environ["CUDA_VISIBLE_DEVICES"] = "0" def main(): # parse options parser = TestOptions() opts = parser.parse() # data loader print('--- load dat...
1,237
446
#!/usr/bin/python # load many feeds to the GTFS data manager, from a csv with fields name and url # usage: bulkLoadFeeds.py file.csv http://server.example.com/ import csv from getpass import getpass from sys import argv import json from cookielib import CookieJar import urllib2 from urllib import urlencode if len(arg...
1,853
595
import numpy as np from scipy import integrate import matplotlib.pyplot as plt from UTILS.Calculus import Calculus from UTILS.SetAxisLimit import SetAxisLimit from UTILS.Tools import Tools from UTILS.Errors import Errors import sys # Theoretical background https://arxiv.org/abs/1401.5176 # Mocak, Meakin, Viallet, Ar...
5,962
2,224
# -*- coding: utf-8 -*- from __future__ import print_function import logging from flask import url_for logger = logging.getLogger() try: from flask_weasyprint import render_pdf import_error = False except (ImportError, OSError) as e: # print(""" # Error importing flask-weasyprint! # PDF support...
953
311
from ._version import __version__ # noqa:F401 try: from .app import TerminalsExtensionApp except ModuleNotFoundError: import warnings warnings.warn("Could not import submodules") def _jupyter_server_extension_points(): # pragma: no cover return [ { "module": "jupyter_server_ter...
392
118
# By TheDestruc7i0n https://thedestruc7i0n.ca # MrGarretto for the code for traversing the command block chain https://mrgarretto.com import mcplatform import codecs __version__ = "V1.4.1" displayName = "Commands to Function" inputs = ( ("Converts a command block chain into a function.", "label"), ("The fil...
5,256
1,645
class InstanceNotFound(Exception): """ Raise if an instance is not found in the database """ class InvalidValue(Exception): """ Raise if an invalid value is given """ class OverDemand(Exception): """ Raise if excess demand is requested """ class InvalidAmount(Exception): ...
420
121
import json from flask import g, request, render_template from flask.views import View from godmode import logging from godmode.acl import ACL from godmode.audit_log import audit_log from godmode.exceptions import AccessDenied log = logging.getLogger(__name__) class BaseAction(View): name = None title = No...
2,147
656
import discord import asyncio import time import aiohttp import re import pathlib import os import json from bs4 import BeautifulSoup from datetime import datetime from models.UpdatedMessage import UpdatedMessage from models.EmbedTemplate import EmbedTemplate from models.BotMention import BotMention from f...
16,001
7,079
c = get_config() c.JupyterHub.ip = u'127.0.0.1' c.JupyterHub.port = 8000 c.JupyterHub.cookie_secret_file = u'/srv/jupyterhub/jupyterhub_cookie_secret' c.JupyterHub.db_url = u'/srv/jupyterhub/jupyterhub.sqlite' #c.JupyterHub.proxy_auth_token = u'/srv/jupyterhub/proxy_auth_token' c.ConfigurableHTTPProxy.auth_token = u'/s...
2,561
1,032
import datetime import warnings import pandas as pd import numpy as np from MongoDBUtils import * from scipy.optimize import fsolve import pymongo TRADING_FEE = 0.008 EARLIEST_DATE = datetime.datetime(2014, 10, 17) LATEST_DATE = datetime.datetime(2019, 10, 17) # In any cases, we shouldn't know today's and future val...
11,908
3,632
import torch.nn as nn class TitanicSimpleNNModel(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(12, 12) self.sigmoid1 = nn.Sigmoid() self.linear2 = nn.Linear(12, 8) self.sigmoid2 = nn.Sigmoid() self.linear3 = nn.Linear(8, 2) self...
579
240
# Generated by Django 4.0.3 on 2022-04-18 14:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('agents', '0048_remove_agent_has_patches_pending_and_more'), ] operations = [ migrations.AddIndex( model_name='agent', ...
426
155
import os import torch import numpy as np import pandas as pd from torch.utils.data import Dataset, DataLoader from scipy.spatial.distance import cdist import logging class STD_Dataset(Dataset): """Spoken Term Detection dataset.""" def __init__(self, root_dir, labels_csv, query_dir, audio_dir, apply_vad = Fal...
6,431
2,134
"""Implements a db backed storage area for intermediate results""" import sqlite3 class Store(object): """ Represents an sqlite3 backed storage area that's vaguely key value modeled for intermediate storage about metadata / data for metrics about multiple wikis that have some underlying country relate...
3,209
932
def generate_attention(path, size=(224, 224)): image = Image.open(path) image.thumbnail(size, Image.ANTIALIAS) tensor = transform(image)[None] with torch.no_grad(): logits = net(tensor)[0] probs = torch.softmax(logits, dim=0) attention_map = probs[indexes].sum(dim=0) return image, attention_map
316
124
import boto3 import dateutil import glob import json import logging import os import queue import time from queries import MetadataQueries USE_LOCAL_DATA = True # whether to load data from S3 (false) or locally (true) LOCAL_DATA_REPOSITORY = "s3data/usdot-its-cvpilot-public-data" # path to local directory containing s...
7,074
2,371
Managers = ['Shim', 'Mike', 'Ryan', 'Kevin', 'Wessa', 'ser0wl'] # google spreedsheet id ISKO_SPREADSHEET_ID = '' # the list of names with discord ID ISKO_DiscordAccount = 'DiscordAccount!A2:B100' # the list of Names, ronin address, ronin private keys # eg: # Name | Address | Privat...
1,070
479
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-08-19 03:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('character', '0015_auto_20170605_2252'), ('dominion', '0010_auto_20170511_0645'), ...
566
213
from gpiozero import Button import os from time import sleep button = Button(2) i = 0 while True: if button.is_pressed: print(i, ". I've been pressed") i += 1 sleep(0.1)
200
70
import rasterio from rasterio.plot import show, reshape_as_raster, reshape_as_image, adjust_band from rasterio import warp import numpy as np def reprojectio(img, bounds, transform, projection = "epsg:4326", resolution = 0.00001): # Reproject transform, width, height = warp.calculate_default_transform( \ ...
820
281
from logging import getLogger from queue import Empty import threading import random import time logger = getLogger('opentsdb-py') class PushThread(threading.Thread): WAIT_NEXT_METRIC_TIMEOUT = 3 def __init__(self, tsdb_connect, metrics_queue, close_client, send_metrics_limit, send_metrics...
4,034
1,171
from xlrd import open_workbook wb = open_workbook(r"C:\Users\Lenovo\Documents\excel converter.xlsx") for s in wb.sheets(): #print 'Sheet:',s.name values = [] for row in range(s.nrows): col_value = [] for col in range(s.ncols): value = (s.cell(row,col).value) ...
465
161
from apitax.drivers.Driver import Driver from apitax.utilities.Files import getAllFiles from apitax.ah.Options import Options from pathlib import Path from apitax.ah.Credentials import Credentials from apitax.utilities.Json import read from apitax.ah.State import State from apitax.utilities.Files import getPath class...
3,068
832
# my_script.py import pandas from my_lambdata.my_mod import enlarge print('HAPPY TUESDAY NIGHT') df = pandas.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) print(df.head()) x = 5 print("ENLARGE", x, "TO", enlarge(x))
220
106
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np from scipy.integrate import simps from scipy.optimize import curve_fit def curve3(x,a,b,c,d): return a*x**3+b*x**2+c*x+d def BIC(y, yhat, k, weight = 1): err = y - yhat sigma = np.std(np.real(err)) n = len(y) B = n*np.log(sigm...
1,063
624
import time import sys sys.path.append("/home/ubuntu/quokka/pyquokka") import pyarrow.compute as compute import pyarrow as pa import pandas as pd from pyquokka.quokka_runtime import TaskGraph from pyquokka.dataset import InputS3CSVDataset from pyquokka.executors import UDFExecutor, AggExecutor import ray from pyquokka....
1,225
443
"""Helper functions to initializer Websauna framework for command line applications.""" # Standard Library import logging import os import sys import typing as t # Pyramid import plaster from pyramid import router from pyramid import scripting from rainbow_logging_handler import RainbowLoggingHandler # Websauna from...
5,464
1,655
import typing as t from ..typing import T_value from ..database import DataPoint from ..exceptions import NoDataForTrigger class Trigger(t.Generic[T_value]): name: str async def start(self) -> None: """Coroutine to do any initial setup""" return async def match(self, datapoint: DataPoin...
2,010
517
#!/usr/bin/python3 import setup_run_dir # Set the working directory and python sys.path to 2 levels above import os from glob import glob from amrlib.graph_processing.amr_loading_raw import load_raw_amr # Collect all the amr graphs from multiple files and create a gold test file. # This simply concatenates fil...
1,056
340
"""empty message Revision ID: 281362c70f34 Revises: acff3391146d Create Date: 2020-05-27 16:58:11.029790 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '281362c70f34' down_revision = 'acff3391146d' branch_labels = None depends_on = None def...
1,818
624
from Histogram import Histogram from HistogramWidget import HistogramWidget from TrackingHistogramWidget import TrackingHistogramWidget
136
32
""" numpy模块 —— 数据分析 """ import numpy #创建矩阵 array = numpy.array([[1,2,3],[4,5,6]]) print(array,'\n',type(array)) #矩阵维度 print(array.ndim) #行数和列数 print(array.shape) #元素个数 print(array.size)
188
115
class Base(object): DEBUG = False TESTING = False class Production(Base): DEBUG = False TESTING = False class Staging(Base): DEBUG = True TESTING = False class Development(Base): DEBUG = True TESTING = True class Testing(Base): DEBUG = False TESTING = True
305
101
# pylint: disable=unused-wildcard-import,wildcard-import """ Please try and avoid modifying this file where possible, doing so may cause different behaviours between local (development) and production environments. Instead consider modifying the base (default) config. This way, the production config is effectively th...
395
100
#051 - Progressão Aritmética primeiro = int(input('primeiro termo: ')) razao = int(input('razao: ')) decimo = primeiro + (10 - 1) * razao for c in range(primeiro, decimo + razao, razao): print(f'{c}', end=' - ') print('acabou')
232
101
#!/usr/local/bin/python3 # coding: UTF-8 # Author: David # Email: youchen.du@gmail.com # Created: 2017-04-26 11:14 # Last modified: 2017-04-30 15:55 # Filename: rules.py # Description: import os import redis from scrapy.utils.conf import init_env from ProxyCrawl.settings import PROJECT_ROOT conn = redis.Redis(decod...
5,175
1,623
# -*- 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...
1,299
394
""" The roseguarden project Copyright (C) 2018-2020 Marcus Drobisch, This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pr...
3,469
828
import json import requests def fund_intro_dict() -> dict: headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" } url = "http://fund.eastmoney.com/js/fundcode_search.js" res = requests.get(ur...
1,157
479
from pyrentals import Cart import unittest class Test_test_pyrentals(unittest.TestCase): def test_method_empty(self): test_cart_instance = Cart() test_cart_instance.Rentals = {} return self.assertTrue(test_cart_instance.empty(), "Cart should be empty when it's just created.") def test_...
3,374
1,146
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Authors: # - Grégoire Péan <gregoire.pean@hpc-project.com> # - Ronan Keryell <ronan.keryell@hpc-project.com> # + Many others... # Beware: class p4a_scmp_compiler declared in ../scmp/p4a_scmp_compiler.py # inherits from class p4a_processor. # Maybe a common parent class...
63,514
18,902
# vim: fdm=marker ''' author: Fabio Zanini date: 12/01/15 content: Get subtype entropy from alignments, since it's used so often. ''' # Modules import os import argparse import cPickle as pickle import numpy as np from hivwholeseq.utils.miseq import alpha from hivwholeseq.utils.one_site_statistics import ...
4,790
1,365
import copy import json import itertools import os import operator from .errors import * # --------------------------------------------------- # Imports and Variables - # --------------------------------------------------- class Standard: """ Basic functionality wrappers. Do ...
15,119
4,308
from aequitas.plot.summary_chart import plot_summary_chart as summary from aequitas.plot.bubble_disparity_chart import plot_disparity_bubble_chart as disparity from aequitas.plot.bubble_metric_chart import plot_metric_bubble_chart as absolute from aequitas.plot.bubble_concatenation_chart import plot_concatenated_bubble...
425
133
import numpy as np from model import get_model def get_trained_model(): model = get_model() model.load_weights('weights.ckpt') return model #model = get_fit_model('random.tsv') #inputs_raw = [[0,0,0,0,0]] #inputs_np = np.array(inputs_raw) #print(model.predict(inputs_np))
287
114
''' @Author: dzy @Date: 2021-09-13 11:07:48 @LastEditTime: 2021-09-26 20:25:17 @LastEditors: dzy @Description: Helper functions or classes used for the model. @FilePath: /JDProductSummaryGeneration/src/predict.py ''' import random import os import sys import pathlib import torch import jieba import config from model i...
12,150
3,632