text
string
size
int64
token_count
int64
"""In this module, we modify the basic console helpers for friendly-traceback to add custom ones for Rich-based formatters.""" from friendly_traceback.console_helpers import * # noqa; include Friendly below from friendly_traceback.console_helpers import Friendly, helpers from friendly_traceback.functions_help import ...
3,424
1,002
from abc import ABC, abstractmethod import os import numpy as np from kevin.data_flow.reader import File_Iterative_Reader from kevin.data_flow.cache import Cache_Manager_for_Iterator, Strategies class Unified_Reader_Base(ABC): """ 按行读取数据的抽象基类 支持通过对以 - 内存变量 - 持久化磁盘文件 ...
10,425
3,547
import tensorflow as tf from tensorflow.contrib import layers from logger import get_logger, get_name name = get_name(__name__, __file__) logger = get_logger(name) def build_infer_graph(features, params): """ builds inference graph """ _params = { "batch_size": 32, "p_keep": 1.0, ...
5,102
1,632
import pytest from galaxy.webapps.galaxy.services.history_contents import HistoriesContentsService @pytest.fixture def mock_init(monkeypatch): monkeypatch.setattr(HistoriesContentsService, '__init__', lambda _: None) class TestSetItemCounts: """ up: number of displayed items with hid > {hid} ...
2,167
701
# -*- coding: utf-8 -*- from __future__ import unicode_literals import enum import six from django.conf import settings from django.db import models from django.utils.six import python_2_unicode_compatible, string_types from django.utils.translation import ugettext_lazy as _, ugettext postgresql_engine_names = [ ...
3,428
1,002
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import abc from dataclasses import dataclass from flsim.utils.config_utils...
3,644
1,153
import cv2 import time import threading class ThreadedImageCapture: def __init__(self, cam_width=1280, cam_height=720): self.cam_width = cam_width self.cam_height = cam_height # Set up video capture object self.vidcap = cv2.VideoCapture(0) self.vidcap.set(cv2.CAP_PROP_FRA...
1,427
464
import requests import json import random import uuid login="test" password="P@ssword" with open("dict", 'r', encoding="latin-1") as words : a = words.readlines() headers = { 'Content-type': 'application/json', 'Accept': 'application/json' } def gen_ip(): a = random.randint(1, 254) b = rando...
2,026
751
# Copyright (c) 2017 Ansible Tower by Red Hat # All Rights Reserved. def filter_insights_api_response(json): new_json = {} ''' 'last_check_in', 'reports.[].rule.severity', 'reports.[].rule.description', 'reports.[].rule.category', 'reports.[].rule.summary', 'reports.[].rule.ansible_fix...
1,572
495
#!/usr/bin/env python # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import filecmp import optparse import os.path import platform import re import subprocess import sys _VULKAN_HEADER_FILE = "third_part...
16,211
6,326
def alternate_elements(lst1, lst2): assert len(lst1) == len(lst2) def alt(lst1, lst2): for idx in range(len(lst1)): yield lst1[idx], lst2[idx] return list(alt(lst1, lst2)) if __name__ == "__main__": lst1 = ["a", "b", "c"] lst2 = [1, 2, 3] correct = list(zip(lst1, lst2)) result = alternate_elements(lst1, ls...
411
180
import unittest import dockermake.cli class CliTest(unittest.TestCase): def test_parse_no_push(self): _, args = dockermake.cli.parse(['-n']) self.assertTrue(args.no_push) self.assertFalse(args.dry_run) self.assertFalse(args.purge) self.assertFalse(args.summary) sel...
1,970
687
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str = None price: float tax: float @app.get('/') async def root(): return {'message': 'Hello Fast API!'} @app.get('/items/{item_id}') def read_item(item_id): return {'i...
405
141
from django.core.management.base import BaseCommand from core.models import Trip from datetime import datetime, timedelta class Command(BaseCommand): help = 'Expires trip objects which are out-of-date' def handle(self, *args, **options): print("here") Trip.objects.filter(start_time__lte=date...
359
108
while True: print('\nSelecione a opção desejada: ') opção = int(input('1 - Juros simples \n2 - Juros compostos \n3 - Sair \n\nOpção desejada: ')) if opção == 3: break if opção != 1 and opção != 2: print('Opção inválida, selecione uma opção disponível') continue deposito = ...
1,258
480
#!/usr/bin/env python import os import rospy import threading from waitress import serve from flask import Flask from flask_ask import Ask, question, statement from std_msgs.msg import String,Bool from sensor_msgs.msg import NavSatFix start_flag =False e_stop_flag =False app = Flask(__name__) ask = Ask(app, "/") #NEWC...
3,838
1,393
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Menu', fields=[ ('id', models.AutoField(verbose...
1,999
557
# Generated by Django 2.0.9 on 2018-10-23 11:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('yekpay', '0002_auto_20181023_1458'), ] operations = [ migrations.AlterField( model_name='transaction', name='fromCur...
1,098
406
from fastapp.plugins.datastore.tests import * import unittest import os from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from fastapp.plugins import call_plugin_func from fastapp.tests import BaseTestCase from fastapp.plugins.models import PluginUserCo...
940
299
import sys def my_except_hook(exctype, value, traceback): print('There has been an error in the system') sys.excepthook = my_except_hook import warnings if not sys.warnoptions: warnings.simplefilter("ignore") import parselmouth from parselmouth.praat import call, run_file import glob import errno import csv...
10,730
4,484
import pisqpipe as pp import minimax """ This file is adapt from the example.py file provided. The only thing changed here is the brain_turn method which uses the minimax with alpha–beta pruning algorithm now. """ MAX_BOARD = 100 board = [[0 for i in range(MAX_BOARD)] for j in range(MAX_BOARD)] ...
4,199
1,559
import copy, sys from mod.MVVlStd import (glSep_s, mInP_FltAVali_fefi, mMenu_c, mSupportsWrite_ca, mCre_SFrFloat_ff) # from mod.MVVlStd import glSep_s, mInP_FltAVali_fefi, mMenu_c mOutStt_d = dict(kAccSum_n=0, kBuyHstT_l=[]) def mA_RefillAcc_ffmp(laSf_o, file=sys.stdout): # loAdd_n = mInP_FltAVali_fefi(f' Введи...
5,518
2,929
"""SegmentationNN""" import torch import torch.nn as nn from torchvision import models class SegmentationNN(nn.Module): def __init__(self, num_classes=23, hparams=None): super().__init__() self.hparams = hparams self.num_classes = num_classes ######################################...
3,800
1,098
# Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). # # Example 1: # # Input: [3, 2, 1] # # Output: 1 # # Explanation: The third maximum is 1. # # # # Example 2: # # Input: [1, 2] # # Output: 2...
2,363
894
''' TODO: add THERMAL_GENL_ATTR_EVENT structure ''' from pr2modules.netlink import genlmsg from pr2modules.netlink.nlsocket import Marshal from pr2modules.netlink.event import EventSocket THERMAL_GENL_CMD_UNSPEC = 0 THERMAL_GENL_CMD_EVENT = 1 class thermal_msg(genlmsg): nla_map = (('THERMAL_GENL_ATTR_UNSPEC', 'n...
650
265
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from tree_sitter import Language Language.build_library( # Store the library in the `build` directory 'evaluation/CodeBLEU/parser/my-languages.so', # Include one or more languages [ "third_party/tree-sitter-java", ...
363
116
import soco class SonoserException(Exception): pass class SonoserPlaylistNotFoundException(SonoserException): pass class SonoserZoneNotFoundException(SonoserException): pass class SonosAccessor: def __init__(self): self.zones = [zone for zone in soco.discover()] self.playlists = ...
1,052
329
from dataclasses import dataclass from typing import Dict, List, Union from bridger.enums import Operator @dataclass(unsafe_hash=True) class Condition: operator: Operator value: Union[str, float, int, bool] def __post_init__(self): if self.operator == Operator.EXISTS: assert isinstan...
1,464
415
# Migration to convert all tables and text columns as of 2020-07-22 to utf8mb4 from django.db import migrations class Migration(migrations.Migration): dependencies = [ # Go after this converstion in MyLA ('dashboard', '0015_auto_20200116_1408'), # Django dependencies ('sites', '0...
10,572
3,825
""" Evolution Strategies (Salimans 2017), evaluated by default on a random set of 20 environments at each iteration. The environment set can be specified with a pickle file, using --load_env. """ from Utils.Loader import resume_from_folder, prepare_folder from Utils.Stats import bundle_stats, append_stats from Algorit...
7,585
2,407
import os from setuptools import find_packages, setup setup( name='unicorn', version='0.0.1', license='MIT', entry_points={ 'console_scripts': [ 'unicorn = unicorn.__main__:main', ], }, packages=find_packages(), install_requires=[ 'elasticsearch>=6.0.0,<7...
426
151
"""Abstract class for PipelineTask""" from dataclasses import dataclass from typing import Any, Callable, Dict, List from pypelines import utils from pypelines.pipeline_options import PipelineOptions @dataclass class TaskInputSchema: """Schema for task input""" name: str default_value: str = None al...
4,748
1,297
import collections from timm.models.vision_transformer import _init_vit_weights, trunc_normal_ import torch.nn as nn from functools import partial import torch from everything_at_once.model.utils.layers import FusionBlock class FusionTransformer(nn.Module): def __init__(self, embed_dim=768, depth=1, num_heads=12...
4,370
1,389
import os from functools import lru_cache from pydantic import BaseSettings class Settings(BaseSettings): API_URL: str = str(os.getenv("API_URL", "http://localhost:8000")) LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO") API_KEY_HEADER: str = os.getenv("API_KEY_HEADER", "X-Api-Key") API_KEY: str = os....
696
260
import os def get_dir_files(dir_path): files = [file for file in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, file))] return sorted(files) def create_dir_if_not_exists(dir_path): if not os.path.exists(dir_path): os.makedirs(dir_path) def remove_dir(dir_path): for file in o...
484
187
from lettuce import step, world from selenium.webdriver.common.keys import Keys import time @step("I'm on Google") def step_impl(step): world.browser.get("https://www.google.com/ncr") world.browser.maximize_window() @step("I search for BrowserStack") def step_impl(step): element = world.browser.find_eleme...
613
192
import torch import torch.nn as nn import pdb class QuantileLoss(nn.Module): def __init__(self, quantiles): super().__init__() self.quantiles = quantiles def forward(self, preds, target): assert not target.requires_grad assert preds.size(0) == target.size(0) losses = [...
963
321
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys import os import mudslide import mudslide.__main__ import mudslide.surface testdir = os.path.dirname(__file__) def print_problem(problem, file=sys.stdout): what = problem["what"] if what == "incorrect data": where = problem["wh...
7,141
2,542
from .board import * def kickoff_action(board: Board) -> Action: ball_vector = Vector.from_point( board.ball.position - board.controlled_player.position ) if ball_vector.length() < 0.1: return board.set_action(Action.ShortPass, Vector(-1, 0)) else: return board.set_action(None,...
347
114
from velocityhelper.api.deltamodel import DeltaModel from velocityhelper.api.dataio import DataIO from settings import DELTACALCSPATH import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class Delta(object): def __init__(self): self.gridPath = DELTACALCSPATH+...
4,076
1,161
import machine ARRAYSIZE = 20 class PinToWatch: def __init__(self, pin_number, pull_up=False): self.buffer = bytearray(ARRAYSIZE) self.copy = bytearray(ARRAYSIZE) self.index = 0 if pull_up: self.pin = machine.Pin(pin_number, machine.Pin.IN, ...
2,269
717
## uniq (UNIX style) ## 6 kyu ## https://www.codewars.com//kata/52249faee9abb9cefa0001ee import itertools def uniq(seq): # ans = [] return [list(g)[0] for k, g in itertools.groupby(seq)]
202
97
from __future__ import absolute_import, division import json from notebook.base.handlers import IPythonHandler import os import subprocess class PyflybyStatus(IPythonHandler): """ Checks if pyflyby is loaded by default in ipython session Return {"status": "loaded"} if included by default, else {"status":...
2,479
699
# -*- coding: utf-8 -*- # # Copyright (C) 2021 CERN. # # Invenio-Communities is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """Abstract database model for modelling community/record relationships.""" from invenio_db import db from ...
1,621
485
from enum import Enum class eFormNodeType(Enum): CHECKBOX = 0 COMBOBOX = 1 SCALARINPUT = 2 BUTTON = 3 def __str__(self): return self.value
169
68
#!/usr/bin/python3 import socket import sys import subprocess # Bind the socket to the port server_address = ('localhost', 10000) # Listen for incoming connections if __name__ == "__main__": print('starting up on %s port %s' % server_address) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creat...
1,214
460
import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if ret: cv2.imshow('WebCam', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
220
87
def main(): print("${app} template has been successfully installed!")
74
19
import math import random import emoji num = int(input('Digite um número: ')) raiz = math.sqrt(num) print('A raiz de {} é: {}'.format(num, math.floor(raiz))) #floor --> arrendonda pra baixo #ceil --> arredonda pra cima #from math import sqrt, floor, ceil #random - mostra numeros aleatorios entre 0 e 1 n1 = random.ra...
553
229
name = "aiowiki" from .wiki import * from .exceptions import *
63
22
import pathlib import pickle from datetime import datetime import pandas as pd from utils import count_ngrams, create_model PROCESSED_DATA_DIR = pathlib.Path('../data/processed/') def read_files(): so = pd.read_csv(PROCESSED_DATA_DIR / 'tokenized.csv') so = so.loc[so.text.dropna().index] return so def...
1,208
430
""" --- The Rows of Cakes --- Challenging Someone has decided to bake a load of cakes and place them on the floor. Our robots can't help but try to find a pattern behind the cakes' disposition. Some cakes form rows, we want to count these rows. A row is a sequence of three or more cakes if we can draw a straight line ...
2,584
860
import MeCab from lib.util import ReplaceText from lib.convert_dict import ConvertDictionary class PreFilter: def __init__(self, text: str, dictList: dict): self.mecab = MeCab.Tagger() self.text = text self.dictList = dictList self.c = ConvertDictionary() def pre_process(self):...
954
328
#-*- coding: utf-8 -*- import math import os import tensorflow as tf import numpy as np import pandas as pd import cPickle from tensorflow.models.rnn import rnn_cell import tensorflow.python.platform from keras.preprocessing import sequence from collections import Counter from cnn_util import * class Caption_Generato...
12,049
4,288
import requests import json import os def lambda_handler(event, context): print("--- Prisma High Alerts ---") send_alert(event) def send_alert(msg): if 'hasFinding' in msg: del msg['hasFinding'] if 'alertRemediationCli' in msg: del msg['alertRemediationCli'] if 'source' in msg: del msg['source...
1,972
631
import sys import os import os.path import show_status as ss import subprocess import datetime import shutil import pbs as sc from pbs import git from pbs import ls def cleanFolder(path): print('Removing folder ' + path) shutil.rmtree(path, ignore_errors=True) #==== C DOCS ==== def generateDocs(doxyFil...
2,199
697
import os import io import random import string import typing as t import json from jinja2 import Environment, PackageLoader, select_autoescape, contextfilter from markdown import Markdown # Markdown extensions extensions = [ "markdown.extensions.fenced_code", "markdown.extensions.footnotes", "markdown.ext...
11,715
3,568
""" Unit test for ModifierHandler. """ from django.test import TestCase from attributes.modifier import Modifier from attributes.modifier_handler import ModifierHandler from mock import Mock class ModifierHandlerTestCase(TestCase): BASE_VAL = 10 FLOAT_VAL = 0.5 ADD_MOD = { 'desc': "add mod...
4,838
1,501
import os from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from oauth2client.client import GoogleCredentials from google.colab import auth auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) def ls(): ...
911
288
import sys import os from os.path import join, exists import re import shutil import tempfile from io import StringIO import urllib.request, urllib.error, urllib.parse from invoke import task, run ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) SOURCE_DIR = join(ROOT_DIR, 'src') TEST_DIR = join(ROO...
10,507
3,664
from django.shortcuts import render from django.conf import settings from django.core.files import File from oscar.core.loading import get_class, get_classes, get_model ProductClass, Product, Category, ProductCategory = get_classes( 'catalogue.models', ('ProductClass', 'Product', 'Category', ...
1,232
408
""" Django settings for example project. Generated by 'django-admin startproject' using Django 1.8.18. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build pat...
4,787
1,499
# -*- coding: utf-8 -*- import requests import json from multiprocessing import Pool import time import os import sys def send(data, url, key): print data os._exit() class Sender(object): def __init__(self, batch_size=1): self.queue = [] self.sending = [] self.batch_size = batch...
1,043
341
from db import db from app import app """ Run Flask API in Heroku env """ db.init_app(app) @app.before_first_request def create_tables(): db.create_all() # if __name__ == "__main__": # app.run(port=5000, debug=True)
227
94
from index import TODFileInfo from calibrate import assign_files_to_processes files = [TODFileInfo(name, 0, 12, 12) for name in ('A.fits', 'B.fits', 'C.fits')] result = assign_files_to_processes([10, 10, 8, 8], files) ...
617
199
""" Sliding Window Feed Forward NN - a three-layer network that takes a feature vector, representing the weather and pollutant data from the past n hours, and outputs the predictions for the next hour's pollutant levels. Brief description of model ------------------------------ Input: a n-dimensional ve...
6,481
2,624
from .. import app from .captcha import captcha_api from .sms import sms_api # Register API buleprint app.register_blueprint(captcha_api) app.register_blueprint(sms_api)
173
62
from random import randint numeros = ((randint(1,10)), (randint(1,10)), (randint(1,10)), (randint(1,10)), (randint(1,10)), (randint(1,10))) print('Os números sorteados foram: ', end='') for c in numeros: print(c, end=' ') print(f'\nO maior numero foi: {max(numeros)}') print(f'O menor número fo...
340
134
from mylib import datasets from mylib import functions from mylib import links from mylib import training
110
29
# -*- coding: utf-8 -*- # # Copyright 2019 Google 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 requir...
36,966
10,408
# -*- coding: utf-8 -*- import scrapy from ..items import JazzScraperItem class JazzSpider(scrapy.Spider): name = "jazz" allowed_domains = ["umbriajazz.com"] start_urls = ( 'http://www.umbriajazz.com/pagine/programma-umbria-jazz', ) def parse(self, response): for days in response...
1,363
395
class Repeater: """ Environment which incentivizes the agent to act as if every turn is repeated twice. Whenever the agent takes an action, the environment determines: would the agent take the same action if every turn leading up to that action were doubled? If so, give the agent reward +1, othe...
810
265
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ riko.modules.truncate ~~~~~~~~~~~~~~~~~~~~~ Provides functions for returning a specified number of items from a stream. Contrast this with the tail module, which also limits the number of items, but returns items from the bottom of the stream. Examples: basic...
3,989
1,170
from datetime import date CURRENT_DATE = date.today().strftime("%Y-%m-%e") # FETCH_MEAL_RECORDS = 'SELECT * FROM app_slackuser;' FETCH_MEAL_RECORDS = f""" SELECT to_char(app_mealservice.date, 'DD-MM-YYYY'), app_mealservice.date_modified, app_mealservice.user_id, app_slackuser.firstname, app_slacku...
1,125
472
""" A module to interact with the JWQL postgresql database ``jwqldb`` The ``load_connection()`` function within this module allows the user to connect to the ``jwqldb`` database via the ``session``, ``base``, and ``engine`` objects (described below). The classes within serve as ORMs (Object-relational mappings) that ...
5,607
1,599
class Simulator(): def __init__( self, environment_generator: 'base.EnvironmentGenerator', agent: 'agents.Agent', view_model: 'view_models.ViewModel', num_scenarios: int, num_steps: int): self.environment_generator = environment_generator s...
1,080
276
import logging from flask import Flask from flask.logging import default_handler from app.api import api_bp from app.models import db from app.utils.middleware import log_request_params, log_response from app.webhook import telegram_bp from app.utils import multilog from app.utils.error import handle_exception from c...
1,639
553
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.template.loader import select_template from django.utils.translation import ugettext_lazy as _ from cms.plugin_pool import plugin_pool from shop import settings as shop_settings from .plugin_base import ShopPluginBase class ShopCatalogPlugin(...
1,233
358
''' ex023: Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. Ex: Digite um número: 1834 unidade: 4 dezena: 3 centena: 8 milhar: 1 ''' from colorise import set_color, reset_color cores = { 'azul':'\033[1;34m', 'limpa':'\033[m', 'branco':'...
911
403
import json; import requests; import pymongo; import requests from pymongo.collation import Collation cookies = { 'WTSesIDHx': '35g0w816vv3xtlw65ylmwa1n0-4vj2hm-2pmtm0', '_ga': 'GA1.2.1358434475.1548575832', 'WTSesIDx': '35g0iwwzs45qbi4mny20qb5mu-1bphsej-4at7mq', 'WTSesIDxC': '37d9cf2f6e016ee74acd070d8...
8,044
3,666
# 참고자료 # 모두를 위한 머신러닝/딥러닝 강의 # 홍콩과기대 김성훈 # http://hunkim.github.io/ml import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') print(hello) sess = tf.Session() print(sess.run(hello)) print(sess.run(hello).decode(encoding='utf-8'))
245
144
""" This file contains api routes corresponding to a friend relations on a data server. """ from urllib.parse import urlparse from flask import Blueprint, request from flask_jwt_extended import create_access_token, get_jwt_identity import requests from app.api import jwt_required_custom from app.api.utils import goo...
11,274
3,062
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LogisticRegression # from sklearn.tree import DecisionTreeClassifier # from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.model_...
16,013
5,540
import socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sock.sendto(b"Message", 'unix.sock')
110
44
''' Classes from the 'CoreDAV' framework. ''' try: from rubicon.objc import ObjCClass except ValueError: def ObjCClass(name): return None def _Class(name): try: return ObjCClass(name) except NameError: return None CoreDAVXMLElementGenerator = _Class('CoreDAVXMLElementGen...
6,955
2,262
# Licensed under a 3-clause BSD style license - see LICENSE ''' This module provides miscellaneous scripts, called in other parts of the cross-match framework. ''' import os import operator import numpy as np __all__ = [] def create_auf_params_grid(auf_folder_path, auf_pointings, filt_names, array_name, ...
14,601
4,565
from rest_framework import status, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes, parser_classes from .serializers import UserSerializer from rest_framework import permissions from .models import User from rest_framework.parsers import MultiPar...
4,812
1,376
# Algorithms > Strings > Strong Password # How many characters should you add to make the password strong? # # https://www.hackerrank.com/challenges/strong-password/problem # numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" special_characters = "!@#$%^&*()-+" ...
943
352
a = 1 b = 2 n = int(input()) if n == 1: print(a) elif n == 2: print(b) else: for cnt in range(n - 2): c = a + b a = b b = c print(c)
178
85
import numpy as np import scipy as sp import scipy.special import tensorflow as tf from scipy.optimize import brentq @tf.function def tf_spherical_bessel_jn_explicit(x, n=0): r"""Compute spherical bessel functions :math:`j_n(x)` for constant positive integer :math:`n` explicitly. TensorFlow has to cache the f...
10,207
3,950
# credits to @NotThatMF on telegram for chiaki fast api # well i also borrowed the base code from him from pyrogram import Client, filters from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message from .. import BOT_NAME, HELP_DICT, TRIGGERS as trg from ..utils.data_parser imp...
1,915
708
import difflib import os from typing import Optional, Tuple from ecr.lib.judger import DataItem, JudgeResult, trimLineEnd, getFileContents, judged from ecr.lib.console import info, error, write dataPath = "./data" def judgeOne(std: DataItem, out: DataItem) -> Tuple[JudgeResult, Optional[str]]: diff = difflib.co...
1,595
502
def mean_bpm(num_beats, duration, inmin=None): """Find the average heart rate (in bpm) for a given ECG signal Args: num_beats: number of detected heart beats in an ECG strip duration: the duration of the ECG signal (in seconds) Returns: bpm: average heart rate i...
814
266
from . import bash, functional from .functional import cfg_tobool from .io import NativeIO from .util.system import (make_fofn_abs, make_dirs, cd) import json import logging import logging.config import os import re import io import sys import tempfile import time import uuid logger = logging.getLogger(__name__) from...
20,627
7,056
import sys sys.path.append("../training/") from next_util_classes import PreTrainingFindModuleDataset, BaseVariableLengthDataset, TrainingDataset import torch tokens = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 34, 45, 17, 5, 6], [1, 432, 343, 953, 349, 3940, 3993, 33, 22, 111, 2349, 3490], ...
4,680
2,569
from .result import ok, bad from .blame import Blame from .decider import Decider from .example_base import Example, ExampleDecider from .example_constraint import ExampleConstraintDecider
189
48
""" Synaplexus Trainer Script """ import os import snpx import numpy as np from snpx_arg_parser import snpx_parse_cmd_line_options def main(): args = snpx_parse_cmd_line_options() classifier = snpx.get_classifier(args) classifier.train(num_epoch = args.num_epoch, batch_size = a...
1,499
564
from chroma_agent.plugin_manager import DevicePlugin class FakeControllerDevicePlugin(DevicePlugin): def _read_config(self): import json return json.loads(open("/root/fake_controller.json").read()) def start_session(self): return self._read_config() def update_session(self): ...
351
99
# To increment version # Check you have ~/.pypirc filled in # git tag x.y.z # git push && git push --tags # rm -rf dist; python setup.py sdist bdist_wheel # TEST: twine upload --repository-url https://test.pypi.org/legacy/ dist/* # twine upload dist/* from setuptools import setup, find_packages import sys if sys.vers...
1,339
468
from fontParts.base.lib import BaseLib class Lib(BaseLib): def __init__(self, **kwargs): self._dict = {} super(BaseLib, self).__init__(self, **kwargs) def _set_glyph(self, glyph): self._dict["glyph"] = glyph def _getItem(self, attr): if not attr in self._dict: ...
560
181