text
string
size
int64
token_count
int64
""" The tool to check the availability or syntax of domain, IP or URL. :: โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ•šโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆ...
12,781
4,023
from malaya_speech.utils import ( check_file, load_graph, generate_session, nodes_session, ) from malaya_speech.model.tf import UNET, UNETSTFT, UNET1D def load(model, module, quantized=False, **kwargs): path = check_file( file=model, module=module, keys={'model': 'model.pb...
1,938
621
# Use this command if numpy import fails: sudo apt-get install python-dev libatlas-base-dev # If this doesn't work, uninstall both numpy and scipy. Thonny will keep an older default version of numpy. # Install an older version of scipy that corresponds to the correct version of numpy. from guizero import App, PushButt...
4,618
1,713
# -*- coding: utf-8 -*- from array import array def lcsubstrings(seq1, seq2, positions=False): """Find the longest common substring(s) in the sequences `seq1` and `seq2`. If positions evaluates to `True` only their positions will be returned, together with their length, in a tuple: (length, [(start pos in s...
1,182
551
# -*- coding: utf-8 -*- """ Defines the unit tests for the :mod:`colour.models.rgb.transfer_functions.\ panasonic_vlog` module. """ import numpy as np import unittest from colour.models.rgb.transfer_functions import ( log_encoding_VLog, log_decoding_VLog, ) from colour.utilities import domain_range_scale, ign...
6,072
2,401
########################################################################## # # Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
3,546
1,134
""" Unit tests for measure """ # Import package, test suite, and other packages as needed import numpy as np import molecool import pytest def test_calculate_distance(): """Sample test to check calculate_distance is working """ r1 = np.array([1, 0, 0]) r2 = np.array([3, 0, 0]) expected_dist...
2,164
855
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ test_util_matrix @author: jdiedrichsen """ import unittest import pyrsa.util as rsu import numpy as np class TestIndicator(unittest.TestCase): def test_indicator(self): a = np.array(range(0, 5)) a = np.concatenate((a, a)) X = rsu.matrix...
1,240
507
"""------------------for Washer""" import datetime import enum import time import logging from typing import Optional from .device import ( Device, DeviceStatus, STATE_UNKNOWN, STATE_OPTIONITEM_ON, STATE_OPTIONITEM_OFF, ) from .washer_states import ( STATE_WASHER, STATE_WASHER_ERROR, W...
6,999
2,286
from pathlib import Path def read(filename='in'): file_path = Path(__file__).parent / filename with file_path.open('r') as file: return read_lines(file.readlines()) def read_lines(lines): cells = {} for y in range(len(lines)): line = lines[y].strip() for x in range(len(line))...
375
121
import argparse import os class ArgumentParser(argparse.ArgumentParser): def __init__(self, description='base', **kwargs): super(ArgumentParser, self).__init__(description=description) def add_arguments(self): home = os.path.expanduser('~') self.add_argument('model', type=str) ...
4,644
1,475
# Copyright 2019 The SQLNet Company GmbH # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, ...
2,210
634
## Copyright 2014 Cognitect. All Rights Reserved. ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable...
870
282
import pandas as pd import matplotlib.pyplot as plt #ํ•œ๊ธ€ ํฐํŠธ ์˜ค๋ฅ˜ ์ œ๊ฑฐ from matplotlib import font_manager,rc font_path ="D:/5674-833_4th/part4/malgun.ttf" font_name = font_manager.FontProperties(fname=font_path).get_name() rc('font',family = font_name) df = pd.read_excel('D:/5674-833_4th/part4/์‹œ๋„๋ณ„ ์ „์ถœ์ž… ์ธ๊ตฌ์ˆ˜.xlsx',engine = 'o...
1,779
1,160
import os from jinja2 import Environment, FileSystemLoader QUERIES_DIR = os.path.dirname(os.path.abspath(__file__)) def get_query(query_name, params): j2_env = Environment(loader=FileSystemLoader(QUERIES_DIR+"/queries"), trim_blocks=True) return j2_env.get_template(query_name+'.sql')....
365
122
import matplotlib.pyplot as plt import pyaudio, wave import numpy as np from collections import OrderedDict as OD from struct import pack from math import fmod from os import system def getNoteAndDuration(chord : str, defaultDuration : float): if ',' in chord: note,duration = chord.strip('()').split(',') ...
8,507
3,898
from setuptools import setup from setuptools import find_packages from lagom.version import __version__ # Read content of README.md with open('README.md', 'r') as f: long_description = f.read() setup(name='lagom', version=__version__, author='Xingdong Zuo', author_email='zuoxingdong@hotmail.co...
1,603
437
import os import time import pyautogui # from voiceassmain import play_voice_assistant_speech from vacore import VACore # based on EnjiRouz realization https://github.com/EnjiRouz/Voice-Assistant-App/blob/master/app.py # ั„ัƒะฝะบั†ะธั ะฝะฐ ัั‚ะฐั€ั‚ะต def start(core: VACore): manifest = { "name": "ะ’ะธะบะธะฟะตะดะธั (ะฟะพะธัะบ)"...
2,046
674
# Django from django.urls import include, path # Django REST Framework from rest_framework.routers import DefaultRouter # Views from .views import tasks as task_views router = DefaultRouter() router.register(r'tasks', task_views.TaskViewSet, basename='task') urlpatterns = [ path('', include(router.urls)) ]
316
94
import enum from typing import Any, List, Optional, Tuple class ArmorType(enum.Enum): LIGHT = enum.auto() MEDIUM = enum.auto() HEAVY = enum.auto() def __repr__(self): return '%s.%s' % (self.__class__.__name__, self.name) class Armor: def __init__(self, name: str, armor_class: int, ...
7,936
2,623
import importlib.metadata import logging import os import shutil from typing import Dict, Any, List import click from sqlalchemy import text from dbd.log.dbd_exception import DbdException from dbd.config.dbd_profile import DbdProfile from dbd.config.dbd_project import DbdProject from dbd.executors.model_executor impo...
7,094
2,133
from rest_framework import serializers from bestiary import models class GameItemSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = models.GameItem fields = [ 'id', 'com2us_id', 'url', 'n...
9,901
2,887
# Copyright Abel Garcia. All Rights Reserved. # https://github.com/abel-gr/AbelNN import numpy as np import copy as copy import random import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from pylab import text import math class ConvNetAbel: version = 1.2 def __init__(self, hidd...
56,761
17,025
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import logging ENV_VAR_ROOT = "IG_SERVICE" CONFIG_FILE_NAME = "trading_ig_config.py" logger = logging.getLogger(__name__) class ConfigEnvVar(object): def __init__(self, env_var_base): self.ENV_VAR_BASE = env_var_base def _env_var(self, key): ...
1,365
429
# Example usage: # python train.py --device cuda --epochs 10 --input /home/miguelv/data/in/train/ --output /home/miguelv/data/out/delete/test/25/ import os, time, torch, json import numpy as np import nibabel as nib from lib.utils import * from lib.losses import Loss from torch.utils.data import DataLoader from dateti...
6,434
1,975
import numpy as np from toml_parser import Parser from scipy.sparse.csgraph import dijkstra, csgraph_from_dense from sklearn.metrics.pairwise import nan_euclidean_distances from math import sqrt class Graph(object): def __init__(self, transactions, weighted=True): config = Parser("config.toml").load() self._ma...
2,053
826
from skrf.vi.vna import rs_zva class Analyzer(rs_zva.ZVA): DEFAULT_VISA_ADDRESS = "GPIB::16::INSTR" NAME = "Rhode & Schwartz ZVA" NPORTS = 4 NCHANNELS = 32 SCPI_VERSION_TESTED = ''
203
98
def container_image_is_external(biocontainers, app): """ Return a boolean: is this container going to be run using an external URL (quay.io/biocontainers), or is it going to use a local, named Docker image? """ d = biocontainers[app] if (('use_local' in d) and (d['use_local'] is True)): ...
1,507
429
#!/usr/bin/env python # -*- coding: utf-8 -*- """ episode, season, disc, episode_count, season_count and episode_details properties """ import copy from collections import defaultdict from rebulk import Rebulk, RemoveMatch, Rule, AppendMatch, RenameMatch from rebulk.match import Match from rebulk.remodule import re fr...
37,531
10,991
""" Run heterodyne pre-processing of gravitational-wave data. """ import ast import configparser import copy import os import shutil import signal import sys import tempfile from argparse import ArgumentParser import cwinpy import numpy as np from bilby_pipe.bilbyargparser import BilbyArgParser from bilby_pipe.job_cr...
76,767
20,277
import flask import functools import bs4 import urllib.parse from .. import auth from .. import themes from .. import settings INVALID_PERMISSIONS_FLASH_MESSAGE = "Sorry, you don't have permission to view that page." def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.se...
5,787
1,514
#!/usr/bin/env python3 # This is bot coded by Abhijith N T and used for educational purposes only # https://github.com/AbhijithNT # Copyright ABHIJITH N T # Thank you https://github.com/pyrogram/pyrogram from pyrogram.types import ( InlineKeyboardMarkup, InlineKeyboardButton ) def server_select(): upload...
1,542
431
import logging import operator import storymarket from django import forms from django.core.cache import cache from django.conf import settings from .models import SyncedObject # Timeout for choices cached from Storymarket. 5 minutes. CHOICE_CACHE_TIMEOUT = 600 log = logging.getLogger('django_storymarket') class Sto...
4,022
1,018
import pickle from collections import OrderedDict from datetime import datetime from .chunk import Chunk from .review import Review from .tokenizer import LineTokenizer from .utils import norm_path from .database.snippet import maybe_init, Snippet as DataSnippet class Snippet(object): def __init__(self, snippet...
5,773
1,818
# default_app_config = '.apps.WorkflowConfig'
46
16
####<i>This sample will show how to convert several HTML documents to PDF and merge them to one document</i> #Import of classes from libraries import base64 import os import shutil import random import time from pyramid.renderers import render_to_response from groupdocs.StorageApi import StorageApi from groupdocs.Asy...
6,361
1,655
# Copyright (c) 2015 Presslabs SRL # # 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 writ...
2,503
766
import os import fecfile import json import csv import sys from settings import RAW_ELECTRONIC_DIR, MASTER_HEADER_ROW, HEADER_DUMP_FILE START_YEAR = 2019 ERROR_HEADERS = ['path', 'error', ] def readfile(filepath, writer): filename = os.path.basename(filepath) filename = filename.replace(".fec", "") f...
3,117
985
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url urlpatterns = patterns('collector.views', url(r'^blob404/$', 'blob404'), url(r'^deleted/$', 'deleted'), url(r'^$', 'create'), url(r'^(?P<uid>\w+)/$', 'delete'), ) # Local Variables: # indent-tabs-mode: nil # End: # vim: ai et...
331
143
#-*- coding: utf-8 -*- """ Dispersion calculation functions """ import numpy # module for array manipulation import pandas # module for general data analysis import os # module for general OS manipulation import scipy # module for scientific manipulation and analysis ## def set_transverse_mo...
7,658
2,681
import numpy as np from data_prep import data import spotipy from spotipy.oauth2 import SpotifyClientCredentials from os import getenv client_id = getenv('CLIENT_ID') client_id_secret = getenv('CLIENT_ID_SECRET') manager = SpotifyClientCredentials( client_id = client_id, client_secret= client_id_secret) ...
1,280
416
""" categories: Modules,array description: Array deletion not implemented cause: Unknown workaround: Unknown """ import array a = array.array('b', (1, 2, 3)) del a[1] print(a)
176
65
# !/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Time : 2019/9/17 15:07 @Author : Jay Chen @FileName: models.py @GitHub : https://github.com/cRiii """ from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from jaysblog.extensions import db from flask_login...
10,001
3,894
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root: 'TreeNode', sum: 'int') -> 'bool': if not root: return False def helper(node,val):...
602
169
#!/usr/bin/env python # coding: utf-8 import yaml import json import sys import os sys.path.append('../venv/lib/python3.5/site-packages') from elasticsearch import Elasticsearch sys.path.append('../telemanom') class Config: '''Loads parameters from config.yaml into global object''' def __init__(self, path...
1,509
440
from nanome._internal._util._serializers import _StringSerializer from nanome._internal._util._serializers import _TypeSerializer class _OpenURL(_TypeSerializer): def __init__(self): self.string = _StringSerializer() def version(self): return 0 def name(self): return "OpenURL" ...
508
140
print("********************************") print("********** QUESTรƒO 01 **********") print("********************************") print("******** RAUL BARCELOS *********") print() print("Olรก mundo")
196
55
import logging from CorpusToolkit.ply_parser import make_parser, lexer logging.basicConfig( level=logging.DEBUG, filename="parselog.txt", filemode="w", format="%(filename)10s:%(lineno)4d:%(message)s" ) log = logging.getLogger() test_data = ( "19980101-01-001-002/m ไธญๅ…ฑไธญๅคฎ/nt ๆ€ปไนฆ่ฎฐ/n ใ€/wu ๅ›ฝๅฎถ/n ไธปๅธญ/...
2,772
2,074
"""Helper functions for Philips Hue v2.""" from __future__ import annotations def normalize_hue_brightness(brightness: float | None) -> float | None: """Return calculated brightness values.""" if brightness is not None: # Hue uses a range of [0, 100] to control brightness. brightness = float((...
978
312
from .errors import IncapBlocked, MaxRetriesExceeded, RecaptchaBlocked from .parsers import ResourceParser, WebsiteResourceParser, IframeResourceParser from .session import IncapSession
186
48
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
3,646
1,057
from collections import deque class Solution: def longestValidParentheses(self, s: str) -> int: if len(s) == 1 or s == '': return 0 opened = deque() for i,p in enumerate(s): if p == '(': opened.append(i) else: if opened: if s[opened...
744
211
''' Flask Application Config ''' import os from logging.config import dictConfig BASEDIR = os.path.abspath(os.path.dirname(__file__)) class Config: '''๊ณตํ†ต Config''' JWT_SECRET_KEY = os.environ.get('FLASK_JWT_SECRET_KEY') # test only TEST_ACCESS_TOKEN = os.environ.get('FLASK_TEST_ACCESS_TOKEN') ADM...
2,358
868
# example of average pooling from numpy import asarray from keras.models import Sequential from keras.layers import Conv2D from keras.layers import AveragePooling2D # define input data data = [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1,...
1,066
521
from django.db import models from django.core.validators import RegexValidator, ValidationError from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from smart_selects.db_fields import ChainedForeignKey, ChainedManyToManyField from ordered_model.models import OrderedModel ...
13,127
4,013
from django import forms from .models import Connection, KoboUser, KoboData from django.contrib.admin.widgets import FilteredSelectMultiple from django.db.models import Q class ConnectionForm(forms.ModelForm): class Meta: model = Connection exclude = [] widgets = { 'auth_pass':...
714
199
from odc.aws import ( ec2_metadata, ec2_current_region, botocore_default_region, auto_find_region, make_s3_client, s3_url_parse, s3_fmt_range, s3_ls, s3_ls_dir, s3_find, get_boto_session, get_creds_with_retry, s3_fetch, ) from odc.aws._find import ( s3_file_info,...
713
318
from log.logger import logger class SystemStage(object): """ Default stage object: creates a SystemStage for doing something """ @property def name(self): return "Need to replace name when inheriting" def __repr__(self): return "SystemStage '%s' Try %s.methods()" % ( ...
883
253
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
37,840
13,420
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. 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...
1,947
592
# _*_ coding:utf-8 _*_ import logging import re import app_config from bs4 import BeautifulSoup from shortcode import process_shortcode logging.basicConfig(format=app_config.LOG_FORMAT) logger = logging.getLogger(__name__) logger.setLevel(app_config.LOG_LEVEL) end_doc_regex = re.compile(ur'^\s*[Ee][Nn][Dd]\s*$', ...
5,580
1,634
""" Abdur-Rahmaan Janhangeer Skeleton of https://github.com/pyhoneybot/honeybot/ """ import time import os import socket directory = "irc" if not os.path.exists(directory): os.makedirs(directory) target = open(os.path.join(directory, "log.txt"), "w") def message_checker(msgLine): sendvar = "" global mut...
2,162
913
# coding: utf-8 """ Xenia Python Client Library Python Client Library to interact with the Xenia API. # noqa: E501 The version of the OpenAPI document: v2.1 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from xenia_python_client_library.configur...
5,494
1,629
################################################################################ # Create a Registration with the UI for a Role. # Each module's aushadha.py is screened for this # # Each Class is registered for a Role in UI # These can be used to generate Role based UI elements later. # # As of now string base role...
672
173
from turtle import * def rysuj(s): a = 720 / len(s) up = "bdfhklt" down = "gjpqy" numb = "0123456789" samogloski = "aeiouy" pu(); bk(360); pd() for elem in s: if elem in numb: prost(a, "green") elif elem in up: prost(a, "yellow") elif elem in ...
973
393
""" Define the Movie model """ from . import db from .abc import BaseModel, MetaBaseModel class Movie(db.Model, BaseModel, metaclass=MetaBaseModel): """ The Movie model """ __tablename__ = "movies" movie_id = db.Column(db.String(300), primary_key=True) title = db.Column(db.String(300)) author = ...
616
205
f""" Shell script tho reproduce results for BERTScores in data from WMT18/19 Metrics Shared task. """ import argparse import hashlib import logging import os import sys from typing import Any, Dict, Iterator, List import numpy as np import pandas as pd import sentencepiece as spm import torch from tqdm import tqdm fr...
17,963
5,854
import os os.makedirs('./img/', exist_ok=True) IMAGE_URL = "https://mofanpy.com/static/img/description/learning_step_flowchart.png" def urllib_download(): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, './img/image1.png') # whole document def request_download(): import requests ...
826
274
from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout import tensorflow.keras as keras import os import cv2 import numpy as np from sklearn.model_selection import train_test_split def data_prep(path, img_rows, img_cols, color): """ A function to preprocess ...
5,787
1,815
""" Oracle library """ import lib_common from lib_properties import pc def Graphic_colorbg(): return "#CC99FF" def EntityOntology(): return ( ["Db", "Schema", "Library"], ) # Ambiguity with tables, oracle or normal users. def MakeUri(dbName,schemaName,libraryName): return lib_common.gUriGen.UriMakeFromDict("ora...
895
320
"""Training method""" import argparse import json import os import pathlib from typing import Union import numpy as np import torch from torch.backends import cudnn import pytorch_lightning as pl import dgmvae.models as dvm from experiment import VAEUpdater def main(): # ------------------------------------...
4,104
1,359
from myhdl import Signal, intbv, block, always_comb, ConcatSignal import myhdl from collections import OrderedDict import keyword def _is_valid_name(ident: str) -> bool: '''Determine if ident is a valid register or bitfield name. ''' if not isinstance(ident, str): raise TypeError("expected str, b...
17,193
4,394
import random def read_fasta(path_in, path_out): fasta = list() append = fasta.append fasta_in = open(path_in, 'r') fasta_out = open(path_out, 'w') for index, line in enumerate(fasta_in): if not line.startswith('>'): line = line.strip().upper() line = clear_n(line) ...
1,429
451
"""Advanced Tensor slicing ========================== Utilities for advanced tensor slicing and batching operations. Reference --------- """ import tensorflow as tf def slice_within_stride(x, stride, si=0, ei=None, keepdims=True): """Select ``x[..., (i * stride + si):(i * stride + ei)]`` for each i. The te...
2,217
685
# Copyright (c) 2014 Simplistix Ltd # See license.txt for license details. from decimal import Decimal from testfixtures import RoundComparison as R, compare, ShouldRaise from unittest import TestCase from ..compat import PY2, PY3 class Tests(TestCase): def test_equal_yes_rhs(self): self.assertTrue(0.1...
5,168
2,270
"""***************************************************************************** * Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to ...
23,628
7,831
""" quant_test ~~~~~~ The quant_test package - a Python package template project that is intended to be used as a cookie-cutter for developing new Python packages. """
169
45
import re from django.utils.html import escape from django.utils.safestring import mark_safe from ..utils import Parameter class ExtendedParameter(Parameter): extract_re = re.compile(r"\%\(([\w\-]+)(?:\:([\w\-]+))?\)(s|(?:0?\.(\d+))?d|b)") extract_name_re = lambda name: re.compile(rf"\%\({name}(?:\:[\w\-]+)?\...
5,189
1,530
# -*- coding=utf-8 -*- # author: dongrixinyu # contact: dongrixinyu.89@163.com # blog: https://github.com/dongrixinyu/ # file: bare_embedding.py # time: 2020-06-12 11:27 import os import pdb import logging from typing import Union, Optional, Dict, Any, Tuple import torch import torch.nn as nn from torch.nn.utils.r...
3,644
1,279
import numpy as np from psyneulink import PredictionErrorDeltaFunction np.set_printoptions(suppress=True) def test_prediction_error_delta_first_run(): learning_rate = 0.3 stimulus_onset = 41 sample = np.zeros(60) sample[stimulus_onset:] = 1 reward_onset = 54 target = np.zeros(60) targe...
56,576
32,750
from datetime import datetime as dt from django.utils import timezone import uuid from django.contrib.auth import get_user_model from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view from company.utils import get_or_create_company from ...
22,823
6,100
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python x=5 print x def reassign(b): x=6 print x reassign(x) print x
127
56
from collections import namedtuple from dagster import check from dagster.config.config_type import ConfigType, ConfigTypeKind from dagster.config.field import Field from dagster.core.serdes import whitelist_for_serdes @whitelist_for_serdes class NonGenericTypeRefMeta(namedtuple('_NonGenericTypeRefMeta', 'key')): ...
6,632
1,980
from orator.migrations import Migration class CreateUsersTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('users') as table: table.integer('id') table.string('name') table.string('gender', 1) table....
624
174
from configparser import ConfigParser import os import json obj = {} config = ConfigParser() config.read(os.path.join(os.getenv("HOME"), ".aws", "credentials")) obj["MY_ACCESS_KEY"] = config.get("default", "aws_access_key_id", fallback="") obj["MY_SECRET_KEY"] = config.get("default", "aws_secret_access_key", fallback=...
387
136
######################################################### # ๆฏๆฏ”็އใฎๅทฎใฎๆคœๅฎš๏ผใ‚ฟใ‚คใƒ—1 ######################################################### import sys import math def error_usage(): sys.stderr.write("usage: " + sys.argv[0] + "\n") sys.stderr.write("\tใ“ใฎใƒ—ใƒญใ‚ฐใƒฉใƒ ใฏใ€4ใคใฎๅผ•ๆ•ฐใŒๅฟ…่ฆใงใ™ใ€‚\n\n") sys.stderr.write( "\t1.ๅฑžๆ€ง1ใฎn...
1,051
631
# coding=utf-8 import functools from flask import Flask, session from flask import redirect from flask import request, make_response from flask import render_template from flask import url_for from flask_bootstrap import Bootstrap # ๆ•ฐๆฎๅบ“ๅค„็† from db import * # json import json # ็”Ÿๆˆไธ€ไธชapp app = Flask(__name...
13,796
4,780
# Licensed under the MIT License from mymusichere import env class TestEnv: def test_get_config_from_env(self, monkeypatch): monkeypatch.setenv('CONFIG', 'value') assert env.get_str_config('config') == 'value' def test_get_secret_from_env(self, monkeypatch): monkeypatch.setenv('SECR...
1,462
472
# STL imports import random import logging import string import time import datetime import random import struct import sys from functools import wraps # Third party imports import numpy as np import faker from faker.providers import BaseProvider logging.getLogger('faker').setLevel(logging.ERROR) sys.path.append('.'...
2,943
1,101
import math import os import random import re import sys first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) m = int(first_multiple_input[1]) matrix = [] if (n>0 and m>0 and n<100 and m< 100): for _ in range(n): matrix_item = input() matrix.append(matrix_item) for...
524
187
# pylint: disable=C0111,R0902,R0904,R0912,R0913,R0915,E1101 # Smartsheet Python SDK. # # Copyright 2016 Smartsheet.com, 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....
4,495
1,284
import torch import torch.nn.functional as F import os.path as osp import json from torch_geometric.utils import precision, recall from torch_geometric.utils import f1_score, accuracy from torch.utils.tensorboard import SummaryWriter def train_epoch_classifier(model, train_loader, len_train, optimizer, device): m...
5,524
1,908
class Solution: def orchestraLayout(self, num: int, xPos: int, yPos: int) -> int: a, b = (min(xPos, num-1-yPos), 1) if yPos >= xPos else (min(yPos, num-1-xPos), -1) return (4*num*a - 4*a*a - 2*a + b*(xPos+yPos) + (b>>1&1)*4*(num-a-1))%9 + 1
260
126
# nuScenes dev-kit. # Code written by Holger Caesar, 2020. import argparse import gc import os import random from typing import List from collections import defaultdict import cv2 import tqdm from nuimages.nuimages import NuImages def render_images(nuim: NuImages, mode: str = 'all', ...
9,716
2,981
import re from configparser import ConfigParser from constants import PROJECT_FOLDER, RELEASE_LEVEL_DICT from release_type import ReleaseLevel, ReleaseType, value_from_key class VersionInfo: def __init__( self, major: int = 0, minor: int = 0, bugfix: int = 0, ...
10,868
3,298
# test_create_json_items_from_embark_xml.py 2/18/19 sm """ test create_json_items_from_embark_xml.py """ import sys import json import unittest import csv from xml.etree.ElementTree import ElementTree, tostring # add parent directory to path import os import inspect CURRENTDIR = os.path.dirname(os.path.abspath(inspec...
2,302
722
import os import sys cwd = os.getcwd() sys.path.append(cwd) import pickle import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from plot.helper import plot_task, plot_weights, plot_rf_z_max, plot_rf_quad, plot_vector_traj tasks = [ 'com_pos', 'com_vel', 'chassis_quat', 'ch...
3,000
1,078
from pyramid.httpexceptions import HTTPConflict from h.auth.util import client_authority from h.presenters import TrustedUserJSONPresenter from h.schemas import ValidationError from h.schemas.api.user import CreateUserAPISchema, UpdateUserAPISchema from h.services.user_unique import DuplicateUserError from h.views.api...
3,504
992
from kivy.logger import Logger from kivy.utils import platform __version__ = "2.3.2" _log_message = "KivyAuth:" + f" {__version__}" + f' (installed at "{__file__}")' __all__ = ("login_providers", "auto_login") Logger.info(_log_message)
239
91
from .user import *
20
7