text
string
size
int64
token_count
int64
# from binary_tree import * # # root = Node(8) # # root.insert(3) # root.insert(10) # root.insert(1) # root.insert(6) # root.insert(4) # root.insert(7) # root.insert(14) # root.insert(13) # node, parent = root.lookup(6) # print(node, parent) # root.print_tree() # # root.delete(10) # # root.print_tree() import tkinter...
5,388
1,777
import requests import json from concurrent.futures import ProcessPoolExecutor as Executor from concurrent.futures import ThreadPoolExecutor from time import sleep, time from couchbase.bucket import Bucket from cbagent.collectors import Latency, Collector from logger import logger from perfrunner.helpers.misc impor...
4,634
1,437
from jnpr.junos import Device from jnpr.junos.utils.config import Config def clean_routing_table(): device=Device (host='100.123.1.3', user='jcluser', password='Juniper!1') device.open() cfg=Config(device, mode='private') cfg.load(path='junos_configuration/clean_routes.conf', format='text') cfg.com...
370
136
""" Author : vakhet at gmail.com This script gets all your NPC names from the original rAthena folder and updates their lines in navi_npc_krpri.lub wherever matches the map_name and coords """ import re import os import random import sqlite3 NPC_match = r'^[\w\d_]+,\d+,\d+,\d+\tscript\t[\w\d_ -]+#*[...
5,000
1,900
from rpicarserver import ext class Extension(ext.Extension): name = "backlight"
85
27
"""Test nest diagnostics.""" from typing import Any from .conftest import ComponentSetup from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry THERMOSTAT_TYPE = "sdm.devices.types.THERMOSTAT" async def test_entry_diagnostics( hass, hass_client, ...
712
237
import pandas as pd import numpy as np df = pd.read_csv('poblacion.csv') pd.options.display.float_format = '{:,.1f}'.format df = pd.read_csv('poblacion.csv') df['year'] = pd.Categorical(df['year'].apply(str)) idx_filtro = df['Country'].isin(['Mexico','Panama']) df_filtro_country = df[idx_filtro] df_filtro_country =df...
556
228
from django.contrib.auth.models import User from django.db import models class Chv(models.Model): name = models.OneToOneField(User, on_delete=models.PROTECT, related_name='profile') age = models.IntegerField() phonenumber = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to...
3,477
1,149
# # Py-Alpha-AMD Registration Framework # Author: Johan Ofverstedt # Reference: Fast and Robust Symmetric Image Registration Based on Distances Combining Intensity and Spatial Information # # Copyright 2019 Johan Ofverstedt # # Permission is hereby granted, free of charge, to any person obtaining a copy of this softwa...
4,876
1,625
# Generated by Django 3.0.8 on 2020-07-28 12:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0004_product_product_image'), ] operations = [ migrations.AddField( model_name='product', name='discounted_p...
431
140
from math import factorial n = int(input('Digite um número, para obter seu fatorial: ')) print('{}! é {}'.format(n, factorial(n)))
131
45
#!/usr/bin/env python3 from setuptools import setup, Extension setup( ext_modules=[ Extension('bloom._hashc', ['bloom/_hashcmodule.c']) ])
157
55
#!/usr/bin/env python3 import atexit import logging import os import random import subprocess import sys import time import msgpack logger = logging.getLogger(__name__) def maybedecode(x): if hasattr(x, 'decode'): return x.decode() return x def mloads(x): return msgpack.loads(x, strict_map_key...
5,645
1,837
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------------------------------------------------- # INFO: # ----------------------------------------------------------------------------------------------------------------------- """ Author: Evan Hub...
11,093
3,292
#!/usr/bin/env python # -*- coding: utf-8 -*- import random from python_hll.hlltype import HLLType from python_hll.hll import HLL from python_hll.serialization import SerializationUtil """Unit tests for BitVector.""" def test_add_basic(): """ Tests basic set semantics of ``HLL.add_raw()``. """ # Ad...
4,948
1,900
from weixin.utils.WeiXinUtils import * # 5.主函数main() def hello(wxNames, atHours, atMinutes, cityCode): names = wxNames hours = atHours minutes = atMinutes number = cityCode g = getYMD() g1 = get_iciba_everyday_chicken_soup() # 天气接口的网站 number为城市编号 name = 'http://t.weather.sojson.com/ap...
4,792
1,894
from .models import Dealer from .models import Employee from .models import Customer from .models import Medicine from .models import Purchase from django.shortcuts import render from django.db import IntegrityError def home(request): return render(request, 'pharma/index.html') def dealerform(request): dict...
7,892
2,523
from django.shortcuts import render from .models import Profile # Create your views here. def home(request): profile=Profile.objects return render(request,'home.html',{'profile' : profile})
202
57
# Generated by Django 3.0.4 on 2021-03-20 12:41 import phone_field.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('books', '0022_auto_20210215_1053'), ] operations = [ migrations.AlterField( model_name='warehouse', ...
458
163
#!/usr/bin/env python # coding=utf-8 ''' Author: Shuangchi He / Yulv Email: yulvchi@qq.com Date: 2022-01-28 14:21:09 Motto: Entities should not be multiplied unnecessarily. LastEditors: Shuangchi He LastEditTime: 2022-04-06 11:40:23 FilePath: /Model_Inference_Deployment/src/PyTorch2ONNX/PyTorch2ONNX_Run_in_ONNX_RUNTIME...
6,912
2,512
import numpy as np import tensorflow as tf from sklearn.model_selection import StratifiedKFold # Set dataset seed np.random.seed(seed=842102) class SingletonDecorator: def __init__(self,klass): self.klass = klass self.instance = None def __call__(self,*args,**kwds): if self.instance ==...
2,085
647
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 14:03:52 2015 @author: jemanjohnson """ import numpy as np import matplotlib.pyplot as plt import os import scipy.io from sklearn import preprocessing from time import time from sklearn.preprocessing import MinMaxScaler # Image Reshape Function def img_as_array(img...
1,962
637
""" Tests for the finsignia.gae.controllers module. """ import os import sys from finsignia.gae import loader import unittest class ApplicationControllerTest(unittest.TestCase): def setUp(self): loader.load() from finsignia.gae import controllers class TestController(controllers.ApplicationController)...
1,767
504
from tweepypoll.tweepypoll import visualize_poll import pandas as pd import altair as alt def test_visualize_poll(): """Test visualize_poll on a dictionary input""" sample_poll_obj = [ { "text": "Important research!!!", "duration": 1440, "date": "2022-01-22T04:01:0...
2,074
710
""" Avahi Network Service Scripting """ import Queue import threading import avahi, dbus, gobject from dbus import DBusException from dbus.mainloop.glib import DBusGMainLoop __all__ = ["QuiltAvahiServer", "QuiltAvahiClient"] TYPE = '_quilt._tcp' class QuiltAvahiNode(object): """ Quilt Avahi Connection Nod...
5,629
1,625
from appium import webdriver from .utils import PATH desired_caps = dict( platformName='Android', platformVersion='10', automationName='uiautomator2', deviceName='Android Emulator', app=PATH('app/ApiDemos-debug.apk.zip') ) driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) ...
612
201
import json import os import argparse HOME = os.environ['HOME']+'/results/' parser = argparse.ArgumentParser(description="Python script generates the SCFiles using MSPIDs") parser.add_argument("-m", "--mspids", nargs="+", required=True, help="1 or more MSPIDs") parser.add_argument("-n", "--networkId", metavar='', req...
6,161
1,963
import re #Regular expression library from django import forms from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.template import RequestContext from django.contrib.auth.forms import AuthenticationForm from catalogue.models import Submitted from models import...
9,721
3,092
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def make_mlp(dim_list, activation='relu', batch_norm=True, dropout=0): # make_mlp主要是构造多层的全连接网络,并且根据需求决定激活函数的类型,其参数dim_list是全连接网络各层维度的列表 layers = [] for dim_in, dim_out in zip(dim_list[:-1], dim_list[1:]): layers....
38,343
14,211
#!/usr/bin/python # # Generates ipfixtypes.hh from IPFIX spec and schema # # Copyright (c) 2006 Mazu Networks, Inc. # # $Id: ipfixtypes.py,v 1.1 2006/05/12 16:43:44 eddietwo Exp $ # import xml.dom.minidom import sys import time class IPFIXField: """ Represents a <field> element in the IPFIX specification. Acc...
4,258
1,459
import enum class MediaType(enum.Enum): MEDIA_TYPE_WILDCARD = "*" WILDCARD = "*/*" APPLICATION_XML = "application/xml" APPLICATION_ATOM_XML = "application/atom+xml" APPLICATION_XHTML_XML = "application/xhtml+xml" APPLICATION_SVG_XML = "application/svg+xml" APPLICATION_JSON = "application/j...
694
266
# -*- coding: utf-8 -*- ''' Created on 24 Aug 2010 @author: Matthew Wilcoxson functions convert from one value to another in the form: def conversion(value): #do something return new_value ''' import time def convert_to_rdf_date(value): date_check = value # rdf uses format '1651-12-31T00:00:00...
2,940
1,154
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2018 QiaoPeng. # # Invenio 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 2 of the # License, or (at your option) any l...
992
339
from absl import app from absl import flags from absl import logging import csv import importlib import numpy as np import os.path as path import random from sklearn.model_selection import train_test_split import time from transformations.reader.matrix import test_argument_and_file, load_and_log import transformations...
11,305
3,601
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jan 10 09:45:23 2018 @author: www.github.com/GustavZ """ import os import sys import numpy as np from rod.config import Config from rod.helper import get_model_list, check_if_optimized_model from rod.model import ObjectDetectionModel, DeepLabModel RO...
2,610
862
# Copyright 2021, Robotics Lab, City College of New York # 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 ...
5,953
1,959
import sys def show_balance(balance): balance = '' print(" Has logged in!") print(" The current balance is " + str(balance)) def deposit(balance): print("Your current balance is: " + str(balance)) while True: deposit_amount = float(input("Enter deposit amount: ")) balance = f...
805
234
from bs4 import BeautifulSoup from ricecooker.classes import nodes class WHOPageScraperBase: def __init__(self, url, file_on_disk): self.url = url self.file_on_disk = file_on_disk def node_for_text_section(self, content): # print("content = {}".format(content.prettify())) pas...
2,098
613
from __future__ import absolute_import, division, print_function import six.moves.cPickle as pickle from glob import glob import os import pytest from dxtbx.model import Experiment, ExperimentList from dxtbx.model.experiment_list import ExperimentListFactory, \ ExperimentListDumper, ExperimentListDict def test_ex...
23,817
8,730
from sys import argv def make_new_reference_files(filename, sub1, sub2, divider=">chr9"): genomes = open(filename).read().split(divider) f = open(sub1, "w") f.write(genomes[0]) f.close() f = open(sub2, "w") f.write(">chr9"+genomes[1]) f.close() if __name__=="__main__": make_new_referen...
365
154
"""Module which defines collaborating app ids. This module is used by: settings.py scripts/deploy.sh """ import os # List of (playground appid, mimic app id, playground app id alias) _APP_ID_TUPLES = [ # production environment ('try-appengine', 'shared-playground', 'cloud-playground'), # developmen...
1,323
485
# 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 # d...
21,183
6,573
from sys import modules from importlib import import_module modules['server'] = import_module('src') from werkzeug.serving import run_simple from server.app import App from server.mode import Mode if __name__=='__main__': app = App(mode=Mode.Development) run_simple('localhost', 8000, app, use_reloader=Tr...
325
109
""" An abstraction layer for metadata fetchers. Supports both syncronous and asyncronous fetchers with cache. """ from .logs import get_log import os import requests from .constants import config from datetime import datetime from collections import deque import six from concurrent import futures import traceback fr...
6,891
1,968
from pychonet.EchonetInstance import EchonetInstance class HomeSolarPower(EchonetInstance): def __init__(self, netif, instance = 0x1): self.eojgc = 0x02 self.eojcc = 0x79 EchonetInstance.__init__(self, self.eojgc, self.eojcc, instance, netif) def getMeasuredInstantPower(self): ...
498
183
from IPython.core.magic import Magics, magics_class, line_cell_magic from sys import stdout from os import linesep from os.path import join, expanduser from adlmagics.version import adlmagics_version from adlmagics.converters.dataframe_converter import DataFrameConverter from adlmagics.utils.json_file_persister impo...
6,955
2,263
import asyncio import json from datetime import datetime, timedelta from aiohttp import web from .utils import read_body, get_week_times, get_formatted_time from ..data.models import RunRow from ..data.postgres_async_db import AsyncPostgresDB import logging class DashboardAPI(object): _run_table = None lock = ...
10,137
2,972
# -*- coding: utf-8 -*- from setup_teardown import start_db, stop_db from nose.tools import * from pykt import KyotoTycoon, KTException @raises(IOError) def test_err_report(): db = KyotoTycoon() db.report() @with_setup(setup=start_db,teardown=stop_db) def test_report(): db = KyotoTycoon() db = db.open...
838
332
import Resources import Colors import pygame screen = None def init(width, height): global screen screen = pygame.display.set_mode((width, height)) def width(): return screen.get_width() def height(): return screen.get_height() def res(): return (screen.get_width(), screen.get_height()) def ...
1,024
333
import re import datetime import bs4 from typing import Dict, Tuple, Optional, TYPE_CHECKING, ClassVar, Pattern, cast, Match, Any from .base import BaseMangaExtractor, MangaExtractorData from ..constants import STATUS_IDS, CENSOR_IDS if TYPE_CHECKING: from ..ext_info import ExternalInfo class ToonilyExtractor...
5,416
1,791
#!/usr/bin/env python3 import os.path import threading from .. import cryptfile from ..util import * from ..client import create_client from ..syncdir import FsProvider, FsListener class BlindFsListener(threading.Thread, FsListener): def is_stopping(self): return self.stop_requested.isSet() def __in...
10,965
2,945
#!/usr/bin/env python ####################################################### # Copyright (c) 2018, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ###############################...
3,587
1,323
import numpy as np from scipy.linalg import sqrtm from sklearn.preprocessing import StandardScaler def make_linear_regression(n_samples=10000, n_uncorr_features=10, n_corr_features=10, n_drop_features=4, include_intercept=True, ...
4,376
1,520
#!/usr/bin/env python3 # encoding: utf-8 """ fake-registration-server.py Created by nano on 2018-11-22. Copyright (c) 2018 VTRUST. All rights reserved. """ import tornado.web import tornado.locks from tornado.options import define, options, parse_command_line define("port", default=80, help="run on the given port", t...
1,735
647
import numpy as np import fast_carpenter.summary.binning_config as mgr from . import dummy_binning_descriptions as binning def test_create_one_region(): cfg = {"_" + k: v for k, v in binning.bins_nmuon.items()} _in, _out, _bins, _index = mgr.create_one_dimension("test_create_one_region", **cfg) assert _in...
1,998
785
from __future__ import division from constants import * import numpy as np import os precueITIs = np.random.exponential(standard_parameters['mean_iti_precue'], standard_parameters['n_targets']) + standard_parameters['min_iti_precue'] np.save('ITIs/precueITIs.npy',precueITIs) postcueITIs = np.random.exponential(standa...
671
232
''' PUT FUNCTION HERE !! Author Davinci ''' def helloworld(name): return "KDlearn :" + name
99
38
# Implementation of the Set ADT container using a Python list. class Set: # Creates an empty set instance. def __init__(self): self._theElements = list() # Returns the number of items in the set def __len__(self): return len(self._theElements) # Determines if an element is in the s...
4,122
1,133
from django.apps import AppConfig class ButtonsConfig(AppConfig): name = 'apps.buttons' verbose_name = 'Клавиши'
123
42
input() S=input() dot=S.count(".") ans=dot count=0 for s in S: if s=="#":count+=1 else:dot-=1 ans=(min(ans,count+dot)) print(ans)
141
65
from flask import (Blueprint, abort, flash, redirect, render_template, request, url_for) from flask_login import current_user, login_required from app import db from app.billing.forms import CreateBillingForm from app.models import Billing from sqlalchemy import desc billing = Blueprint('billing', ...
2,932
949
""" Author: Ryan Faulkner Date: October 19th, 2014 Container for mashup logic. """ import json import random from sqlalchemy.orm.exc import UnmappedInstanceError from flickipedia.redisio import DataIORedis from flickipedia.model.articles import ArticleModel, ArticleContentModel from flickipedia.config ...
9,120
2,687
from bluedot import BlueDot from gpiozero import PWMLED from signal import pause def set_brightness(pos): brightness = (pos.y + 1) / 2 led.value = brightness led = PWMLED(27) bd = BlueDot() bd.when_moved = set_brightness pause()
240
95
from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('<slug:post>/',views.post_detail,name="post_detail"), path('comment/reply/', views.reply_page, name="reply"), path('tag/<slug:tag_slug>/',views.post_list, name='post_tag...
328
119
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: tree, words, len_w = collections.defaultdict(set), set( wordList ), len(beginWord) if endWord not in words: return [] found, q, nextq = False, {beginWord...
1,313
354
import os from tempfile import TemporaryDirectory import codecs import logging from grizzled.file.includer import * from grizzled.os import working_directory from grizzled.text import strip_margin import pytest @pytest.fixture def log(): return logging.getLogger('test') def test_simple(log): outer = '''|Firs...
3,144
964
from output.models.nist_data.list_pkg.unsigned_short.schema_instance.nistschema_sv_iv_list_unsigned_short_min_length_2_xsd.nistschema_sv_iv_list_unsigned_short_min_length_2 import NistschemaSvIvListUnsignedShortMinLength2 __all__ = [ "NistschemaSvIvListUnsignedShortMinLength2", ]
286
107
from django.conf.urls import url from simple.localsite.views import example urlpatterns = [ url(r'example/', example), ]
127
41
from django.test import TestCase from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from tbconnect.models import TBCheck, TBTest from userprofile.models import Hea...
8,850
2,773
import nltk import random from preprocess import compile_corpus from nltk.translate import IBMModel1, AlignedSent, Alignment def run(filename, iterations): # global variables utilized in the assessment of the IBM Model global ibm1 global corpus # construct and modify corpus by adding the system alignm...
1,350
383
from os import environ, path from .server import Server from .config import configure def boot(create_dependencies): config_path = environ.get("PYAPP_CONFIG_PATH") or path.realpath( path.join(path.dirname(__file__), "..", "..", "config") ) server = Server(create_dependencies, config_path) ser...
374
111
# -*- coding: utf-8 -*- from checker.backends import BaseBackend from checker import logger log = logger.getLogger(__name__) class PagureBackend(BaseBackend): """for projects hosted on pagure.io""" name = 'Pagure' domain = 'pagure.io' example = 'https://pagure.io/pagure' def __init__(self, url...
1,027
348
import os import re from time import time from vial import vfunc, vim from vial.fsearch import get_files from vial.utils import get_projects, redraw MAX_FILESIZE = 10 * 1024 * 1024 def grep(query): matcher = re.compile(re.escape(query)) t = time() - 1 result = [] for r in get_projects(): f...
2,184
658
# -*- coding: utf-8 -*- """ Unit tests for new Project/Flight data classes, including JSON serialization/de-serialization """ import time from datetime import datetime from typing import Tuple from uuid import uuid4 from pathlib import Path import pytest import pandas as pd from dgp.core import DataType from dgp.cor...
3,619
1,368
from django.conf.urls import include, url from rest_framework.documentation import include_docs_urls from examples.rest import router from .views import index urlpatterns = [ url(r'^$', index, name='index'), url(r'^', include(router.urls)), url(r'^dynamicforms/', include('dynamicforms.urls')), url(r'^...
389
121
"""Test cases for concepts.""" from typing import Any import pytest import requests @pytest.mark.contract def test_get_concept_with_id(http_service: Any) -> None: test_id = "a683bc63-2961-46af-9956-8a4a3f991cc6" url = f"{http_service}/concepts/{test_id}" result = requests.get(url=url, headers={"accept": ...
1,312
514
''' Mostly these are internal imports related to django and rest_framework. The os and io imports are for creating files, paths and parsing bytes objects respectively ''' from django.db import models from django.contrib.auth.models import User from rest_framework.renderers import JSONRenderer from rest_framework.par...
4,572
1,186
#! /usr/bin/python # coding=utf-8 import struct import os import hashlib import Instruction Access_Flag = {'public': 1, 'private': 2, 'protected': 4, 'static': 8, 'final': 0x10, 'synchronized': 0x20, 'volatile': 0x40, 'bridge': 0x40, 'transient': 0x80, 'varargs': 0x80, 'native': ...
95,557
32,331
from rest_framework import serializers from api.models import User, UserProfile, Post, News, Video from datetime import datetime class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('address', 'country', 'city', 'zip', 'photo') class UserSerializer(...
1,852
502
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are m...
6,603
2,239
import markovify import re import nltk import os import urllib.request from shutil import copyfile # We need a temporary(ish) place to store the data we retrieve. # If you are running this in a docker container you may want to mount a volume and use it. # Also be sure to make a symlink between it and the assets direc...
5,344
1,812
import environs env = environs.Env() env.read_env() from wsgi_microservice_middleware.cors import CORSMiddleware from wsgi_microservice_middleware.request_id import ( RequestIdFilter, RequestIdMiddleware, current_request_id, RequestIdJsonLogFormatter ) __all__ = [ 'CORSMiddleware', 'Re...
427
150
import turtle as t import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 1 def next_level(): global STARTING_MOVE_DISTANCE STARTING_MOVE_DISTANCE += MOVE_INCREMENT class CarManager(t.Turtle): def __init__(self): super().__init...
686
271
""" Advent of code 2021 day 05 / 2 """ import math from os import path import re from collections import Counter class Code(object): def __init__(self, lines): self.lines = lines def printmap(self, dim, minx, miny, maxx, maxy): for i in range(miny, maxy + 1): ln = "" ...
3,329
1,113
""" Tissue Corrections ================== """ ################################################################################################### # .. _tutorial_removing_autoflourescence: # # Removing autofluorescence # ========================= # # In addition to the bright spots (signal) that we want to detect, micr...
2,032
588
from .alaska_temperature import AlaskaTemperature from .bmi import AlaskaTemperatureBMI __all__ = ["AlaskaTemperature", "AlaskaTemperatureBMI"]
146
51
import re t = int(input()) for i in range(0, t): chars = input() m1, m2 = [None] * len(chars), [None] * len(chars) for j in range(0, len(chars)): m1[j] = "3" if chars[j] == "4" else chars[j] m2[j] = "1" if chars[j] == "4" else "0" s1 = ''.join(m1) s2 = ''.join(m2) print("C...
378
177
#!/usr/bin/env python # coding: utf-8 # Scraper movies data from Imdb # In[ ]: import csv import pandas as pd # Year range to collect data. # In[ ]: startYear=int(input("startYear: ")) finishYear=int(input("finishYear: ")) # File path to save. Ex: C:\Users\User\Desktop\newFile # In[ ]: filePath = input("F...
1,645
614
""" @author: magician @file: descriptor_demo.py @date: 2020/1/14 """ from weakref import WeakKeyDictionary class Homework(object): """ Homework """ def __init__(self): self._grade = 0 @property def grade(self): return self._grade @grade.setter def grade(self, valu...
2,680
917
import torch import numpy as np import torch.nn.functional as F def masked_softmax(x, m=None, axis=-1): ''' x: batch x time x hid m: batch x time (optional) ''' x = torch.clamp(x, min=-15.0, max=15.0) if m is not None: m = m.float() x = x * m e_x = torch.exp(x - torch.max(x...
3,584
1,447
# -*- coding: utf-8 -*- """ create on 2019-03-20 04:17 author @lilia """ from sklearn.neighbors import KNeighborsClassifier from analysis_llt.ml.cv.base import BaseCV class KNNCV(BaseCV): fit_predict_proba_ = False def __init__(self, n_neighbors=5, cv=None, random_state=None, verbose=0, **model_params): ...
707
272
import threading from zds_client.oas import schema_fetcher def test_schema_fetch_twice(oas): schema = oas.fetch() assert isinstance(schema, dict) assert oas.mocker.call_count == 1 oas.fetch() # check that the cache is used assert oas.mocker.call_count == 1 def test_clear_caches_in_betwee...
1,066
364
""" Display tools for TTrees. """ from __future__ import annotations import dataclasses import functools from pathlib import Path from typing import Any, Dict import uproot from rich.console import Console from rich.markup import escape from rich.text import Text from rich.tree import Tree console = Console() __al...
4,165
1,435
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from apps.core.models import BaseModel from apps.core.utils import HASH_MAX_LENGTH, create_hash, truncate from django.utils.encoding import python_2_unicode_compat...
5,256
1,655
# Copyright 2019 Elasticsearch BV # # 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 applicabl...
2,650
891
# Copyright 2021 Roots # # 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, softwa...
1,811
502
import logging from sqlalchemy import create_engine, event from configuration import config as cnf from helpers.DbHelper import on_connect, db_session, assert_database_type from models import Base, Flow # from models.depreciated import Metric logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logg...
1,639
480
from tests.utils import W3CTestCase class TestFlexbox_Flex11Npercent(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flex-1-1-Npercent'))
166
66
# AARD: function: __main__ # AARD: #1:1 -> :: defs: %1 / uses: [@1 4:1-4:22] { call } 'value: {}'.format(3) # AARD: @1 = constant_attribute.py
150
75
from tensorflow.python.keras.layers import Layer from tensorflow.python.keras import backend as K class LayerNorm(Layer): def __init__(self, axis=-1, eps=1e-6, **kwargs): self.axis = axis self.eps = eps super(LayerNorm, self).__init__(**kwargs) def build(self, input_shape): i...
884
296