text
string
size
int64
token_count
int64
from asyncio import get_event_loop from dataclasses import dataclass, field from typing import Dict, List, Optional, Union from aiohttp import ClientSession from pydantic import BaseModel from sgqlc.endpoint.base import BaseEndpoint from sgqlc.operation import Operation from sgqlc_schemas.github.schema import ( Ad...
3,443
1,052
import time import datetime from apscheduler.schedulers.background import BackgroundScheduler from financialdata.producer import Update from loguru import logger def sent_crawler_task(): # 將此段,改成發送任務的程式碼 # logger.info(f"sent_crawler_task {dataset}") today = datetime.datetime.today().date().strftime("%Y-%...
851
353
import matplotlib.pyplot as plt from matplotlib import cm import numpy as np def scatter_tokamak_source(source, quantity=None, **kwargs): """Create a 2D scatter plot of the tokamak source. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html for more arguments. Args: s...
2,692
847
#Exercício046 from time import sleep import emoji print('\033[32mCONTAGEM REGRESSIVA PARA O ANO NOVO:\033[m') sleep(1) for c in range(10, 0 - 1, -1):#repete os números de 10 até o 0 print(c) sleep(1) print(emoji.emojize("\033[31m:boom::boom::boom:KABUM:boom::boom::boom:", use_aliases=True)) print(emoji.emojize(...
620
319
import abc import math from ... import constants class Rule(abc.ABC): def __init__(self, failure_bin, **kwargs): self.failure_bin = failure_bin self.enabled = kwargs.get("enabled", True) self.threshold = kwargs.get("threshold", float("nan")) self.rule_name = kwargs.get("rule_name"...
10,989
3,598
# Copyright 2022 Maximilien Le Clei. # # 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 w...
1,959
793
from sys import argv from os.path import splitext from lxml import etree from struct import pack def main(): print(argv) gpx = argv[1] """ bryton: 1: go ahead 2: right 3: left 4: slight right 5: slight left 6: close right 7: close left ...
3,306
1,258
import pandas as pd import smartplots3_setup def createSetup(name,expansion_factor,percapita_factor,plot_size,settings): plt_setup_smart={ 'name': name, 'expansion_factor':expansion_factor, 'percapita_factor':percapita_factor, 'scenarios_itr': [], 'scenarios_id':[], ...
5,022
2,229
from genrl.deep.agents.sac.sac import SAC # noqa
50
23
import os import sys def main(): print 'const char* ya_get_symbolizer_gen() {' print ' return "{}";'.format(os.path.join(os.path.dirname(sys.argv[1]), 'llvm-symbolizer')) print '}' if __name__ == '__main__': main()
238
89
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import time import schedule dir = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] sys.path.append(dir) from utilities.prompt_format import item from unosat_flood_portal_collect import collect as Collect def Wrapper(patch=False): '''Wrap...
775
278
# python # import warnings # Third party imports import numpy as np # grAdapt from .base import Initial from grAdapt.utils.sampling import sample_corner_bounds class Vertices(Initial): """ Samples vertices if n_evals >= 2 ** len(bounds). Else low discrepancy sequences are sampled. """ def __ini...
1,916
529
"""Base Module.""" from abc import ABC, abstractmethod from typing import Callable, Dict, List, Optional, Union, cast from eth_account.account import LocalAccount from thirdweb_web3 import Web3 from thirdweb_web3.types import TxReceipt from zero_ex.contract_wrappers import TxParams import json from ..abi.coin import ...
6,456
1,952
# Copyright 2021 Jacob Durrant # 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, sof...
17,356
5,928
from discord.gateway import DiscordWebSocket, utils, _log, KeepAliveHandler, ReconnectWebSocket async def received_message(self, msg, /): if type(msg) is bytes: self._buffer.extend(msg) if len(msg) < 4 or msg[-4:] != b'\x00\x00\xff\xff': return msg = self._zlib.decompre...
4,181
1,333
import numpy as np np.random.seed(123) # for reproducibility from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from dataset_pothole import pothole from keras.models import model_from_j...
2,207
870
import hashlib import random import string import logging from django.db import models LOG = logging.getLogger(__name__) class Device(models.Model): name = models.CharField(max_length=50, unique=True) customer = models.CharField(max_length=50) agent_status = models.CharField(max_length=10, default="off...
2,094
677
# flake8:NOQA """Python asteroid airburst calculator""" from .solver import * from .damage import * from .locator import * from .mapping import *
147
51
from django.contrib.auth import SESSION_KEY from django.core.cache import cache from django.conf import settings from django.http import HttpResponse, HttpResponseServerError from proxy_server.response import AJAX_REQUEST import httplib, json, proxy_server def invoke_backend_service(method, function_path, json_data=di...
8,235
2,164
# from peewee import * from playhouse.apsw_ext import TextField, IntegerField, PrimaryKeyField from py.trawl_analyzer.Settings import SensorsModel as BaseModel # database = SqliteDatabase('data\clean_sensors.db', **{}) class UnknownField(object): def __init__(self, *_, **__): pass class EnviroNetRawFiles(Base...
1,645
604
import transitions from functools import partial # from transitions import transitions.Machine # TODO: whenever there is a state chage store the following # (DAY,function_called) -> Stored for every person for agent status, state and Testing state class AgentStatusA(object): """The Statemachine of the agent""" stat...
9,754
3,902
import os import scipy.io.wavfile as wav # install lame # install bleeding edge scipy (needs new cython) fname = 'XC135672-Red-winged\ Blackbird1301.mp3' oname = 'temp.wav' cmd = 'lame --decode {0} {1}'.format( fname,oname ) os.system(cmd) data = wav.read(oname) # your code goes here print len(data[1])
304
131
"""Config flow for Eva Calor.""" from collections import OrderedDict import logging import uuid from pyevacalor import ( # pylint: disable=redefined-builtin ConnectionError, Error as EvaCalorError, UnauthorizedError, evacalor, ) import voluptuous as vol from homeassistant import config_entries from h...
2,612
756
# Dataview.py # import json from .DataviewQuery import DataviewQuery from .DataviewMapping import DataviewMapping from .DataviewIndexConfig import DataviewIndexConfig from .DataviewGroupRule import DataviewGroupRule class Dataview(object): """ Dataview definition """ def __init__( self, ...
6,608
1,772
from tkinter import * window0 = Tk() window0.geometry('960x540') #tk.iconbitmap(default='ROBO_BEV_LOGO.ico') window0.title("BARISTO") photo = PhotoImage(file="Page1.png") widget = Label(window0, image=photo) widget.photo = photo widget = Label(window0, text="10", fg="white", font=("Source Sans Pro",50)) #widget = L...
392
157
from os import path from telethon import Client from telethon.types import Message, Voice from callsmusic import callsmusic, queues import converter from downloaders import youtube from config import BOT_NAME as bn, DURATION_LIMIT from helpers.filters import command, other_filters from helpers.decorators import err...
2,354
734
from __future__ import annotations from constants import DBL_EPSILON class DeltaProp(object): def __init__(self, cp: float, h: float, s: float, g: float, u: float, a: float): self.Cp = cp self.H = h self.S = s self.G = g self.U = u self.A = a def subtract(self...
2,662
1,030
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Brief: Produces rand disjoint communities (clusters) for the given network with sizes similar in the ground truth. :Description: Takes number of the resulting communities and their sizes from the specified groundtruth (actually any sample of the community structure, ...
8,240
3,022
import numpy as np import cv2 import os import torch import os import time from torchvision import models, transforms from torch.utils.data import DataLoader from torch.optim import SGD from torch.autograd import Variable idx2catename = {'voc20': ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair',...
17,578
6,141
COGNITO = "Cognito" SERVERLESS_REPO = "ServerlessRepo" MODE = "Mode" XRAY = "XRay" LAYERS = "Layers" HTTP_API = "HttpApi" IOT = "IoT" CODE_DEPLOY = "CodeDeploy" ARM = "ARM" GATEWAY_RESPONSES = "GatewayResponses" MSK = "MSK" KMS = "KMS" CWE_CWS_DLQ = "CweCwsDlq" CODE_SIGN = "CodeSign" MQ = "MQ" USAGE_PLANS = "UsagePlans...
453
244
import onnx import onnxruntime import torch import onnx.numpy_helper # added by huxi, load rpn config from pcdet.pointpillar_quantize_config import load_rpn_config_json # ======================================== config_dict = load_rpn_config_json.get_config() onnx_model_file = config_dict["vfe_onnx_file"] onnx_mode...
2,373
911
from sklearn.cluster import KMeans from .exceptions import KMeansException from .task import Task class Cluster(Task): """ Use the K-Means algorithm to group pixels by clusters. The algorithm tries to determine the optimal number of clusters for the given pixels. """ def __init__(self, settings=N...
1,825
566
# # @license BSD-3-Clause # # Copyright (c) 2019 Project Jupyter Contributors. # Distributed under the terms of the 3-Clause BSD License. import IPython.display import pandas def output_url(url): IPython.display.publish_display_data( {"application/x.jupyter.relative-dataset-urls+json": [url]} )
315
112
import django.conf url_bases = { 'geonames': { 'dump': 'http://download.geonames.org/export/dump/', 'zip': 'http://download.geonames.org/export/zip/', }, } india_country_code = 'IN' files = { 'state': { 'filename': '', 'urls': [ url_bases['geonames']['dump'] + ...
1,154
355
from decimal import Decimal from typing import List from src.dao.dao import DAO from src.dto.attempt_dto import AttemptDTO from src.entity.evaluation_entity import EvaluationEntity from src.utils.utils import Utils class EvaluationDAO: @staticmethod def create(summation: Decimal, funds: str, attempt: Attempt...
1,588
507
#! /usr/bin/python import requests import re from bs4 import BeautifulSoup import colors class FindingComments(object): def __init__(self, url): self.url = url self.comment_list = ['<!--(.*)-->'] self.found_comments = {} def get_soure_code(self): resp_text = requests.get(sel...
1,031
291
d = {"1": "a"} d[1] d["1"]
27
20
#!/usr/bin/python # This program revises the existing overview file. # If a keyword is found in an Abstract of an accession of a gene, the url of the abstract is added to the overview file # The revised overview.txt is created in the same directory of the old one and named overview_new.txt """ Usage: link_assignment.py...
2,753
973
from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from .models import * import cloudinary import cloudinary.uploader import cloudinary.api from django.http import HttpResponseRedirect, JsonResponse from .forms import RegistrationForm, UpdateUserForm...
5,421
1,565
import FreeCAD, FreeCADGui from arch_texture_utils.resource_utils import iconPath import arch_texture_utils.qtutils as qtutils from arch_texture_utils.selection_utils import findSelectedTextureConfig class ExportTextureConfigCommand: toolbarName = 'ArchTexture_Tools' commandName = 'Export_Config' def Get...
1,557
413
EDGE = '101' MIDDLE = '01010' CODES = { 'A': ( '0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011' ), 'B': ( '0100111', '0110011', '0011011', '0100001', '0011101', '0111001', '0000101', '0010001', '0001001', '0010111' ...
597
409
# -------------- import pandas as pd from sklearn.model_selection import train_test_split #path - Path of file # Code starts here df = pd.read_csv(path) df.head(5) X = df.drop(['customerID','Churn'],1) y = df['Churn'] X_train,X_test,y_train,y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # --...
2,787
1,069
import argparse, time, logging, os, math, random os.environ["MXNET_USE_OPERATOR_TUNING"] = "0" import numpy as np from scipy import stats import mxnet as mx from mxnet import gluon, nd from mxnet import autograd as ag from mxnet.gluon import nn from mxnet.gluon.data.vision import transforms from gluoncv.model_zoo im...
16,566
6,058
#!/usr/bin/env python # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
59,644
18,490
from pupa.scrape import Jurisdiction from legistar.ext.pupa import LegistarPeopleScraper class Jonesboro(Jurisdiction): division_id = 'ocd-division/country:us/state:ar/place:jonesboro' jurisdiction_id = 'ocd-jurisdiction/country:us/state:ar/place:jonesboro/government' name = 'Jonesboro City Council' ...
424
165
import yaml import os def parse_config(args): """ prepare configs """ file_dir = os.path.dirname(os.path.realpath('__file__')) messytable_dir = os.path.realpath(os.path.join(file_dir, '..')) config_pathname = os.path.join(messytable_dir,'models',args.config_dir,'train.yaml') config = yaml....
2,766
991
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '!t_(11ght0&nmb&$tf4to=gdg&u$!hsm3@)c6dzp=zdc*c9zci' # nosec INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'adminlte2_templ...
1,194
441
import argparse import numpy as np import csv if __name__ == "__main__": parser = argparse.ArgumentParser(description='fxy_gen.py generates a synthetic dataset file calling a two-variables real function on a rectangle') parser.add_argument('--dsout', type=str, d...
2,658
743
from corehq.apps.locations.util import location_hierarchy_config from custom.icds_reports.utils import icds_pre_release_features def get_dashboard_template_context(domain, couch_user): context = {} context['location_hierarchy'] = location_hierarchy_config(domain) context['user_location_id'] = couch_user.g...
995
329
import json import string, sys from random import * class Token: def __init__(self): self.company, self.website, self.email, self.username, self.password = None, None, None, None, None def get_input(self): while(self.company in (None,'')): self.company = input('Account Association:') if(self.company in (N...
1,714
619
from boa_test.tests.boa_test import BoaTest from boa.compiler import Compiler from neo.Settings import settings from neo.Prompt.Commands.BuildNRun import TestBuild class TestContract(BoaTest): def test_dict1(self): output = Compiler.instance().load('%s/boa_test/example/DictTest1.py' % TestContract.dirna...
1,401
458
from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['tensorflow==1.8.0','pandas==0.23.1','setuptools==38.7.0','numpy==1.14.1','Keras==2.1.4','scikit_learn==0.19.1','h5py'] setup( name='classifier', version='0.1', install_requires=REQUIRED_PACKAGES, packages=find_pack...
520
201
import sys import copy def main(): in_file = open(sys.argv[1], 'r') jumps = [] for line in in_file.readlines(): jumps.append(int(line.strip())) #print(compute_exit(jumps)) print(compute_exit2(jumps)) def compute_exit(jump_list): current_ind = 0 step_num = 0 while True: ...
1,023
354
import os from contextlib import contextmanager from tempfile import NamedTemporaryFile from typing import Optional, Sequence from pydantic import BaseModel, Field, FilePath @contextmanager def temp_config(**kwargs): """A context manager that creates a temporary config file for SIMReconstructor. `**kwargs` ...
4,949
1,472
import os import json import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument( '--input', help='Path to input files or folder\ with tesseract dict format.\ File name structure \ [IMAGE_NAME]___te...
4,098
1,169
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.6.0-bd605d07 on 2018-12-20. # 2018, SMART Health IT. import os import io import unittest import json from . import contract from .fhirdate import FHIRDate class ContractTests(unittest.TestCase): def instantiate_from(self, filename): ...
24,525
8,898
import math import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from scipy.stats import ttest_ind from sklearn.preprocessing import LabelEncoder def load_data(): questionnaire = pd.read_excel('XAutoML.xlsx') encoder = LabelEncoder() encoder.classes_ = np.array([...
9,978
3,815
""" ***************** Specifying Colors ***************** Matplotlib recognizes the following formats to specify a color: * an RGB or RGBA (red, green, blue, alpha) tuple of float values in closed interval ``[0, 1]`` (e.g., ``(0.1, 0.2, 0.5)`` or ``(0.1, 0.2, 0.5, 0.3)``); * a hex RGB or RGBA string (e.g., ``'#0f0f...
4,941
1,838
# List Comprehensions ######################### ### Basic List Comprehensions ######################### # allow us to circumvent constructing lists with for loops l = [] # The Old Way for n in range(12): l.append(n**2) [n ** 2 for n in range(12)] # Comprehension way # General Syntax: # [ ...
1,313
480
# -*- coding: utf-8 -*- """CLI for Chemical Roles exporters.""" import os import click from ..constants import DATA @click.group() def export(): """Export the database.""" @export.command(name='all') @click.pass_context def export_all(ctx): """Export all.""" ctx.invoke(summary) ctx.invoke(obo) ...
1,515
550
"""Write DRC rule decks in klayout. TODO: - add min area - define derived layers (composed rules) """ import pathlib from dataclasses import asdict, is_dataclass from typing import List, Optional try: from typing import Literal except ImportError: from typing_extensions import Literal from gdsfactory.confi...
4,681
1,670
# Generated by Django 2.0.4 on 2018-04-17 19:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180417_1613'), ] operations = [ migrations.CreateModel( name='Item', fields=[ ('...
1,620
509
#! /usr/bin/env python # coding=utf-8 #================================================================ # Copyright (C) 2019 * Ltd. All rights reserved. # # Editor : VIM # File name : image_demo.py # Author : YunYang1994 # Created date: 2019-01-20 16:06:06 # Description : # #====================...
2,173
879
import cv2 from datetime import * import time import logging import base64 import sys import os import shutil import paho.mqtt.client as mqtt from influxdb import InfluxDBClient import datetime import sys import re from typing import NamedTuple import json from dotenv import load_dotenv load_dotenv("sensor-variab...
7,090
2,340
# Note: # I add an underscore at the biginning of the variable name for example: "_variable" to prevent # conflicts with build-in variables from Oxide. # Use to manage the player's inventory. import ItemManager # Use to get player's information. import BasePlayer # The plug-in name should be the same as the ...
4,511
1,128
# encoding: utf-8 """ Parameterized decorator for catching errors and displaying them in an error popup """ from enum import Enum import npyscreen class DialogType(Enum): """ Enum defining the type of dialog. CONFIRM - the dialog waits until the user clicks OK BRIEF - the dialog appears for a few sec...
1,043
288
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Taskmaster-2 implementation for ParlAI. No official train/valid/test splits are available as of 2020-05-18, so we m...
13,043
3,764
from jmeter_api.timers.constant_throughput_timer.elements import ConstantThroughputTimer, BasedOn from jmeter_api.timers.constant_timer.elements import ConstantTimer from jmeter_api.timers.uniform_random_timer.elements import UniformRandTimer
243
70
import os import torch from torch import distributed as dist from torch import multiprocessing as mp from tensorfn import distributed as dist_fn def find_free_port(): import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", 0)) port = sock.getsockname()[1] sock.clo...
2,520
855
from enum import Enum from threading import Thread import cv2 import time class Resolution(Enum): _32p = (64, 32) _96p = (128, 96) _120p = (160, 120) _144p = (256, 144) _240p = (360, 240) _288p = (480, 272) _360p = (480, 360) _480p = (720, 480) _576p = (720, 576) _Hd = (1280, ...
4,097
1,352
from mysql.connector.pooling import MySQLConnectionPool from ._connect import _parse_kwargs, _patch_MySQLConnection class MySQLConnectionPool(MySQLConnectionPool): def set_config(self, **kwargs): kwargs = _parse_kwargs(kwargs) super(MySQLConnectionPool, self).set_config(**kwargs) def add_con...
444
130
class network_x_utils: """ This class provides commonly used utils which are shared between all different types of NetworkX nodes (Feed Items, Solutions, Myths). For each of these, we want to be able to pull basic information like the IRI, Descriptions, Images, etc. Include any generalized Networ...
4,813
1,265
# Do not manually invoke this setup.py, use catkin instead! from setuptools import setup from catkin_pkg.python_setup import generate_distutils_setup setup_args = generate_distutils_setup( packages=['vswarm'], package_dir={'': 'src'} ) setup(**setup_args)
267
86
import numpy as np nparr = np.array([i for i in range(10)]) a = np.zeros(10) f = np.zeros(10,dtype=float) n = np.full((3,5),44) r = np.random.randint(0,100,size=(3,5)) r2 = np.random.random((3,5)) x = np.linspace(0,100,50) print(nparr,a,f,n,r,r2,x)
250
141
''' Function: 微博监控 Author: Charles 微信公众号: Charles的皮卡丘 ''' import re import time from DecryptLogin import login '''微博监控''' class WeiboMonitor(): def __init__(self, username, password, time_interval=30): _, self.session = self.login(username, password) self.headers = { 'Accep...
4,790
1,677
from godot.bindings import ResourceLoader from crawlai.grid_item import GridItem from crawlai.items.food import Food from crawlai.math_utils import clamp from crawlai.turn import Turn from crawlai.position import Position _critter_resource = ResourceLoader.load("res://Game/Critter/Critter.tscn") class BaseCritter(G...
1,191
507
# -*- coding: utf-8 -*- # Copyright: (c) 2015, Peter Sprygada <psprygada@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = r''' options: provider: descriptio...
3,008
773
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. #!/usr/bin/env python3 import abc import math from collections import defaultdict, dequ...
25,299
7,122
__author__ = 'JohnHiness' import sys import os import random import time import string import connection from time import strftime import ceq import json, urllib2 import thread args = sys.argv req_files = ['filegen.py', 'connection.py', 'commands.py', 'general.py', 'automatics.py'] for filename in req_files: if os....
7,594
3,267
from unittest import TestCase import numpy as np from scipy.signal import fftconvolve import pyroomacoustics as pra # fix seed for repeatability np.random.seed(0) h_len = 30 x_len = 1000 SNR = 1000. # decibels h_lp = np.fft.irfft(np.ones(5), n=h_len) h_rand = np.random.randn(h_len) h_hann = pra.hann(h_len, flag='...
2,364
1,063
import cv2 as cv from deskew import determine_skew import numpy as np from PIL import Image, ImageFilter, ImageOps from pytesseract import image_to_string from skimage import io from skimage.color import rgb2gray from skimage.transform import rotate from spellchecker import SpellChecker import traceback # On Windows, ...
7,423
2,287
# Params learning_rate = 0.001 k = 0.0025 x0 =2500 epochs = 4 batch_size=16 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") import torch, numpy as np from tqdm import tqdm # Get the dataloader from dataloader import get_train_test trainStays, testStays = get_train_test(train_size=0.95, batch_siz...
3,544
1,307
# Copyright (c) 2019-2021, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import numpy import pytest import vector.backends.numpy_ import vector.backends.object_ ...
1,674
734
#!/usr/bin/env python3 import os # imports for array-handling import numpy as np import tensorflow as tf # keras imports for the dataset and building our neural network from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout # l...
3,791
1,344
import random values = [random.gauss(1, .5) for i in range(1000)]
67
29
class Display(): def __init__(self, width, height): self.width = width self.height = height def getSize(self): return (self.width, self.height)
155
57
# This python script handles stock api request from yfinance # Last Updated: 4/7/2020 # Credits:nóto #Import yfinance api lib import yfinance as yf #Import pandas lib import pandas as pd #Import json to manipulate api data import json #Import math import math class StockApi(): def __init__(self): self.pan...
2,091
647
from datetime import date from random import randrange import factory import factory.fuzzy from hth.core.tests.utils import from_today class VenueFactory(factory.django.DjangoModelFactory): class Meta: model = 'shows.Venue' name = factory.Sequence(lambda n: 'Venue %d' % n) city = factory.Sequ...
1,493
498
"""Support for Eight Sleep binary sensors.""" from __future__ import annotations import logging from pyeight.eight import EightSleep from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.enti...
2,143
698
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # # pylint: disable=invalid-name # pylint: disable=missing-module-docstring import os from typing import Any, Dict, Iterator, Tuple from tensorbay.dataset import Data, Dataset from tensorbay.exception import ModuleImportError from tensorba...
3,384
1,057
def get_time(time_in_seconds): import datetime time_str = str(datetime.timedelta(time_in_seconds)) time_fractions = time_str.split(":") time_fractions[0] = time_fractions[0].replace(",","") time_fractions[-1] += 's' time_fractions[-2] += 'm' time_fractions[-3] += 'h' # print(time_fracti...
3,925
1,360
# coding: utf-8 """ Copyright 2018 OSIsoft, 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 t...
3,391
1,294
#! /root/anaconda3/bin/python import os from apscheduler.schedulers.asyncio import AsyncIOScheduler from pyrogram import Client, filters from read_config import read_config import json import requests import schedule import time def get_value_usd(sum): price = requests.get('https://api.coingecko.com/api/v3/simple/...
4,054
1,530
# Copyright (c) AIRBUS and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import Dict, Tuple from skdecide.discrete_optimization.rcpsp_multiskill.rcpsp_multiskill import ( E...
7,622
2,761
import logging # monkey patch to suppress the annoying warning you get when you import apache_beam # # No handlers could be found for logger "oauth2client.contrib.multistore_file" # # This warning is harmless, but annooying when you are using beam from a command line app # see: https://issues.apache.org/jira/browse/BE...
530
154
from django.db import models class SoftDeleteManager(models.Manager): def save_soft_delete(self): self.is_deleted = True self.save() return True def get_soft_delete(self): return self.filter(is_deleted=True) def get_unsoft_delete(self): return self.filter(is_delet...
330
105
""" All scales have a means by which the values that are mapped onto the scale are interpreted. Numeric digital scales put out numbers for direct interpretation, but most scales cannot do this. What they offer is named markers/ticks that aid in assessing the values e.g. the common odometer will have ticks and values to...
22,286
7,029
# Copyright 2022 NREL # 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 # distri...
2,412
831
import numpy import numpy as np # converting to a layer with 4 input and 3 neuron inputs = [[1.2, 2.1, 3.4, 1.2], [1.2, 2.1, 3.4, 1.2], [1.2, 2.1, 3.4, 1.2]] print(numpy.shape(inputs)) weights = [[4.1, -4.5, 3.1, 2.3], [-4.1, 4.5, 2.1, 2.3], [4.1, 4.5, 3.1, -2.3]] print(numpy...
623
333
from . import models from . import views from . import commands from . import jobs
83
21